code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php use Spatie\Activitylog\ActivityLogger; use Spatie\Activitylog\ActivityLogStatus; if (! function_exists('activity')) { function activity(string $logName = null): ActivityLogger { $defaultLogName = config('activitylog.default_log_name'); $logStatus = app(ActivityLogStatus::class); return app(ActivityLogger::class) ->useLog($logName ?? $defaultLogName) ->setLogStatus($logStatus); } }
LALarsen/laravel-activitylog
src/helpers.php
PHP
mit
454
from __future__ import division, print_function import myhdl from myhdl import intbv, instance, delay from rhea.system import Barebone from . import SPIBus @myhdl.block def spi_controller_model(clock, ibus, spibus): """A model of an SPI controller Arguments: ibus (Barebone): internal bus spibus (SPIBus): SPI interface (SPIBus) """ assert isinstance(ibus, Barebone) assert isinstance(spibus, SPIBus) @instance def decode_ibus(): while True: yield clock.posedge if ibus.write: yield spibus.writeread(ibus.get_write_data()) yield ibus.acktrans(spibus.get_read_data()) elif ibus.read: yield spibus.writeread(0x55) # dummy write byte yield ibus.acktrans(spibus.get_read_data()) return decode_ibus class SPISlave(object): def __init__(self): self.reg = intbv(0)[8:] @myhdl.block def process(self, spibus): sck, mosi, miso, csn = spibus() @instance def gproc(): while True: yield csn.negedge bcnt = 8 while not csn: if bcnt > 0: miso.next = self.reg[bcnt-1] yield sck.posedge bcnt -= bcnt self.reg[bcnt] = mosi else: yield delay(10) return gproc
cfelton/rhea
rhea/cores/spi/spi_models.py
Python
mit
1,479
items_found_can_i_use = None can_i_use_file = None can_i_use_popup_is_showing = False can_i_use_list_from_main_menu = False path_to_can_i_use_data = os.path.join(H_SETTINGS_FOLDER, "can_i_use", "can_i_use_data.json") path_to_test_can_i_use_data = os.path.join(H_SETTINGS_FOLDER, "can_i_use", "can_i_use_data2.json") url_can_i_use_json_data = "https://raw.githubusercontent.com/Fyrd/caniuse/master/data.json" can_i_use_css = "" with open(os.path.join(H_SETTINGS_FOLDER, "can_i_use", "style.css")) as css_file: can_i_use_css = "<style>"+css_file.read()+"</style>" def donwload_can_i_use_json_data() : global can_i_use_file if os.path.isfile(path_to_can_i_use_data) : with open(path_to_can_i_use_data) as json_file: try : can_i_use_file = json.load(json_file) except Exception as e : print("Error: "+traceback.format_exc()) sublime.active_window().status_message("Can't use \"Can I use\" json data from: https://raw.githubusercontent.com/Fyrd/caniuse/master/data.json") if Util.download_and_save(url_can_i_use_json_data, path_to_test_can_i_use_data) : if os.path.isfile(path_to_can_i_use_data) : if not Util.checksum_sha1_equalcompare(path_to_can_i_use_data, path_to_test_can_i_use_data) : with open(path_to_test_can_i_use_data) as json_file: try : can_i_use_file = json.load(json_file) if os.path.isfile(path_to_can_i_use_data) : os.remove(path_to_can_i_use_data) os.rename(path_to_test_can_i_use_data, path_to_can_i_use_data) except Exception as e : print("Error: "+traceback.format_exc()) sublime.active_window().status_message("Can't use new \"Can I use\" json data from: https://raw.githubusercontent.com/Fyrd/caniuse/master/data.json") if os.path.isfile(path_to_test_can_i_use_data) : os.remove(path_to_test_can_i_use_data) else : os.rename(path_to_test_can_i_use_data, path_to_can_i_use_data) with open(path_to_can_i_use_data) as json_file : try : can_i_use_file = json.load(json_file) except Exception as e : print("Error: "+traceback.format_exc()) sublime.active_window().status_message("Can't use \"Can I use\" json data from: https://raw.githubusercontent.com/Fyrd/caniuse/master/data.json") Util.create_and_start_thread(donwload_can_i_use_json_data, "DownloadCanIuseJsonData") def find_in_can_i_use(word) : global can_i_use_file can_i_use_data = can_i_use_file.get("data") word = word.lower() return [value for key, value in can_i_use_data.items() if value["title"].lower().find(word) >= 0] def back_to_can_i_use_list(action): global can_i_use_popup_is_showing if action.find("http") >= 0: webbrowser.open(action) return view = sublime.active_window().active_view() can_i_use_popup_is_showing = False view.hide_popup() if len(action.split(",")) > 1 and action.split(",")[1] == "main-menu" : view.run_command("can_i_use", args={"from": "main-menu"}) else : view.run_command("can_i_use") def show_pop_can_i_use(index): global can_i_use_file global items_found_can_i_use global can_i_use_popup_is_showing if index < 0: return item = items_found_can_i_use[index] browser_accepted = ["ie", "edge", "firefox", "chrome", "safari", "opera", "ios_saf", "op_mini", "android", "and_chr"] browser_name = [ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IE", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;EDGE", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Firefox", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Chrome", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Safari", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Opera", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;iOS Safari", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Opera Mini", "&nbsp;&nbsp;&nbsp;Android Browser", "Chrome for Android" ] html_browser = "" html_browser += "<div>" html_browser += "<h1 class=\"title\">"+cgi.escape(item["title"])+" <a href=\""+item["spec"].replace(" ", "%20")+"\"><span class=\"status "+item["status"]+"\"> - "+item["status"].upper()+"</span></a></h1>" html_browser += "<p class=\"description\">"+cgi.escape(item["description"])+"</p>" html_browser += "<p class=\"\"><span class=\"support\">Global Support: <span class=\"support-y\">"+str(item["usage_perc_y"])+"%</span>"+( " + <span class=\"support-a\">"+str(item["usage_perc_a"])+"%</span> = " if float(item["usage_perc_a"]) > 0 else "" )+( "<span class=\"support-total\">"+str( "{:10.2f}".format(float(item["usage_perc_y"]) + float(item["usage_perc_a"])) )+"%</span>" if float(item["usage_perc_a"]) > 0 else "" )+"</span> "+( " ".join(["<span class=\"category\">"+category+"</span>" for category in item["categories"]]) )+"</p>" html_browser += "</div>" html_browser += "<div class=\"container-browser-list\">" i = 0 for browser in browser_accepted : browser_versions = can_i_use_file["agents"] stat = item["stats"].get(browser) stat_items_ordered = list() for k in stat.keys() : if k != "TP" : stat_items_ordered.append(k) if len(stat_items_ordered) >= 1 and stat_items_ordered[0] != "all" : stat_items_ordered.sort(key=LooseVersion) stat_items_ordered = stat_items_ordered[::-1] html_p = "<p class=\"version-stat-item\"><span class=\"browser-name\">"+browser_name[i]+"</span> : " j = 0 while j < len(stat_items_ordered) : if j == 7: break class_name = stat.get(stat_items_ordered[j]) html_annotation_numbers = "" requires_prefix = "" can_be_enabled = "" if re.search(r"\bx\b", class_name) : requires_prefix = "x" if re.search(r"\bd\b", class_name) : can_be_enabled = "d" if class_name.find("#") >= 0 : numbers = class_name[class_name.find("#"):].strip().split(" ") for number in numbers : number = int(number.replace("#", "")) html_annotation_numbers += "<span class=\"annotation-number\">"+str(number)+"</span>" html_p += "<span class=\"version-stat "+stat.get(stat_items_ordered[j])+" \">"+( html_annotation_numbers if html_annotation_numbers else "" )+stat_items_ordered[j]+( "<span class=\"can-be-enabled\">&nbsp;</span>" if can_be_enabled else "" )+( "<span class=\"requires-prefix\">&nbsp;</span>" if requires_prefix else "" )+"</span> " j = j + 1 html_p += "</p>" html_browser += html_p i = i + 1 html_browser += "</div>" if item["notes_by_num"] : html_browser += "<div>" html_browser += "<h3>Notes</h3>" notes_by_num = item["notes_by_num"] notes_by_num_ordered = list() for k in notes_by_num.keys() : notes_by_num_ordered.append(k) notes_by_num_ordered.sort() i = 0 while i < len(notes_by_num_ordered) : note = notes_by_num.get(notes_by_num_ordered[i]) html_p = "<p class=\"note\"><span class=\"annotation-number\">"+str(notes_by_num_ordered[i])+"</span>"+cgi.escape(note)+"</p>" html_browser += html_p i = i + 1 html_browser += "</div>" if item["links"] : html_browser += "<div>" html_browser += "<h3>Links</h3>" links = item["links"] for link in links : html_p = "<p class=\"link\"><a href=\""+link.get("url")+"\">"+cgi.escape(link.get("title"))+"</a></p>" html_browser += html_p html_browser += "</div>" view = sublime.active_window().active_view() can_i_use_popup_is_showing = True view.show_popup(""" <html> <head></head> <body> """+can_i_use_css+""" <div class=\"container-back-button\"> <a class=\"back-button\" href=\"back"""+( ",main-menu" if can_i_use_list_from_main_menu else "")+"""\">&lt; Back</a> <a class=\"view-on-site\" href=\"http://caniuse.com/#search="""+item["title"].replace(" ", "%20")+"""\"># View on \"Can I use\" site #</a> </div> <div class=\"content\"> """+html_browser+""" <div class=\"legend\"> <h3>Legend</h3> <div class=\"container-legend-items\"> <span class=\"legend-item y\">&nbsp;</span> = Supported <span class=\"legend-item n\">&nbsp;</span> = Not Supported <span class=\"legend-item p a\">&nbsp;</span> = Partial support <span class=\"legend-item u\">&nbsp;</span> = Support unknown <span class=\"legend-item requires-prefix\">&nbsp;</span> = Requires Prefix <span class=\"legend-item can-be-enabled\">&nbsp;</span> = Can Be Enabled </div> </div> </div> </body> </html>""", sublime.COOPERATE_WITH_AUTO_COMPLETE, -1, 1250, 650, back_to_can_i_use_list) class can_i_useCommand(sublime_plugin.TextCommand): def run(self, edit, **args): global items_found_can_i_use global can_i_use_file global can_i_use_list_from_main_menu can_i_use_data = can_i_use_file.get("data") if not can_i_use_data : return view = self.view selection = view.sel()[0] if args.get("from") != "main-menu" : can_i_use_list_from_main_menu = False word = view.substr(view.word(selection)).strip() items_found_can_i_use = find_in_can_i_use(word) sublime.active_window().show_quick_panel([item["title"] for item in items_found_can_i_use], show_pop_can_i_use) else : can_i_use_list_from_main_menu = True items_found_can_i_use = find_in_can_i_use("") sublime.active_window().show_quick_panel([item["title"] for item in items_found_can_i_use], show_pop_can_i_use) def is_enabled(self, **args): view = self.view if args.get("from") == "main-menu" or javascriptCompletions.get("enable_can_i_use_menu_option") : return True return False def is_visible(self, **args): view = self.view if args.get("from") == "main-menu" : return True if javascriptCompletions.get("enable_can_i_use_menu_option") : if Util.split_string_and_find_on_multiple(view.scope_name(0), ["source.js", "text.html.basic", "source.css"]) < 0 : return False return True return False class can_i_use_hide_popupEventListener(sublime_plugin.EventListener): def on_modified_async(self, view) : global can_i_use_popup_is_showing if can_i_use_popup_is_showing : view.hide_popup() can_i_use_popup_is_showing = False
pichillilorenzo/JavaScript-Completions
helper/can_i_use/can_i_use_command.py
Python
mit
10,624
package online.zhaopei.myproject.domain.para; import java.io.Serializable; public class Para implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = -6856542086478273749L; private String code; private String name; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
zhaopei0418/maintain
src/main/java/online/zhaopei/myproject/domain/para/Para.java
Java
mit
482
/** * 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. */ package com.microsoft.azure.management.storage.v2019_06_01; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Defines values for KeyPermission. */ public enum KeyPermission { /** Enum value Read. */ READ("Read"), /** Enum value Full. */ FULL("Full"); /** The actual serialized value for a KeyPermission instance. */ private String value; KeyPermission(String value) { this.value = value; } /** * Parses a serialized value to a KeyPermission instance. * * @param value the serialized value to parse. * @return the parsed KeyPermission object, or null if unable to parse. */ @JsonCreator public static KeyPermission fromString(String value) { KeyPermission[] items = KeyPermission.values(); for (KeyPermission item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return null; } @JsonValue @Override public String toString() { return this.value; } }
selvasingh/azure-sdk-for-java
sdk/storage/mgmt-v2019_06_01/src/main/java/com/microsoft/azure/management/storage/v2019_06_01/KeyPermission.java
Java
mit
1,352
/** * 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. */ package com.microsoft.azure.management.logic.v2018_07_01_preview.implementation; import com.microsoft.azure.management.logic.v2018_07_01_preview.IntegrationAccountMap; import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; import rx.Observable; import java.util.Map; import com.microsoft.azure.management.logic.v2018_07_01_preview.MapType; import com.microsoft.azure.management.logic.v2018_07_01_preview.IntegrationAccountMapPropertiesParametersSchema; import org.joda.time.DateTime; import com.microsoft.azure.management.logic.v2018_07_01_preview.ContentLink; class IntegrationAccountMapImpl extends CreatableUpdatableImpl<IntegrationAccountMap, IntegrationAccountMapInner, IntegrationAccountMapImpl> implements IntegrationAccountMap, IntegrationAccountMap.Definition, IntegrationAccountMap.Update { private final LogicManager manager; private String resourceGroupName; private String integrationAccountName; private String mapName; IntegrationAccountMapImpl(String name, LogicManager manager) { super(name, new IntegrationAccountMapInner()); this.manager = manager; // Set resource name this.mapName = name; // } IntegrationAccountMapImpl(IntegrationAccountMapInner inner, LogicManager manager) { super(inner.name(), inner); this.manager = manager; // Set resource name this.mapName = inner.name(); // set resource ancestor and positional variables this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); this.integrationAccountName = IdParsingUtils.getValueFromIdByName(inner.id(), "integrationAccounts"); this.mapName = IdParsingUtils.getValueFromIdByName(inner.id(), "maps"); // } @Override public LogicManager manager() { return this.manager; } @Override public Observable<IntegrationAccountMap> createResourceAsync() { IntegrationAccountMapsInner client = this.manager().inner().integrationAccountMaps(); return client.createOrUpdateAsync(this.resourceGroupName, this.integrationAccountName, this.mapName, this.inner()) .map(innerToFluentMap(this)); } @Override public Observable<IntegrationAccountMap> updateResourceAsync() { IntegrationAccountMapsInner client = this.manager().inner().integrationAccountMaps(); return client.createOrUpdateAsync(this.resourceGroupName, this.integrationAccountName, this.mapName, this.inner()) .map(innerToFluentMap(this)); } @Override protected Observable<IntegrationAccountMapInner> getInnerAsync() { IntegrationAccountMapsInner client = this.manager().inner().integrationAccountMaps(); return client.getAsync(this.resourceGroupName, this.integrationAccountName, this.mapName); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } @Override public DateTime changedTime() { return this.inner().changedTime(); } @Override public String content() { return this.inner().content(); } @Override public ContentLink contentLink() { return this.inner().contentLink(); } @Override public String contentType() { return this.inner().contentType(); } @Override public DateTime createdTime() { return this.inner().createdTime(); } @Override public String id() { return this.inner().id(); } @Override public String location() { return this.inner().location(); } @Override public MapType mapType() { return this.inner().mapType(); } @Override public Object metadata() { return this.inner().metadata(); } @Override public String name() { return this.inner().name(); } @Override public IntegrationAccountMapPropertiesParametersSchema parametersSchema() { return this.inner().parametersSchema(); } @Override public Map<String, String> tags() { return this.inner().getTags(); } @Override public String type() { return this.inner().type(); } @Override public IntegrationAccountMapImpl withExistingIntegrationAccount(String resourceGroupName, String integrationAccountName) { this.resourceGroupName = resourceGroupName; this.integrationAccountName = integrationAccountName; return this; } @Override public IntegrationAccountMapImpl withMapType(MapType mapType) { this.inner().withMapType(mapType); return this; } @Override public IntegrationAccountMapImpl withContent(String content) { this.inner().withContent(content); return this; } @Override public IntegrationAccountMapImpl withContentType(String contentType) { this.inner().withContentType(contentType); return this; } @Override public IntegrationAccountMapImpl withLocation(String location) { this.inner().withLocation(location); return this; } @Override public IntegrationAccountMapImpl withMetadata(Object metadata) { this.inner().withMetadata(metadata); return this; } @Override public IntegrationAccountMapImpl withParametersSchema(IntegrationAccountMapPropertiesParametersSchema parametersSchema) { this.inner().withParametersSchema(parametersSchema); return this; } @Override public IntegrationAccountMapImpl withTags(Map<String, String> tags) { this.inner().withTags(tags); return this; } }
selvasingh/azure-sdk-for-java
sdk/logic/mgmt-v2018_07_01_preview/src/main/java/com/microsoft/azure/management/logic/v2018_07_01_preview/implementation/IntegrationAccountMapImpl.java
Java
mit
5,910
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Minimal Flask application example for development. SPHINX-START Run example development server: .. code-block:: console $ pip install -e .[all] $ cd examples $ ./app-setup.sh $ python app.py Open the schema from web: .. code-block:: console $ curl http://localhost:5000/schemas/record_schema.json $ curl http://localhost:5000/schemas/biology/animal_record_schema.json Teardown the application: .. code-block:: console $ ./app-teardown.sh SPHINX-END """ from __future__ import absolute_import, print_function import json from flask import Flask from invenio_jsonschemas import InvenioJSONSchemas # Create Flask application app = Flask(__name__) # set the endpoint serving the JSON schemas app.config['JSONSCHEMAS_ENDPOINT'] = '/schemas' # Initialize the application with the InvenioJSONSchema extension. # This registers the jsonschemas from examples/samplepkg/jsonschemas as # samplepkg's setup.py has the "invenio_jsonschemas.schemas" entrypoint. ext = InvenioJSONSchemas(app) # list all registered schemas print('SCHEMAS >> {}'.format(ext.list_schemas())) for schema in ext.list_schemas(): print('=' * 50) print('SCHEMA {}'.format(schema)) # retrieve the schema content print(json.dumps(ext.get_schema(schema), indent=4)) # InvenioJSONSchemas registers a blueprint serving the JSON schemas print('>> You can retrieve the schemas using the url in their "id".') if __name__ == "__main__": app.run()
inveniosoftware/invenio-jsonschemas
examples/app.py
Python
mit
1,706
const mockDevice = { moveAbsolute: jest.fn(() => Promise.resolve()) }; jest.mock("../../device", () => ({ getDevice: () => mockDevice })); let mockPath = ""; jest.mock("../../history", () => ({ getPathArray: jest.fn(() => mockPath.split("/")), history: { push: jest.fn() } })); import * as React from "react"; import { mount, shallow } from "enzyme"; import { RawMoveTo as MoveTo, MoveToProps, MoveToForm, MoveToFormProps, MoveModeLink, chooseLocation, mapStateToProps, } from "../move_to"; import { history } from "../../history"; import { Actions } from "../../constants"; import { clickButton } from "../../__test_support__/helpers"; import { fakeState } from "../../__test_support__/fake_state"; describe("<MoveTo />", () => { beforeEach(function () { mockPath = "/app/designer/move_to"; }); const fakeProps = (): MoveToProps => ({ chosenLocation: { x: 1, y: 2, z: 3 }, currentBotLocation: { x: 10, y: 20, z: 30 }, dispatch: jest.fn(), botOnline: true, }); it("moves to location: bot's current z value", () => { const wrapper = mount(<MoveTo {...fakeProps()} />); wrapper.find("button").simulate("click"); expect(mockDevice.moveAbsolute).toHaveBeenCalledWith({ x: 1, y: 2, z: 3 }); }); it("goes back", () => { const wrapper = mount(<MoveTo {...fakeProps()} />); wrapper.find("i").first().simulate("click"); expect(history.push).toHaveBeenCalledWith("/app/designer/plants"); }); it("unmounts", () => { const p = fakeProps(); const wrapper = mount(<MoveTo {...p} />); jest.clearAllMocks(); wrapper.unmount(); expect(p.dispatch).toHaveBeenCalledWith({ type: Actions.CHOOSE_LOCATION, payload: { x: undefined, y: undefined, z: undefined } }); }); }); describe("<MoveToForm />", () => { const fakeProps = (): MoveToFormProps => ({ chosenLocation: { x: 1, y: 2, z: 3 }, currentBotLocation: { x: 10, y: 20, z: 30 }, botOnline: true, }); it("moves to location: custom z value", () => { const wrapper = mount(<MoveToForm {...fakeProps()} />); wrapper.setState({ z: 50 }); wrapper.find("button").simulate("click"); expect(mockDevice.moveAbsolute).toHaveBeenCalledWith({ x: 1, y: 2, z: 50 }); }); it("changes value", () => { const wrapper = shallow<MoveToForm>(<MoveToForm {...fakeProps()} />); wrapper.findWhere(n => "onChange" in n.props()).simulate("change", "", 10); expect(wrapper.state().z).toEqual(10); }); it("fills in some missing values", () => { const p = fakeProps(); p.chosenLocation = { x: 1, y: undefined, z: undefined }; const wrapper = mount(<MoveToForm {...p} />); expect(wrapper.find("input").at(1).props().value).toEqual("---"); wrapper.find("button").simulate("click"); expect(mockDevice.moveAbsolute).toHaveBeenCalledWith({ x: 1, y: 20, z: 30 }); }); it("fills in all missing values", () => { const p = fakeProps(); p.chosenLocation = { x: undefined, y: undefined, z: undefined }; p.currentBotLocation = { x: undefined, y: undefined, z: undefined }; const wrapper = mount(<MoveToForm {...p} />); expect(wrapper.find("input").at(1).props().value).toEqual("---"); wrapper.find("button").simulate("click"); expect(mockDevice.moveAbsolute).toHaveBeenCalledWith({ x: 0, y: 0, z: 0 }); }); it("is disabled when bot is offline", () => { const p = fakeProps(); p.botOnline = false; const wrapper = mount(<MoveToForm {...p} />); expect(wrapper.find("button").hasClass("pseudo-disabled")).toBeTruthy(); }); }); describe("<MoveModeLink />", () => { it("enters 'move to' mode", () => { const wrapper = shallow(<MoveModeLink />); clickButton(wrapper, 0, "move mode"); expect(history.push).toHaveBeenCalledWith("/app/designer/move_to"); }); }); describe("chooseLocation()", () => { it("updates chosen coordinates", () => { const dispatch = jest.fn(); chooseLocation({ dispatch, gardenCoords: { x: 1, y: 2 } }); expect(dispatch).toHaveBeenCalledWith({ type: Actions.CHOOSE_LOCATION, payload: { x: 1, y: 2, z: 0 } }); }); it("doesn't update coordinates", () => { const dispatch = jest.fn(); chooseLocation({ dispatch, gardenCoords: undefined }); expect(dispatch).not.toHaveBeenCalled(); }); }); describe("mapStateToProps()", () => { it("returns props", () => { const state = fakeState(); state.resources.consumers.farm_designer.chosenLocation = { x: 1, y: 2, z: 3 }; const props = mapStateToProps(state); expect(props.chosenLocation).toEqual({ x: 1, y: 2, z: 3 }); }); });
gabrielburnworth/Farmbot-Web-App
frontend/farm_designer/__tests__/move_to_test.tsx
TypeScript
mit
4,612
<?php defined('BASEPATH') OR exit('No direct script access allowed'); define("IS_AJAX",isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == 'xmlhttprequest'); class Reporte extends CI_Controller{ function __construct(){ parent::__construct(); } function Index(){ echo "<p>Page not found 404</p>"; } function ReporteEgresados(){ $this->load->model("egresado_model"); $data["data"] = $this->egresado_model->getReporteEgresadosTrabajando(); $data["data_titulados"] = $this->egresado_model->getReporteEgresadosTitulados(); $data["egresados_carrera"] = $this->egresado_model->getReporteEgresadosCarrera(); if(IS_AJAX){ $this->load->view("reportes/egresados_trabajando_reporte",$data); $this->load->view("reportes/egresados_titulados_reporte",$data); $this->load->view("reportes/egresados_carreras_reporte",$data); }else{ $this->load->view("cabecera"); $this->load->view("nav"); $this->load->view("reportes/egresados_trabajando_reporte",$data); $this->load->view("reportes/egresados_titulados_reporte",$data); $this->load->view("reportes/egresados_carreras_reporte",$data); $this->load->view("footer"); } } function Trabajando(){ $this->load->model("egresado_model"); $data["data"] = $this->egresado_model->getReporteEgresadosTrabajando(); if(IS_AJAX){ $this->load->view("reportes/egresados_trabajando_reporte",$data); }else{ $this->load->view("cabecera"); $this->load->view("nav"); $this->load->view("reportes/egresados_trabajando_reporte",$data); $this->load->view("footer"); } } function Titulados(){ $this->load->model("egresado_model"); $data["data_titulados"] = $this->egresado_model->getReporteEgresadosTitulados(); if(IS_AJAX){ $this->load->view("reportes/egresados_titulados_reporte",$data); }else{ $this->load->view("cabecera"); $this->load->view("nav"); $this->load->view("reportes/egresados_titulados_reporte",$data); $this->load->view("footer"); } } function EgresadosCarrera(){ $this->load->model("egresado_model"); $data["egresados_carrera"] = $this->egresado_model->getReporteEgresadosCarrera(); if(IS_AJAX){ $this->load->view("reportes/egresados_carreras_reporte",$data); }else{ $this->load->view("cabecera"); $this->load->view("nav"); $this->load->view("reportes/egresados_carreras_reporte",$data); $this->load->view("footer"); } } } ?>
mike2c/SCSEUNI
application/controllers/Reporte.php
PHP
mit
2,508
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("9. Increase Age Stored Procedure")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("9. Increase Age Stored Procedure")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("3eb47ffc-3c0d-4b84-bed9-68ea334a5534")] // 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")]
RAstardzhiev/Software-University-SoftUni
Databases Advanced - Entity Framework 6/DB Apps Introduction/9. Increase Age Stored Procedure/Properties/AssemblyInfo.cs
C#
mit
1,435
<?php namespace knx\FarmaciaBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use knx\FarmaciaBundle\Entity\Traslado; use knx\FarmaciaBundle\Entity\Almacen; use knx\FarmaciaBundle\Entity\Inventario; use knx\FarmaciaBundle\Entity\Imv; use knx\FarmaciaBundle\Entity\Farmacia; use knx\FarmaciaBundle\Entity\ImvFarmacia; use knx\FarmaciaBundle\Form\TrasladoType; use knx\FarmaciaBundle\Form\TrasladoSearchType; use Symfony\Component\HttpFoundation\Response; class TrasladoController extends Controller { public function searchAction(){ $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Traslados"); $breadcrumbs->addItem("Busqueda"); $form = $this->createForm(new TrasladoSearchType()); return $this->render('FarmaciaBundle:Traslado:search.html.twig', array( 'form' => $form->createView() )); } public function searchprintAction() { $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Traslados"); $breadcrumbs->addItem("Busqueda"); $form = $this->createForm(new TrasladoSearchType()); return $this->render('FarmaciaBundle:Traslado:searchprint.html.twig', array( 'form' => $form->createView() )); } public function resultAction() { $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia"); $breadcrumbs->addItem("Traslados", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem("Resultado Busqueda"); $em = $this->getDoctrine()->getEntityManager(); $traslado = $em->getRepository('FarmaciaBundle:Traslado')->findAll(); $request = $this->get('request'); $fecha_inicio = $request->request->get('fecha_inicio'); $fecha_fin = $request->request->get('fecha_fin'); //die(print_r($fecha_inicio)); $form = $this->createForm(new TrasladoSearchType()); if(trim($fecha_inicio)){ $desde = explode('/',$fecha_inicio); //die(print_r($desde)); if(!checkdate($desde[1],$desde[0],$desde[2])){ $this->get('session')->setFlash('info', 'La fecha de inicio ingresada es incorrecta.'); return $this->render('FarmaciaBundle:Traslado:search.html.twig', array( 'form' => $form->createView() )); } }else{ $this->get('session')->setFlash('info', 'La fecha de inicio no puede estar en blanco.'); return $this->render('FarmaciaBundle:Traslado:search.html.twig', array( 'form' => $form->createView() )); } if(trim($fecha_fin)){ $hasta = explode('/',$fecha_fin); if(!checkdate($hasta[1],$hasta[0],$hasta[2])){ $this->get('session')->setFlash('info', 'La fecha de finalización ingresada es incorrecta.'); return $this->render('FarmaciaBundle:Traslado:search.html.twig', array( 'form' => $form->createView() )); } }else{ $this->get('session')->setFlash('info', 'La fecha de finalización no puede estar en blanco.'); return $this->render('FarmaciaBundle:Traslado:search.html.twig', array( 'form' => $form->createView() )); } $query = "SELECT f FROM FarmaciaBundle:Traslado f WHERE f.fecha >= :inicio AND f.fecha <= :fin ORDER BY f.fecha ASC"; $dql = $em->createQuery($query); //die(print_r($dql)); $dql->setParameter('inicio', $desde[2]."/".$desde[1]."/".$desde[0].' 00:00:00'); $dql->setParameter('fin', $hasta[2]."/".$hasta[1]."/".$hasta[0].' 23:59:00'); $traslado = $dql->getResult(); //die(var_dump($ingreso)); //die("paso"); if(!$traslado) { $this->get('session')->setFlash('info', 'La consulta no ha arrojado ningún resultado para los parametros de busqueda ingresados.'); return $this->redirect($this->generateUrl('traslado_search')); } return $this->render('FarmaciaBundle:Traslado:list.html.twig', array( 'trasfarma' => $traslado )); } public function listAction() { $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia"); $breadcrumbs->addItem("Traslados", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem("Listado"); $paginator = $this->get('knp_paginator'); $em = $this->getDoctrine()->getEntityManager(); $traslado = $em->getRepository('FarmaciaBundle:Traslado')->findAll(); $farmacia = $em->getRepository('FarmaciaBundle:Farmacia')->findAll(); $imvfarmacia = $em->getRepository('FarmaciaBundle:ImvFarmacia')->findAll(); if (!$traslado) { $this->get('session')->setFlash('info', 'No existen traslados'); } $traslado = $paginator->paginate($traslado,$this->getRequest()->query->get('page', 1), 10); return $this->render('FarmaciaBundle:Traslado:list.html.twig', array( 'trasfarma' => $traslado, 'farmacia' => $farmacia, 'imvfarmacia' => $imvfarmacia )); } public function newAction($imv,$almacen) { $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia"); $breadcrumbs->addItem("Traslados", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem("Nueva Traslado"); $em = $this->getDoctrine()->getEntityManager(); $imv = $em->getRepository('FarmaciaBundle:Imv')->find( $imv); $almacen = $em->getRepository('ParametrizarBundle:Almacen')->find($almacen); //die(var_dump($imv)); $nombre_imv = $imv->getNombre(); $nombre_almacen = $almacen->getNombre(); $traslado = new Traslado(); $traslado->setFecha(new \datetime('now')); $form = $this->createForm(new TrasladoType(), $traslado); $imvf = $form["imv"]->setData($nombre_imv); //$almacenf = $form["almacen"]->setData($nombre_almacen); return $this->render('FarmaciaBundle:Traslado:new.html.twig', array( 'traslado'=>$traslado, 'imv'=>$imv, 'almacen'=>$almacen, 'form' => $form->createView() )); } public function saveAction($imv,$almacen) { $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem("Nueva Traslado"); $em = $this->getDoctrine()->getEntityManager(); $traslado = $em->getRepository('FarmaciaBundle:Traslado')->findAll(); $traslado = new Traslado(); $traslado->setFecha(new \datetime('now')); $request = $this->getRequest(); $form = $this->createForm(new TrasladoType(), $traslado); $imvf = $form->get('imv')->getData(); $em = $this->getDoctrine()->getEntityManager(); $imv = $em->getRepository('FarmaciaBundle:Imv')->find( $imv); $almacen = $em->getRepository('ParametrizarBundle:Almacen')->find($almacen); if ($request->getMethod() == 'POST') { $form->bind($request); if ($form->isValid()) { $almacen = $em->getRepository('ParametrizarBundle:Almacen')->find( $almacen); $trasladoimv = $em->getRepository('FarmaciaBundle:Traslado')->findoneBy(array('farmacia'=> $traslado->getFarmacia(),'imv' => $imv->getId())); //die(print_r($trasladoimv)); $tipo_traslado = $traslado->getTipo();/*tipo de movimiento*/ if($tipo_traslado=='D' && !$trasladoimv ){ $this->get('session')->setFlash('error','El medicamento no presenta traslados para realizar una devolucion deben existir traslados'); return $this->redirect($this->generateUrl('traslado_new', array("imv" => $imv->getId(),"almacen" => $almacen->getId()))); }else{ $tipo_traslado = $traslado->getTipo();/*tipo de movimiento*/ $cant_traslado = $traslado->getCant();/*cantidad de traslado*/ $farmacia = $traslado->getFarmacia();/*Farmacia ingresada*/ //die(var_dump($cant_traslado)); //die(var_dump($cant_imv)); } $em = $this->getDoctrine()->getEntityManager(); $imv = $em->getRepository('FarmaciaBundle:Imv')->find( $imv); $almacen = $em->getRepository('ParametrizarBundle:Almacen')->find( $almacen); //die(var_dump($almacen)); $almacenimv = $em->getRepository('FarmaciaBundle:AlmacenImv')->findoneBy(array('almacen'=> $almacen->getId(), 'imv' => $imv->getId())); $cant_almacenimv = $almacenimv->getCant();/*traigo cantidad total del almacen*/ $almacenid = $almacen->getId(); //die(var_dump($almacenid)); if ($tipo_traslado=='T'){ if ($cant_almacenimv < $cant_traslado){ $this->get('session')->setFlash('error','La cantidad ingresada es mayor que cantidad en existencia almacen,cantidad en existencia='.$cant_almacenimv = $almacenimv->getCant().''); return $this->redirect($this->generateUrl('traslado_new', array("imv" => $imv->getId(),"almacen" => $almacen->getId()))); }else { $imvfarmacia = $em->getRepository('FarmaciaBundle:ImvFarmacia')->findoneBy(array('farmacia'=> $traslado->getFarmacia(), 'imv' => $imv->getId())); $almacenimv = $em->getRepository('FarmaciaBundle:AlmacenImv')->findoneBy(array('almacen'=> $almacen->getId(), 'imv' => $imv->getId())); if($imvfarmacia){ $cant_traslado = $traslado->getCant();/*cantidad de traslado*/ $cant_imvfarmacia = $imvfarmacia->getCant();/*cantidad de imvfarmacia*/ $cant_almacenimv = $almacenimv->getCant();/*traigo cantidad total del almacen*/ $traslado->setImv($imv); $traslado->setAlmacen($almacen); $imvfarmacia->setCant($cant_traslado + $cant_imvfarmacia); $almacenimv->setCant($cant_almacenimv - $cant_traslado); $em->persist($imvfarmacia); $em->persist($almacenimv); $em->persist($traslado); $em->flush(); $this->get('session')->setFlash('ok', 'El traslado ha sido creada éxitosamente.'); return $this->redirect($this->generateUrl('traslado_list')); }else{ $almacenimv = $em->getRepository('FarmaciaBundle:AlmacenImv')->findoneBy(array('almacen'=> $almacen->getId(), 'imv' => $imv->getId())); $cant_almacenimv = $almacenimv->getCant();/*traigo cantidad total del almacen*/ $cant_traslado = $traslado->getCant();/*cantidad de traslado*/ $imvfarmacia = new ImvFarmacia(); $traslado->setImv($imv); $traslado->setAlmacen($almacen); $imvfarmacia->setImv($imv); $imvfarmacia->setFarmacia($farmacia); $imvfarmacia->setCant($cant_traslado); $almacenimv->setCant($cant_almacenimv - $cant_traslado); $em->persist($imvfarmacia); $em->persist($almacenimv); } $em->persist($traslado); $em->flush(); $this->get('session')->setFlash('ok', 'El traslado ha sido creada éxitosamente.'); return $this->redirect($this->generateUrl('traslado_show', array("traslado" => $traslado->getId()))); } } elseif (($tipo_traslado=='D')){ $imvfarmacia = $em->getRepository('FarmaciaBundle:ImvFarmacia')->findoneBy(array('farmacia'=> $traslado->getFarmacia(), 'imv' => $imv->getId())); $cant_traslado = $traslado->getCant();/*cantidad de traslado*/ $cant_imvfarmacia = $imvfarmacia->getCant();/*cantidad de imvfarmacia*/ //die(var_dump($cant_imvfarmacia)); if($cant_imvfarmacia < $cant_traslado ){ $this->get('session')->setFlash('error','La cantidad ingresada es mayor que cantidad en existencia de la farmacia,cantidad en farmacia='.$cant_imvfarmacia = $imvfarmacia->getCant().''); return $this->redirect($this->generateUrl('traslado_new', array("imv" => $imv->getId(),"almacen" => $almacen->getId()))); }else{ $imvfarmacia = $em->getRepository('FarmaciaBundle:ImvFarmacia')->findoneBy(array('farmacia'=> $traslado->getFarmacia(), 'imv' => $imv->getId())); if($imvfarmacia){ $cant_traslado = $traslado->getCant();/*cantidad de traslado*/ $cant_imvfarmacia = $imvfarmacia->getCant();/*cantidad de imvfarmacia*/ $cant_almacenimv = $almacenimv->getCant();/*traigo cantidad total del almacen*/ $traslado->setImv($imv); $traslado->setAlmacen($almacen); $imvfarmacia->setCant($cant_imvfarmacia - $cant_traslado); $almacenimv->setCant($cant_almacenimv + $cant_traslado); $em->persist($imvfarmacia); $em->persist($almacenimv); $em->persist($traslado); $em->flush(); $this->get('session')->setFlash('ok', 'El traslado ha sido creada éxitosamente.'); return $this->redirect($this->generateUrl('traslado_list')); }else{ $cant_almacenimv = $almacenimv->getCant();/*traigo cantidad total del almacen*/ $imvfarmacia = new ImvFarmacia(); $traslado->setImv($imv); $traslado->setAlmacen($almacen); $imvfarmacia->setImv($imv); $imvfarmacia->setFarmacia($farmacia); $imvfarmacia->setCant($cant_traslado); $almacenimv->setCant($cant_almacenimv + $cant_traslado); $em->persist($imvfarmacia); $em->persist($almacenimv); $em->persist($traslado); } $em->flush(); $this->get('session')->setFlash('ok', 'El traslado ha sido creada éxitosamente.'); return $this->redirect($this->generateUrl('traslado_show', array("traslado" => $traslado->getId()))); } } } } return $this->render('FarmaciaBundle:Traslado:new.html.twig', array( 'imv' => $imv, 'form' => $form->createView() )); } public function showAction($traslado) { $em = $this->getDoctrine()->getEntityManager(); $traslado = $em->getRepository('FarmaciaBundle:Traslado')->find($traslado); $imv = $traslado->getImv(); $nombre_imv = $imv->getNombre(); $farmacia = $traslado->getFarmacia(); if (!$traslado) { throw $this->createNotFoundException('El traslado solicitado no esta disponible.'); } $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia"); $breadcrumbs->addItem("Traslados", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem($nombre_imv, $this->get("router")->generate('traslado_show', array('traslado' => $traslado->getId()))); $breadcrumbs->addItem($farmacia->getNombre()); return $this->render('FarmaciaBundle:Traslado:show.html.twig', array( 'trasfarma' => $traslado, )); } public function editAction($traslado) { $em = $this->getDoctrine()->getEntityManager(); $traslado = $em->getRepository('FarmaciaBundle:Traslado')->find($traslado); if (!$traslado) { throw $this->createNotFoundException('El traslado solicitado no esta disponible.'); } $imv = $traslado->getImv(); $nombre_imv = $imv->getNombre(); $farmacia = $traslado->getFarmacia(); $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia"); $breadcrumbs->addItem("Traslados", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem("Modificar"); $breadcrumbs->addItem($nombre_imv, $this->get("router")->generate('traslado_show', array('traslado' => $traslado->getId()))); $form = $this->createForm(new TrasladoType(), $traslado); $imvf = $form["imv"]->setData($nombre_imv); return $this->render('FarmaciaBundle:Traslado:edit.html.twig', array( 'trasfarma' => $traslado, 'form' => $form->createView(), )); } public function updateAction($traslado) { $em = $this->getDoctrine()->getEntityManager(); $traslado = $em->getRepository('FarmaciaBundle:Traslado')->find($traslado); if (!$traslado) { throw $this->createNotFoundException('El traslado solicitado no esta disponible.'); } $form = $this->createForm(new TrasladoType(), $traslado); $request = $this->getRequest(); if ($request->getMethod() == 'POST') { $form->bind($request); if ($form->isValid()) { $tipo_traslado = $traslado->getTipo();/*tipo de traslado*/ $cant_traslado = $traslado->getCant();/*cantidad de traslado*/ //die(var_dump($cant_traslado)); $imv = $traslado->getImv();/*Entidad imv para llegar a la cantidad total*/ $cant_imv = $imv->getCantT();/*traigo cantidad total del imv*/ $farmacia = $traslado->getFarmacia(); $em = $this->getDoctrine()->getEntityManager(); if ($tipo_traslado=='T'){ if ($cant_imv < $cant_traslado){ $this->get('session')->setFlash('error','La cantidad ingresada es mayor que cantidad en existencia,cantidad en existencia-'.$cant_imv = $imv->getCantT().''); return $this->redirect($this->generateUrl('traslado_edit', array('inventario' => $inventario->getId(), 'farmacia' => $farmacia->getId()))); }else { $em->persist($traslado); $em->flush(); $this->get('session')->setFlash('ok', 'El traslado ha sido modificado éxitosamente.'); return $this->redirect($this->generateUrl('traslado_show', array('traslado' => $traslado->getId()))); } } elseif (($tipo_traslado=='D')){ if ($cant_imv < $cant_traslado){ $this->get('session')->setFlash('error','La cantidad ingresada es mayor que cantidad en existencia,cantidad en existencia-'.$cant_imv = $imv->getCantT().''); return $this->redirect($this->generateUrl('traslado_edit', array('traslado' => $traslado->getId()))); }else { $em->persist($traslado); $em->flush(); $this->get('session')->setFlash('ok', 'El traslado ha sido modificado éxitosamente.'); return $this->redirect($this->generateUrl('traslado_show', array('inventario' => $inventario->getId(), 'farmacia' => $farmacia->getId()))); } } } } $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem($traslado->getId(), $this->get("router")->generate("traslado_show", array("traslado" => $traslado->getId()))); $breadcrumbs->addItem("Modificar".$traslado->getId()); return $this->render('FarmaciaBundle:Traslado:new.html.twig', array( 'traslado' => $traslado, 'form' => $form->createView(), )); } public function printAction() { $breadcrumbs = $this->get("white_october_breadcrumbs"); $breadcrumbs->addItem("Inicio", $this->get("router")->generate("parametrizar_index")); $breadcrumbs->addItem("Farmacia"); $breadcrumbs->addItem("Traslados", $this->get("router")->generate("traslado_list")); $breadcrumbs->addItem("Resultado Busqueda"); $em = $this->getDoctrine()->getEntityManager(); $traslado = $em->getRepository('FarmaciaBundle:Traslado')->findAll(); $request = $this->get('request'); $fecha_inicio = $request->request->get('fecha_inicio'); $fecha_fin = $request->request->get('fecha_fin'); //die(print_r($fecha_inicio)); $form = $this->createForm(new TrasladoSearchType()); if(trim($fecha_inicio)){ $desde = explode('/',$fecha_inicio); //die(print_r($desde)); if(!checkdate($desde[1],$desde[0],$desde[2])){ $this->get('session')->setFlash('info', 'La fecha de inicio ingresada es incorrecta.'); return $this->render('FarmaciaBundle:Traslado:searchprint.html.twig', array( 'form' => $form->createView() )); } }else{ $this->get('session')->setFlash('info', 'La fecha de inicio no puede estar en blanco.'); return $this->render('FarmaciaBundle:Traslado:searchprint.html.twig', array( 'form' => $form->createView() )); } if(trim($fecha_fin)){ $hasta = explode('/',$fecha_fin); if(!checkdate($hasta[1],$hasta[0],$hasta[2])){ $this->get('session')->setFlash('info', 'La fecha de finalización ingresada es incorrecta.'); return $this->render('FarmaciaBundle:Traslado:searchprint.html.twig', array( 'form' => $form->createView() )); } }else{ $this->get('session')->setFlash('info', 'La fecha de finalización no puede estar en blanco.'); return $this->render('FarmaciaBundle:Traslado:searchprint.html.twig', array( 'form' => $form->createView() )); } $query = "SELECT f FROM FarmaciaBundle:Traslado f WHERE f.fecha >= :inicio AND f.fecha <= :fin ORDER BY f.fecha ASC"; $dql = $em->createQuery($query); //die(print_r($dql)); $dql->setParameter('inicio', $desde[2]."/".$desde[1]."/".$desde[0].' 00:00:00'); $dql->setParameter('fin', $hasta[2]."/".$hasta[1]."/".$hasta[0].' 23:59:00'); $traslado = $dql->getResult(); //die(var_dump($ingreso)); //die("paso"); if(!$traslado) { $this->get('session')->setFlash('info', 'La consulta no ha arrojado ningún resultado para los parametros de busqueda ingresados.'); return $this->redirect($this->generateUrl('traslado_searchprint')); } $pdf = $this->get('white_october.tcpdf')->create(); $html = $this->renderView('FarmaciaBundle:Traslado:listado.html.twig',array( 'trasfarma' => $traslado, 'fechai' =>$fecha_inicio, 'fechaf' =>$fecha_fin )); return $pdf->quick_pdf($html, 'Detallado_traslados_', 'D'); } }
Kenovix/san-miguel
src/knx/FarmaciaBundle/Controller/TrasladoController.php
PHP
mit
22,433
<?php /** * kitFramework::Basic * * @author Team phpManufaktur <team@phpmanufaktur.de> * @link https://kit2.phpmanufaktur.de * @copyright 2013 Ralf Hertsch <ralf.hertsch@phpmanufaktur.de> * @license MIT License (MIT) http://www.opensource.org/licenses/MIT */ namespace phpManufaktur\Basic\Control\CMS; use phpManufaktur\Basic\Control\CMS\WebsiteBaker\OutputFilter as WebsiteBakerOutputFilter; if (!defined('CMS_PATH') || defined('SYNCDATA_PATH')) { // missing CMS_PATH indicate that the output filter is called directly by the CMS, we have no autoloading at this point !!! require_once WB_PATH.'/kit2/extension/phpmanufaktur/phpManufaktur/Basic/Control/CMS/WebsiteBaker/OutputFilter.php'; } class OutputFilter extends WebsiteBakerOutputFilter { // nothing to extend or to change because the handling for WebsiteBaker, // LEPTON and BlackCat is identical - maybe change later... }
phpManufakturHeirs/kfBasic
Control/CMS/OutputFilter.php
PHP
mit
908
const bodyParser = require('body-parser') module.exports = [ bodyParser.json({ limit: '10mb', extended: false }), bodyParser.urlencoded({ extended: false }), ]
legovaer/json-server
src/server/body-parser.js
JavaScript
mit
165
import cnn import numpy as np if __name__ == '__main__': #import input_data import random from PIL import Image #mnist = input_data.read_data_sets('MNIST_data', one_hot=True) ocr = cnn.CNN() ocr.build() #ocr.predict() show_image2 = Image.open('G:/Users/kakoi/Desktop/无标题.bmp') show_array2 = np.asarray(show_image2).flatten() input_image2 = show_array2 / 255 print(ocr.read(input_image2)) #input_image = mnist.test.images[random.randrange(0, 100)] #show_image = input_image*255 #im = Image.fromarray(show_image.reshape([28,28])) #im.show() #print(ocr.read(input_image))
kelifrisk/justforfun
python/cnn/mnist_resnet/main.py
Python
mit
672
using System.Linq; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Filters; using BenchmarkDotNet.Running; using Xunit; namespace BenchmarkDotNet.Tests { public class GlobFilterTests { [Theory] [InlineData(nameof(TypeWithBenchmarks), true)] // type name [InlineData("typewithbenchmarks", true)] // type name lowercase [InlineData("TYPEWITHBENCHMARKS", true)] // type name uppercase [InlineData("*TypeWithBenchmarks*", true)] // regular expression [InlineData("*typewithbenchmarks*", true)] // regular expression lowercase [InlineData("*TYPEWITHBENCHMARKS*", true)] // regular expression uppercase [InlineData("*", true)] [InlineData("WRONG", false)] [InlineData("*stillWRONG*", false)] public void TheFilterIsCaseInsensitive(string pattern, bool expected) { var benchmarkCase = BenchmarkConverter.TypeToBenchmarks(typeof(TypeWithBenchmarks)).BenchmarksCases.Single(); var filter = new GlobFilter(new[] { pattern }); Assert.Equal(expected, filter.Predicate(benchmarkCase)); } public class TypeWithBenchmarks { [Benchmark] public void TheBenchmark() { } } } }
alinasmirnova/BenchmarkDotNet
tests/BenchmarkDotNet.Tests/GlobFilterTests.cs
C#
mit
1,261
namespace Exrin.Abstraction { using System; public interface IInjectionProxy { void Init(); void Complete(); bool IsRegistered<T>(); void Register<T>(InstanceType type = InstanceType.SingleInstance) where T : class; void RegisterInterface<I, T>(InstanceType type = InstanceType.SingleInstance) where T : class, I where I : class; void RegisterInstance<I, T>(T instance) where T : class, I where I : class; void RegisterInstance<I>(I instance) where I : class; T Get<T>(bool optional = false) where T : class; object Get(Type type); } }
adamped/exrin
Exrin/Exrin.Framework/Abstraction/IInjection.cs
C#
mit
716
package com.adobe.epubcheck.ctc.xml; import java.util.HashSet; import java.util.Locale; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.adobe.epubcheck.api.EPUBLocation; import com.adobe.epubcheck.api.Report; import com.adobe.epubcheck.messages.MessageId; import com.adobe.epubcheck.ops.OPSHandler30; import com.adobe.epubcheck.util.EPUBVersion; import com.adobe.epubcheck.util.FeatureEnum; public class ScriptTagHandler extends DefaultHandler { private Locator locator; private String fileName; private int inlineScriptCount = 0; private boolean inScript = false; private EPUBVersion version = EPUBVersion.Unknown; private final Report report; public static final Pattern xmlHttpRequestPattern = Pattern.compile("new[\\s]*XMLHttpRequest[\\s]*\\("); public static final Pattern microsoftXmlHttpRequestPattern = Pattern.compile("Microsoft.XMLHTTP"); public static final Pattern evalPattern = Pattern.compile("((^eval[\\s]*\\()|([^a-zA-Z0-9]eval[\\s]*\\()|([\\s]+eval[\\s]*\\())"); public static final Pattern localStoragePattern = Pattern.compile("localStorage\\."); public static final Pattern sessionStoragePattern = Pattern.compile("sessionStorage\\."); public void setFileName(String fileName) { this.fileName = fileName; } public ScriptTagHandler(Report report) { this.report = report; } public void setDocumentLocator(Locator locator) { this.locator = locator; } public void setVersion(EPUBVersion version) { this.version = version; } private final Vector<ScriptElement> scriptElements = new Vector<ScriptElement>(); public int getScriptElementCount() { return scriptElements.size(); } public Vector<ScriptElement> getScriptElements() { return scriptElements; } public int getInlineScriptCount() { return inlineScriptCount; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.compareToIgnoreCase("SCRIPT") == 0) { inScript = true; if (this.version == EPUBVersion.VERSION_2) { report.message(MessageId.SCP_004, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), qName)); } ScriptElement scriptElement = new ScriptElement(); boolean isExternal = false; for (int i = 0; i < attributes.getLength(); i++) { String attrName = attributes.getQName(i); String attrValue = attributes.getValue(i); if (attrName.equalsIgnoreCase("src")) { isExternal = true; } scriptElement.addAttribute(attrName, attrValue); } if (isExternal) { report.info(this.fileName, FeatureEnum.SCRIPT, "external"); } else { report.info(this.fileName, FeatureEnum.SCRIPT, "tag"); } scriptElements.add(scriptElement); } else { HashSet<String> scriptEvents = OPSHandler30.getScriptEvents(); HashSet<String> mouseEvents = OPSHandler30.getMouseEvents(); for (int i = 0; i < attributes.getLength(); i++) { String attrName = attributes.getLocalName(i).toLowerCase(Locale.ROOT); if (scriptEvents.contains(attrName)) { this.inlineScriptCount++; if (this.version == EPUBVersion.VERSION_2) { report.message(MessageId.SCP_004, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), attrName)); } report.message(MessageId.SCP_006, EPUBLocation.create(this.fileName, locator.getLineNumber(), locator.getColumnNumber(), attrName)); String attrValue = attributes.getValue(i); CheckForInner(attrValue); } if (mouseEvents.contains(attrName)) { if (this.version == EPUBVersion.VERSION_2) { report.message(MessageId.SCP_004, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), attrName)); } report.message(MessageId.SCP_009, EPUBLocation.create(this.fileName, locator.getLineNumber(), locator.getColumnNumber(), attrName)); } } } } public void endElement(String uri, String localName, String qName) throws SAXException { //outWriter.println("End Tag -->:</" + qName+">"); if (qName.compareToIgnoreCase("SCRIPT") == 0) { inScript = false; } } public void characters(char ch[], int start, int length) throws SAXException { //outWriter.println("-----Tag value----------->"+new String(ch, start, length)); if (inScript) { String script = new String(ch, start, length); CheckForInner(script); } } public void CheckForInner(String script) { String lower = script.toLowerCase(Locale.ROOT); int column = lower.indexOf("innerhtml"); if (column >= 0) { report.message(MessageId.SCP_007, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), trimContext(script, column))); } column = lower.indexOf("innertext"); if (column >= 0) { report.message(MessageId.SCP_008, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), trimContext(script, column))); } // the exact pattern is very complex and it slows down all script checking. // what we can do here is use a blunt check (for the word "eval"). if it is not found, keep moving. // If it is found, look closely using the exact pattern to see if the line truly matches the exact eval() function and report that. Matcher m = null; if (script.contains("eval")) { m = evalPattern.matcher(script); if (m.find()) { report.message(MessageId.SCP_001, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), trimContext(script, m.start()))); } } m = localStoragePattern.matcher(script); if (m.find()) { report.message(MessageId.SCP_003, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), trimContext(script, m.start()))); } m = sessionStoragePattern.matcher(script); if (m.find()) { report.message(MessageId.SCP_003, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), trimContext(script, m.start()))); } m = xmlHttpRequestPattern.matcher(script); if (m.find()) { report.message(MessageId.SCP_002, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), trimContext(script, m.start()))); } m = microsoftXmlHttpRequestPattern.matcher(script); if (m.find()) { report.message(MessageId.SCP_002, EPUBLocation.create(fileName, locator.getLineNumber(), locator.getColumnNumber(), trimContext(script, m.start()))); } } static public String trimContext(String context, int start) { String trimmed = context.substring(start).trim(); int end = trimmed.indexOf("\n"); if (end < 0 && trimmed.length() < 60) { return trimmed; } else { int newEnd = Math.min(60, (end > 0 ? end : trimmed.length())); return trimmed.substring(0, newEnd); } } }
WSchindler/epubcheck
src/main/java/com/adobe/epubcheck/ctc/xml/ScriptTagHandler.java
Java
mit
7,447
export function getEthernetSource(packet: any): string { return decimalToHex(packet.payload.shost.addr); } export function decimalToHex(numbers: number[]): string { let hexStrings = numbers.map(decimal => decimal.toString(16).padStart(2, '0')); return hexStrings.join(':'); }
ide/dash-button
src/MacAddresses.ts
TypeScript
mit
283
<?php namespace Payum\Core\Tests\Reply; use Payum\Core\Reply\HttpResponse; use PHPUnit\Framework\TestCase; class HttpResponseTest extends TestCase { /** * @test */ public function shouldImplementReplyInterface() { $rc = new \ReflectionClass('Payum\Core\Reply\HttpResponse'); $this->assertTrue($rc->implementsInterface('Payum\Core\Reply\ReplyInterface')); } /** * @test */ public function shouldAllowGetContentSetInConstructor() { $expectedContent = 'html page'; $request = new HttpResponse($expectedContent); $this->assertEquals($expectedContent, $request->getContent()); } /** * @test */ public function shouldAllowGetDefaultStatusCodeSetInConstructor() { $request = new HttpResponse('html page'); $this->assertEquals(200, $request->getStatusCode()); } /** * @test */ public function shouldAllowGetCustomStatusCodeSetInConstructor() { $request = new HttpResponse('html page', 301); $this->assertEquals(301, $request->getStatusCode()); } /** * @test */ public function shouldAllowGetDefaultHeadersSetInConstructor() { $request = new HttpResponse('html page'); $this->assertEquals(array(), $request->getHeaders()); } /** * @test */ public function shouldAllowGetCustomHeadersSetInConstructor() { $expectedHeaders = array( 'foo' => 'fooVal', 'bar' => 'barVal', ); $request = new HttpResponse('html page', 200, $expectedHeaders); $this->assertEquals($expectedHeaders, $request->getHeaders()); } }
Payum/Payum
src/Payum/Core/Tests/Reply/HttpResponseTest.php
PHP
mit
1,709
import { equal } from '@ember/object/computed'; import Component from '@ember/component'; import { action, computed } from '@ember/object'; import { htmlSafe } from '@ember/template'; export default Component.extend({ tagName: '', position: 0, side: '', isRight: equal('side', 'right'), isLeft: equal('side', 'left'), minWidth: 60, /** * Reference to drag-handle on mousedown * * @property el * @type {DOMNode|null} * @default null */ el: null, /** * The maximum width this handle can be dragged to. * * @property maxWidth * @type {Number} * @default Infinity */ maxWidth: Infinity, /** * The left offset to add to the initial position. * * @property left * @type {Number} * @default 0 */ left: 0, /** * Modifier added to the class to fade the drag handle. * * @property faded * @type {Boolean} * @default false */ faded: false, /** * Action to trigger whenever the drag handle is moved. * Pass this action through the template. * * @property on-drag * @type {Function} */ 'on-drag'() {}, startDragging() { this._mouseMoveHandler = this.mouseMoveHandler.bind(this); this._stopDragging = this.stopDragging.bind(this); document.body.addEventListener(`mousemove`, this._mouseMoveHandler); document.body.addEventListener(`mouseup`, this._stopDragging); document.body.addEventListener(`mouseleave`, this._stopDragging); }, stopDragging() { document.body.removeEventListener(`mousemove`, this._mouseMoveHandler); document.body.removeEventListener(`mouseup`, this._stopDragging); document.body.removeEventListener(`mouseleave`, this._stopDragging); }, willDestroyElement() { this._super(); this.stopDragging(); }, mouseDownHandler: action(function (e) { e.preventDefault(); this.el = e.target; this.startDragging(); }), style: computed('side', 'position', 'left', function () { return htmlSafe( this.side ? `${this.side}: ${this.position + this.left}px;` : '' ); }), mouseMoveHandler(e) { let container = this.el.parentNode; let containerOffsetLeft = getOffsetLeft(container); let containerOffsetRight = containerOffsetLeft + container.offsetWidth; let position = this.isLeft ? e.pageX - containerOffsetLeft : containerOffsetRight - e.pageX; position -= this.left; if (position >= this.minWidth && position <= this.maxWidth) { this.set('position', position); this['on-drag'](position); } }, }); function getOffsetLeft(elem) { let offsetLeft = 0; do { if (!isNaN(elem.offsetLeft)) { offsetLeft += elem.offsetLeft; } elem = elem.offsetParent; } while (elem.offsetParent); return offsetLeft; }
emberjs/ember-inspector
lib/ui/addon/components/drag-handle.js
JavaScript
mit
2,789
package tests import ( "time" . "github.com/smartystreets/assertions" "flywheel.io/sdk/api" ) func (t *F) TestBatch() { _, _, _, acquisitionId := t.createTestAcquisition() gearId := t.createTestGear() poem := "The falcon cannot hear the falconer;" t.uploadText(t.UploadToAcquisition, acquisitionId, "yeats.txt", poem) // Add tag := RandString() targets := []*api.ContainerReference{ { Id: acquisitionId, Type: "acquisition", }, } proposal, _, err := t.ProposeBatch(gearId, nil, []string{tag}, targets, "ignored") t.So(err, ShouldBeNil) t.So(proposal.Id, ShouldNotBeEmpty) t.So(proposal.GearId, ShouldEqual, gearId) t.So(proposal.Origin, ShouldNotBeNil) t.So(proposal.Origin.Type, ShouldEqual, "user") t.So(proposal.Origin.Id, ShouldNotBeEmpty) t.So(proposal.Matched, ShouldHaveLength, 1) t.So(proposal.Ambiguous, ShouldBeEmpty) t.So(proposal.MissingPermissions, ShouldBeEmpty) t.So(proposal.NotMatched, ShouldBeEmpty) now := time.Now() t.So(*proposal.Created, ShouldHappenBefore, now) t.So(*proposal.Modified, ShouldHappenBefore, now) t.So(proposal.OptionalInputPolicy, ShouldEqual, "ignored") // Get rBatch, _, err := t.GetBatch(proposal.Id) t.So(err, ShouldBeNil) t.So(rBatch.GearId, ShouldEqual, proposal.GearId) t.So(rBatch.State, ShouldEqual, api.Pending) // Get all batches, _, err := t.GetAllBatches() t.So(err, ShouldBeNil) t.So(batches, ShouldContain, rBatch) // Start jobs, _, err := t.StartBatch(proposal.Id) t.So(err, ShouldBeNil) t.So(jobs, ShouldHaveLength, 1) // Get again rBatch2, _, err := t.GetBatch(proposal.Id) t.So(err, ShouldBeNil) t.So(rBatch2.State, ShouldEqual, api.Running) t.So(*rBatch2.Modified, ShouldHappenAfter, *rBatch.Modified) // Cancel cancelled, _, err := t.CancelBatch(proposal.Id) t.So(err, ShouldBeNil) t.So(cancelled, ShouldEqual, 1) }
flywheel-io/core-sdk
tests/batch_test.go
GO
mit
1,847
'use strict'; const debug = require('debug')('risk:Game'); const Battle = require('./Battle'); const stateBuilder = require('./state-builder'); const constants = require('./constants'); const ERRORS = require('./errors'); const createError = require('strict-errors').createError; const events = require('./events'); const GAME_EVENTS = events.GAME_EVENTS; const PLAYER_EVENTS = events.PLAYER_EVENTS; const createEvent = require('strict-emitter').createEvent; const PHASES = constants.PHASES; const TURN_PHASES = constants.TURN_PHASES; class Game { constructor (options, rawState) { this.gameEmitter = null; this.playerEmitters = null; this.state = stateBuilder(options, rawState); this.started = false; } getState () { return this.state; } emit (event, ...args) { const playerEvents = Object.keys(PLAYER_EVENTS).map(eventKey => PLAYER_EVENTS[eventKey]); if (playerEvents.includes(event)) { const playerId = args.shift(); if (this.playerEmitters[playerId]) { const playerEmitter = this.playerEmitters[playerId]; const eventData = createEvent(event, ...args); eventData.data.playerId = playerId; this.state.setPreviousPlayerEvent({ name: eventData.name, playerId: playerId, data: eventData.data }); playerEmitter.emit(eventData.name, eventData.data); } else { debug('no player listener found', event, args); } } else if (this.gameEmitter) { const eventData = createEvent(event, ...args); this.state.setPreviousTurnEvent({ name: event.name, data: eventData.data, }); this.gameEmitter.emit(eventData.name, eventData.data); } else { debug('no game listener found'); } } setEventEmitters (gameEvents, playerEvents) { this.gameEmitter = gameEvents; this.playerEmitters = playerEvents; } get turn () { return this.state.getTurn(); } get phase () { return this.state.getPhase(); } set phase (phase) { this.state.setPhase(phase); } get turnPhase () { return this.turn.phase; } get players () { return this.state.getPlayers(); } get board () { return this.state.getBoard(); } _loadPreviousEvent (previousEvent, events) { let loadEvent = null; Object.keys(events).forEach(eventKey => { const event = events[eventKey]; if (event.name === previousEvent) { loadEvent = event; } }); return loadEvent; } isStarted () { return this.started; } start () { this.started = true; const previousTurnEvent = this.state.getPreviousTurnEvent() ? Object.assign({}, this.state.getPreviousTurnEvent()) : null; const previousPlayerEvent = this.state.getPreviousPlayerEvent() ? Object.assign({}, this.state.getPreviousPlayerEvent()) : null; this.emit(GAME_EVENTS.GAME_START, {}); this.emit(GAME_EVENTS.TURN_CHANGE, { playerId: this.turn.player.getId() }); if (previousTurnEvent && previousTurnEvent.name !== GAME_EVENTS.TURN_CHANGE.name && previousTurnEvent.name !== GAME_EVENTS.GAME_START.name) { const event = this._loadPreviousEvent(previousTurnEvent.name, GAME_EVENTS); this.emit(event, previousTurnEvent.data); } else { this.emit(GAME_EVENTS.PHASE_CHANGE, { playerId: this.turn.player.getId(), phase: this.phase }); if (this.phase === PHASES.BATTLE) { this.emit(GAME_EVENTS.TURN_PHASE_CHANGE, { playerId: this.turn.player.getId(), phase: this.turn.phase }); } } if (previousPlayerEvent) { const event = this._loadPreviousEvent(previousPlayerEvent.name, PLAYER_EVENTS); this.emit(event, previousPlayerEvent.playerId, previousPlayerEvent.data); } else { this.emit(PLAYER_EVENTS.REQUIRE_TERRITORY_CLAIM, this.turn.player.getId(), { territoryIds: this.board.getAvailableTerritories().map(territory => { return territory.getId(); }) }); } } endTurn () { const turn = this.turn; if (this.phase === PHASES.BATTLE) { this._applyMovements(); } turn.player = this.state.getPlayerQueue().next(); let afterTurnEvent = null; if (this.phase === PHASES.SETUP_A) { if (this.board.areAllTerritoriesOccupied()) { this.phase = PHASES.SETUP_B; this.emit(GAME_EVENTS.PHASE_CHANGE, { playerId: this.turn.player.getId(), phase: this.phase }); } else { afterTurnEvent = () => { this.emit(PLAYER_EVENTS.REQUIRE_TERRITORY_CLAIM, turn.player.getId(), { territoryIds: this.board.getAvailableTerritories().map(territory => { return territory.getId(); }) }); }; } } if (this.phase === PHASES.SETUP_B) { if (this._noMoreStartUnits()) { this.phase = PHASES.BATTLE; this.emit(GAME_EVENTS.PHASE_CHANGE, { playerId: this.turn.player.getId(), phase: this.phase }); } else { afterTurnEvent = () => { this.emit(PLAYER_EVENTS.REQUIRE_ONE_UNIT_DEPLOY, turn.player.getId(), { remainingUnits: this.availableUnits(), territoryIds: turn.player.getTerritories().map(territory => territory.getId()) }); }; } } if (this.phase === PHASES.BATTLE) { this._resetTurnPhase(); afterTurnEvent = () => { this.emit(PLAYER_EVENTS.REQUIRE_PLACEMENT_ACTION, turn.player.getId(), { units: this.availableUnits(), territoryIds: turn.player.getTerritories().map(territory => territory.getId()), cards: turn.player.getCards() }); }; } this.emit(GAME_EVENTS.TURN_CHANGE, { playerId: turn.player.getId() }); if (afterTurnEvent) { afterTurnEvent(); } this.state.increaseTurnCount(); } _resetTurnPhase () { this.turn.movements = new Map(); this.turn.phase = TURN_PHASES.PLACEMENT; this.turn.battle = null; this.turn.unitsPlaced = 0; this.turn.cardBonus = 0; this.turn.wonBattle = false; } claimTerritory (territory) { if (territory.getOwner()) { throw createError(ERRORS.TerritoryClaimedError, { territoryId: territory.getId(), owner: territory.getOwner().getId() }); } this.turn.player.removeStartUnit(); territory.setOwner(this.turn.player); territory.setUnits(1); this.turn.player.addTerritory(territory); this.emit(GAME_EVENTS.TERRITORY_CLAIMED, { playerId: this.turn.player.getId(), territoryId: territory.getId(), units: 1 }); this.endTurn(); } deployOneUnit (territory) { if (territory.getOwner() !== this.turn.player) { throw createError(ERRORS.NotOwnTerritoryError, { territoryId: territory.getId(), owner: territory.getOwner().getId() }); } if (!this.turn.player.hasStartUnits()) { throw createError(ERRORS.NoStartingUnitsError); } this.turn.player.removeStartUnit(); territory.addUnits(1); this.emit(GAME_EVENTS.DEPLOY_UNITS, { playerId: this.turn.player.getId(), territoryId: territory.getId(), units: 1 }); this.endTurn(); } deployUnits (territory, units) { if (Number.isNaN(units) || units < 1) { throw createError(ERRORS.InvalidUnitsError, { units }); } if (territory.getOwner() !== this.turn.player) { throw createError(ERRORS.NotOwnTerritoryError, { territoryId: territory.getId(), owner: territory.getOwner().getId() }); } const availableUnits = this.availableUnits(); if (availableUnits >= units && availableUnits - units > -1) { this.turn.unitsPlaced += units; territory.addUnits(units); this.emit(GAME_EVENTS.DEPLOY_UNITS, { playerId: this.turn.player.getId(), territoryId: territory.getId(), units: units }); } else { throw createError(ERRORS.NoUnitsError); } } attackPhase () { if (this.turn.player.getCards().length > 4) { throw createError(ERRORS.RequireCardRedeemError, { cards: this.turn.player.getCards() }); } const availableUnits = this.availableUnits(); if (availableUnits !== 0) { throw createError(ERRORS.RequireDeployError, { units: availableUnits }); } this.turn.phase = TURN_PHASES.ATTACKING; this.emit(GAME_EVENTS.TURN_PHASE_CHANGE, { playerId: this.turn.player.getId(), phase: this.turn.phase }); this.emit(PLAYER_EVENTS.REQUIRE_ATTACK_ACTION, this.turn.player.getId(), {}); } redeemCards (cards) { if (cards.length !== 3) { throw createError(ERRORS.NumberOfCardsError); } if (!this.turn.player.hasCards(cards)) { throw createError(ERRORS.NotOwnCardsError, { cards }); } const bonus = this.state.getCardManager().getBonus(cards); for (const card of cards) { this.turn.player.removeCard(card); this.state.getCardManager().pushCard(card); } this.turn.cardBonus += bonus; this.emit(GAME_EVENTS.REDEEM_CARDS, { playerId: this.turn.player.getId(), cards: cards, bonus: bonus }); } attack (fromTerritory, toTerritory, units) { if (this.turn.battle) { throw createError(ERRORS.AlreadyInBattleError); } if (Number.isNaN(units) || units < 1) { throw createError(ERRORS.InvalidUnitsEror, { units }); } if (fromTerritory.getOwner() !== this.turn.player) { throw createError(ERRORS.NotOwnTerritoryError, { territoryId: fromTerritory.getId(), owner: fromTerritory.getOwner().getId() }); } if (toTerritory.getOwner() === this.turn.player) { throw createError(ERRORS.AttackSelfError, { territoryId: toTerritory.getId() }); } if (units > fromTerritory.getUnits() - 1) { throw createError(ERRORS.LeaveOneUnitError); } this.turn.battle = Battle.create({ from: fromTerritory, to: toTerritory, units }); this.emit(GAME_EVENTS.ATTACK, { from: fromTerritory.getId(), to: toTerritory.getId(), attacker: this.turn.player.getId(), defender: toTerritory.getOwner().getId(), units: units }); this.emit(PLAYER_EVENTS.REQUIRE_DICE_ROLL, this.turn.player.getId(), { type: 'attacker', maxDice: Math.min(3, this.turn.battle.getAttackUnits()) }); } rollDice (numberOfDice) { const battle = this.turn.battle; if (Number.isNaN(numberOfDice) || numberOfDice < 1) { throw createError(ERRORS.InvalidDiceError, { dice: numberOfDice }); } if (battle.getAttacker() === battle.getTurn()) { const playerId = battle.getTurn().getId(); const dice = battle.attackThrow(numberOfDice); this.emit(GAME_EVENTS.ATTACK_DICE_ROLL, { playerId, dice }); if (!battle.hasEnded()) { this.emit(PLAYER_EVENTS.REQUIRE_DICE_ROLL, battle.getDefender().getId(), { type: 'defender', maxDice: Math.min(2, battle.getDefendUnits()) }); } else { this._endBattle(); } } else if (battle.getDefender() === battle.getTurn()) { const playerId = battle.getTurn().getId(); const defendResults = battle.defendThrow(numberOfDice); this.emit(GAME_EVENTS.DEFEND_DICE_ROLL, { dice: defendResults.dice, results: defendResults.results, playerId: playerId }); if (!battle.hasEnded()) { this.emit(PLAYER_EVENTS.REQUIRE_DICE_ROLL, battle.getAttacker().getId(), { type: 'attacker', maxDice: Math.min(3, battle.getAttackUnits()), }); } else { this._endBattle(); } } else { throw createError(ERRORS.NotInBattleError); } } _endBattle () { const battle = this.turn.battle; if (battle.hasEnded()) { this.emit(GAME_EVENTS.BATTLE_END, { type: battle.getWinner() === battle.getAttacker() ? 'attacker' : 'defender', winner: battle.hasEnded() ? battle.getWinner().getId() : null, }); if (battle.getWinner() === this.turn.player) { this.turn.wonBattle = true; if (battle.getDefender().isDead()) { this._killPlayer(battle.getAttacker(), battle.getDefender()); } } this.turn.battle = null; if (this.isGameOver()) { this._endGame(); } else { this.emit(PLAYER_EVENTS.REQUIRE_ATTACK_ACTION, this.turn.player.getId(), {}); } } } fortifyPhase () { if (this.turn.wonBattle) { this._grabCard(); } this.turn.phase = TURN_PHASES.FORTIFYING; this.emit(GAME_EVENTS.TURN_PHASE_CHANGE, { playerId: this.turn.player.getId(), phase: this.turn.phase }); this.emit(PLAYER_EVENTS.REQUIRE_FORTIFY_ACTION, this.turn.player.getId(), {}); } moveUnits (fromTerritory, toTerritory, units) { const player = this.turn.player; if (Number.isNaN(units) || units < 1) { throw createError(ERRORS.InvalidUnitsError, { units }); } if (fromTerritory.getOwner() !== player || toTerritory.getOwner() !== player) { throw createError(ERRORS.MoveOwnTerritoriesError, { territoryIds: [ fromTerritory.getOwner() !== player ? fromTerritory.getId() : null, toTerritory.getOwner() !== player ? toTerritory.getId() : null ].filter(Boolean) }); } if (!fromTerritory.isAdjacentTo(toTerritory)) { throw createError(ERRORS.TerritoriesAdjacentError, { territoryIds: [fromTerritory.getId(), toTerritory.getId()] }); } if (fromTerritory.getUnits() - units <= 0) { throw createError(ERRORS.LeaveOneUnitError); } const move = { from: fromTerritory, to: toTerritory, units: units }; this.turn.movements.set(fromTerritory.getId(), move); this.emit(PLAYER_EVENTS.QUEUED_MOVE, player.getId(), { from: move.from.getId(), to: move.to.getId(), units: move.units }); } isGameOver () { const playerCount = Array.from(this.players.values()).filter(player => !player.isDead()).length; return playerCount === 1; } winner () { const remainingPlayers = Array.from(this.players.values()).filter(player => !player.isDead()); if (remainingPlayers.length === 1) { return remainingPlayers[0]; } return null; } _noMoreStartUnits () { return Array.from(this.players.values()).every(player => { return !player.hasStartUnits(); }); } _killPlayer (killer, killed) { this.state.getPlayerQueue().remove(killed); // Get cards from the killed player const takenCards = []; for (const card of killed.getCards()) { killer.addCard(card); killed.removeCard(card); takenCards.push(card); this.emit(PLAYER_EVENTS.NEW_CARD, killer.getId(), { card: card }); } this.emit(GAME_EVENTS.PLAYER_DEFEATED, { defeatedBy: killer.getId(), playerId: killed.getId(), numberOfCardsTaken: takenCards.length }); } availableUnits (player) { player = player || this.turn.player; if ([PHASES.SETUP_A, PHASES.SETUP_B].includes(this.phase)) { return player.getStartUnits(); } const bonusUnits = this.bonusUnits(player); debug('bonus', bonusUnits); const unitsPlaced = this.turn.player === player ? this.turn.unitsPlaced : 0; return bonusUnits.total - unitsPlaced; } bonusUnits (player) { player = player || this.turn.player; const territories = this.board.getPlayerTerritories(player); let territoryBonus = Math.floor(territories.length / 3); territoryBonus = territoryBonus < 3 ? 3 : territoryBonus; const continents = this.board.getPlayerContinents(player); const continentBonus = continents.reduce((totalBonus, continent) => { return totalBonus + continent.getBonus(); }, 0); const cardBonus = this.turn.player === player ? this.turn.cardBonus : 0; return { territoryBonus: territoryBonus, continentBonus: continentBonus, cardBonus: cardBonus, total: territoryBonus + continentBonus + cardBonus }; } _applyMovements () { const movements = []; for (const move of this.turn.movements.values()) { movements.push({ from: move.from.getId(), to: move.to.getId(), units: move.units }); move.from.removeUnits(move.units); move.to.addUnits(move.units); } this.turn.movements.clear(); this.emit(GAME_EVENTS.MOVE_UNITS, { playerId: this.turn.player.getId(), movements: movements }); } _grabCard () { const card = this.state.getCardManager().popCard(); this.turn.player.addCard(card); this.emit(PLAYER_EVENTS.NEW_CARD, this.turn.player.getId(), { card: card }); } _endGame () { this.emit(GAME_EVENTS.GAME_END, { winner: this.winner().getId() }); } } module.exports = Game;
arjanfrans/conquete
lib/Game.js
JavaScript
mit
19,761
using System.Collections.Generic; using System.Linq; using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Entities; using OfficeDevPnP.Core.Framework.Provisioning.Model; using File = Microsoft.SharePoint.Client.File; using OfficeDevPnP.Core.Diagnostics; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Extensions; using System; using System.Net; using System.IO; using Newtonsoft.Json; using OfficeDevPnP.Core.Utilities; using Microsoft.SharePoint.Client.Taxonomy; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.TokenDefinitions; using OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers.Utilities; namespace OfficeDevPnP.Core.Framework.Provisioning.ObjectHandlers { internal class ObjectFiles : ObjectHandlerBase { private readonly string[] WriteableReadOnlyFields = new string[] { "publishingpagelayout", "contenttypeid" }; // See https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f?ui=en-US&rs=en-US&ad=US public static readonly string[] BlockedExtensionsInNoScript = new string[] { ".asmx", ".ascx", ".aspx", ".htc", ".jar", ".master", ".swf", ".xap", ".xsf" }; public static readonly string[] BlockedLibrariesInNoScript = new string[] { "_catalogs/theme", "style library", "_catalogs/lt", "_catalogs/wp" }; public override string Name { get { return "Files"; } } public override string InternalName => "Files"; public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { // Check if this is not a noscript site as we're not allowed to write to the web property bag is that one bool isNoScriptSite = web.IsNoScriptSite(); web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url); // Build on the fly the list of additional files coming from the Directories var directoryFiles = new List<Model.File>(); foreach (var directory in template.Directories) { var metadataProperties = directory.GetMetadataProperties(); directoryFiles.AddRange(directory.GetDirectoryFiles(metadataProperties)); } var filesToProcess = template.Files.Union(directoryFiles).ToArray(); var siteAssetsFiles = filesToProcess.Where(f => f.Folder.ToLower().Contains("siteassets")).FirstOrDefault(); if (siteAssetsFiles != null) { // Need this so that we dont have access denied error during the first time upload, especially for modern sites web.Lists.EnsureSiteAssetsLibrary(); web.Context.ExecuteQueryRetry(); } var currentFileIndex = 0; var originalWeb = web; // Used to store and re-store context in case files are deployed to masterpage gallery foreach (var file in filesToProcess) { file.Src = parser.ParseString(file.Src); var targetFileName = parser.ParseString( !String.IsNullOrEmpty(file.TargetFileName) ? file.TargetFileName : template.Connector.GetFilenamePart(file.Src) ); currentFileIndex++; WriteSubProgress("File", targetFileName, currentFileIndex, filesToProcess.Length); var folderName = parser.ParseString(file.Folder); if (folderName.ToLower().Contains("/_catalogs/")) { // Edge case where you have files in the template which should be provisioned to the site collection // master page gallery and not to a connected subsite web = web.Context.GetSiteCollectionContext().Web; web.EnsureProperties(w => w.ServerRelativeUrl, w => w.Url); } if (folderName.ToLower().StartsWith((web.ServerRelativeUrl.ToLower()))) { folderName = folderName.Substring(web.ServerRelativeUrl.Length); } if (SkipFile(isNoScriptSite, targetFileName, folderName)) { // add log message scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_Files_SkipFileUpload, targetFileName, folderName); continue; } var folder = web.EnsureFolderPath(folderName); #if !SP2013 //register folder UniqueId as Token folder.EnsureProperties(p => p.UniqueId, p => p.ServerRelativeUrl); parser.AddToken(new FileUniqueIdToken(web, folder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), folder.UniqueId)); parser.AddToken(new FileUniqueIdEncodedToken(web, folder.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), folder.UniqueId)); #endif var checkedOut = false; var targetFile = folder.GetFile(template.Connector.GetFilenamePart(targetFileName)); if (targetFile != null) { if (file.Overwrite) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_and_overwriting_existing_file__0_, targetFileName); checkedOut = CheckOutIfNeeded(web, targetFile); using (var stream = FileUtilities.GetFileStream(template, file)) { targetFile = UploadFile(folder, stream, targetFileName, file.Overwrite); } } else { checkedOut = CheckOutIfNeeded(web, targetFile); } } else { using (var stream = FileUtilities.GetFileStream(template, file)) { if (stream == null) { throw new FileNotFoundException($"File {file.Src} does not exist"); } else { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Uploading_file__0_, targetFileName); targetFile = UploadFile(folder, stream, targetFileName, file.Overwrite); } } checkedOut = CheckOutIfNeeded(web, targetFile); } if (targetFile != null) { // Add the fileuniqueid tokens #if !SP2013 targetFile.EnsureProperties(p => p.UniqueId, p => p.ServerRelativeUrl); parser.AddToken(new FileUniqueIdToken(web, targetFile.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), targetFile.UniqueId)); parser.AddToken(new FileUniqueIdEncodedToken(web, targetFile.ServerRelativeUrl.Substring(web.ServerRelativeUrl.Length).TrimStart("/".ToCharArray()), targetFile.UniqueId)); #endif #if !SP2013 bool webPartsNeedLocalization = false; #endif if (file.WebParts != null && file.WebParts.Any()) { targetFile.EnsureProperties(f => f.ServerRelativeUrl); var existingWebParts = web.GetWebParts(targetFile.ServerRelativeUrl).ToList(); foreach (var webPart in file.WebParts) { // check if the webpart is already set on the page if (existingWebParts.FirstOrDefault(w => w.WebPart.Title == parser.ParseString(webPart.Title)) == null) { scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_Files_Adding_webpart___0___to_page, webPart.Title); var wpEntity = new WebPartEntity(); wpEntity.WebPartTitle = parser.ParseString(webPart.Title); wpEntity.WebPartXml = parser.ParseXmlString(webPart.Contents).Trim(new[] { '\n', ' ' }); wpEntity.WebPartZone = webPart.Zone; wpEntity.WebPartIndex = (int)webPart.Order; var wpd = web.AddWebPartToWebPartPage(targetFile.ServerRelativeUrl, wpEntity); #if !SP2013 if (webPart.Title.ContainsResourceToken()) { // update data based on where it was added - needed in order to localize wp title wpd.EnsureProperties(w => w.ZoneId, w => w.WebPart, w => w.WebPart.Properties); webPart.Zone = wpd.ZoneId; webPart.Order = (uint)wpd.WebPart.ZoneIndex; webPartsNeedLocalization = true; } #endif } } } #if !SP2013 if (webPartsNeedLocalization) { file.LocalizeWebParts(web, parser, targetFile, scope); } #endif //Set Properties before Checkin if (file.Properties != null && file.Properties.Any()) { Dictionary<string, string> transformedProperties = file.Properties.ToDictionary(property => property.Key, property => parser.ParseString(property.Value)); SetFileProperties(targetFile, transformedProperties, parser, false); } switch (file.Level) { case Model.FileLevel.Published: { targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Published); break; } case Model.FileLevel.Draft: { targetFile.PublishFileToLevel(Microsoft.SharePoint.Client.FileLevel.Draft); break; } default: { if (checkedOut) { targetFile.CheckIn("", CheckinType.MajorCheckIn); web.Context.ExecuteQueryRetry(); } break; } } // Don't set security when nothing is defined. This otherwise breaks on files set outside of a list if (file.Security != null && (file.Security.ClearSubscopes == true || file.Security.CopyRoleAssignments == true || file.Security.RoleAssignments.Count > 0)) { targetFile.ListItemAllFields.SetSecurity(parser, file.Security, WriteMessage); } } web = originalWeb; // restore context in case files are provisioned to the master page gallery #1059 } } WriteMessage("Done processing files", ProvisioningMessageType.Completed); return parser; } private static bool CheckOutIfNeeded(Web web, File targetFile) { var checkedOut = false; try { web.Context.Load(targetFile, f => f.CheckOutType, f => f.CheckedOutByUser, f => f.ListItemAllFields.ParentList.ForceCheckout); web.Context.ExecuteQueryRetry(); if (targetFile.ListItemAllFields.ServerObjectIsNull.HasValue && !targetFile.ListItemAllFields.ServerObjectIsNull.Value && targetFile.ListItemAllFields.ParentList.ForceCheckout) { if (targetFile.CheckOutType == CheckOutType.None) { targetFile.CheckOut(); } checkedOut = true; } } catch (ServerException ex) { // Handling the exception stating the "The object specified does not belong to a list." #if !ONPREMISES if (ex.ServerErrorCode != -2113929210) #else if (ex.ServerErrorCode != -2146232832) #endif { throw; } } return checkedOut; } public override ProvisioningTemplate ExtractObjects(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { return template; } public void SetFileProperties(File file, IDictionary<string, string> properties, bool checkoutIfRequired = true) { SetFileProperties(file, properties, null, checkoutIfRequired); } public void SetFileProperties(File file, IDictionary<string, string> properties, TokenParser parser, bool checkoutIfRequired = true) { var context = file.Context; if (properties != null && properties.Count > 0) { // Get a reference to the target list, if any // and load file item properties var parentList = file.ListItemAllFields.ParentList; context.Load(parentList); context.Load(file.ListItemAllFields); try { context.ExecuteQueryRetry(); } catch (ServerException ex) { // If this throws ServerException (does not belong to list), then shouldn't be trying to set properties) #if !ONPREMISES if (ex.ServerErrorCode != -2113929210) #else if (ex.ServerErrorCode != -2146232832) #endif { throw; } } ListItemUtilities.UpdateListItem(file.ListItemAllFields, parser, properties, ListItemUtilities.ListItemUpdateType.UpdateOverwriteVersion); } } /// <summary> /// Checks if a given file can be uploaded. Sites using NoScript can't handle all uploads /// </summary> /// <param name="isNoScriptSite">Is this a noscript site?</param> /// <param name="fileName">Filename to verify</param> /// <param name="folderName">Folder (library) to verify</param> /// <returns>True is the file will not be uploaded, false otherwise</returns> public static bool SkipFile(bool isNoScriptSite, string fileName, string folderName) { string fileExtionsion = Path.GetExtension(fileName).ToLower(); if (isNoScriptSite) { if (!String.IsNullOrEmpty(fileExtionsion) && BlockedExtensionsInNoScript.Contains(fileExtionsion)) { // We need to skip this file return true; } if (!String.IsNullOrEmpty(folderName)) { foreach (string blockedlibrary in BlockedLibrariesInNoScript) { if (folderName.ToLower().StartsWith(blockedlibrary)) { // Can't write to this library, let's skip return true; } } } } return false; } public override bool WillProvision(Web web, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation) { if (!_willProvision.HasValue) { _willProvision = template.Files.Any() | template.Directories.Any(); } return _willProvision.Value; } public override bool WillExtract(Web web, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo) { if (!_willExtract.HasValue) { _willExtract = false; } return _willExtract.Value; } private static File UploadFile(Microsoft.SharePoint.Client.Folder folder, Stream stream, string fileName, bool overwrite) { if (folder == null) throw new ArgumentNullException(nameof(folder)); if (stream == null) throw new ArgumentNullException(nameof(stream)); File targetFile = null; try { targetFile = folder.UploadFile(fileName, stream, overwrite); } catch (ServerException ex) { if (ex.ServerErrorCode != -2130575306) //Error code: -2130575306 = The file is already checked out. { //The file name might contain encoded characters that prevent upload. Decode it and try again. fileName = WebUtility.UrlDecode(fileName); try { targetFile = folder.UploadFile(fileName, stream, overwrite); } catch (Exception) { //unable to Upload file, just ignore } } } return targetFile; } } }
OfficeDev/PnP-Sites-Core
Core/OfficeDevPnP.Core/Framework/Provisioning/ObjectHandlers/ObjectFiles.cs
C#
mit
18,721
<?php namespace Swarrot\SwarrotBundle\Event; use Symfony\Component\EventDispatcher\Event; use Swarrot\Broker\Message; class MessagePublishedEvent extends Event { const NAME = 'swarrot.message_published'; protected $messageType; protected $message; protected $connection; protected $exchange; protected $routingKey; public function __construct($messageType, Message $message, $connection, $exchange, $routingKey) { $this->messageType = $messageType; $this->message = $message; $this->connection = $connection; $this->exchange = $exchange; $this->routingKey = $routingKey; } /** * getMessageType * * @return string */ public function getMessageType() { return $this->messageType; } /** * getMessage * * @return Message */ public function getMessage() { return $this->message; } /** * getConnection * * @return string */ public function getConnection() { return $this->connection; } /** * getExchange * * @return string */ public function getExchange() { return $this->exchange; } /** * getRoutingKey * * @return string */ public function getRoutingKey() { return $this->routingKey; } }
stof/SwarrotBundle
Event/MessagePublishedEvent.php
PHP
mit
1,399
goog.provide('Mavelous.MavlinkAPI'); goog.provide('Mavelous.MavlinkMessage'); goog.require('Mavelous.FakeVehicle'); goog.require('goog.debug.Logger'); /** * A mavlink message. * * @param {{_type: string, _index: number}} attrs The message attributes. * @constructor * @extends {Backbone.Model} */ Mavelous.MavlinkMessage = function(attrs) { goog.base(this, attrs); }; goog.inherits(Mavelous.MavlinkMessage, Backbone.Model); /** * Fetches the most recent mavlink messages of interest from the * server. * * @param {{url: string}} attrs Attributes. * @constructor * @extends {Backbone.Model} */ Mavelous.MavlinkAPI = function(attrs) { goog.base(this, attrs); }; goog.inherits(Mavelous.MavlinkAPI, Backbone.Model); /** * @override * @export */ Mavelous.MavlinkAPI.prototype.initialize = function() { /** @type {goog.debug.Logger} */ this.logger_ = goog.debug.Logger.getLogger('mavelous.MavlinkAPI'); /** @type {string} */ this.url = this.get('url'); /** @type {boolean} */ this.gotonline = false; /** @type {boolean} */ this.online = true; /** @type {number} */ this.failcount = 0; // Table of message models, keyed by message type. /** @type {Object.<string, Mavelous.MavlinkMessage>} */ this.messageModels = {}; /** @type {?Mavelous.FakeVehicle} */ this.fakevehicle = null; }; /** * Registers a handler for a mavlink message type. * * @param {string} msgType The type of message. * @param {function(Object)} handlerFunction The message handler function. * @param {Object} context Specifies the object which |this| should * point to when the function is run. * @return {Mavelous.MavlinkMessage} The message model. */ Mavelous.MavlinkAPI.prototype.subscribe = function( msgType, handlerFunction, context) { if (!this.messageModels[msgType]) { this.messageModels[msgType] = new Mavelous.MavlinkMessage({ '_type': msgType, '_index': -1}); } var model = this.messageModels[msgType]; model.bind('change', handlerFunction, context); return model; }; /** * Handles an array of incoming mavlink messages. * @param {Object} msgEnvelopes The messages. * @private */ Mavelous.MavlinkAPI.prototype.handleMessages_ = function(msgEnvelopes) { this.trigger('gotServerResponse'); _.each(msgEnvelopes, this.handleMessage_, this); }; /** * Handles an incoming message. * * @param {Object} msg The JSON mavlink message. * @param {string} msgType The message type. * @private */ Mavelous.MavlinkAPI.prototype.handleMessage_ = function(msg, msgType) { // Update the model if this is a new message for this type. var msgModel = this.messageModels[msgType]; var mdlidx = msgModel.get('_index'); if (mdlidx === undefined || msg.index > mdlidx) { msgModel.set({ '_index': msg.index }, { 'silent': true }); msgModel.set(msg.msg); } }; /** * Gets the latest mavlink messages from the server (or from the fake * model, if we're offline). */ Mavelous.MavlinkAPI.prototype.update = function() { if (this.online) { this.onlineUpdate(); } else { this.offlineUpdate(); } }; /** * Gets the latest mavlink messages from the server. */ Mavelous.MavlinkAPI.prototype.onlineUpdate = function() { $.ajax({ context: this, type: 'GET', cache: false, url: this.url + _.keys(this.messageModels).join('+'), datatype: 'json', success: function(data) { this.gotonline = true; this.handleMessages_(data); }, error: function() { this.trigger('gotServerError'); if (!this.gotonline) { this.failcount++; if (this.failcount > 5) { this.useOfflineMode(); } } } }); }; /** * Gets the latest fake messages if we're in offline mode. */ Mavelous.MavlinkAPI.prototype.offlineUpdate = function() { goog.asserts.assert(this.fakevehicle); this.fakevehicle.update(); var msgs = this.fakevehicle.requestMessages(this.messageModels); this.handleMessages_(msgs); }; /** * Switches to offline mode. */ Mavelous.MavlinkAPI.prototype.useOfflineMode = function() { if (this.online && !this.gotonline) { this.logger_.info('Switching to offline mode'); this.online = false; this.fakevehicle = new Mavelous.FakeVehicle({ 'lat': 45.5233, 'lon': -122.6670 }); } };
jiusanzhou/mavelous
modules/lib/mavelous_web/script/mavlinkapi.js
JavaScript
mit
4,319
/* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.ml.bayesian; import junit.framework.Assert; import junit.framework.TestCase; import org.encog.ml.bayesian.query.enumerate.EnumerationQuery; public class TestEnumerationQuery extends TestCase { private void testPercent(double d, int target) { if (((int) d) >= (target - 2) && ((int) d) <= (target + 2)) { Assert.assertTrue(false); } } public void testEnumeration1() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.createEvent("a"); BayesianEvent b = network.createEvent("b"); network.createDependency(a, b); network.finalizeStructure(); a.getTable().addLine(0.5, true); // P(A) = 0.5 b.getTable().addLine(0.2, true, true); // p(b|a) = 0.2 b.getTable().addLine(0.8, true, false);// p(b|~a) = 0.8 network.validate(); EnumerationQuery query = new EnumerationQuery(network); query.defineEventType(a, EventType.Evidence); query.defineEventType(b, EventType.Outcome); query.setEventValue(b, true); query.setEventValue(a, true); query.execute(); testPercent(query.getProbability(), 20); } public void testEnumeration2() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.createEvent("a"); BayesianEvent x1 = network.createEvent("x1"); BayesianEvent x2 = network.createEvent("x2"); BayesianEvent x3 = network.createEvent("x3"); network.createDependency(a, x1, x2, x3); network.finalizeStructure(); a.getTable().addLine(0.5, true); // P(A) = 0.5 x1.getTable().addLine(0.2, true, true); // p(x1|a) = 0.2 x1.getTable().addLine(0.6, true, false);// p(x1|~a) = 0.6 x2.getTable().addLine(0.2, true, true); // p(x2|a) = 0.2 x2.getTable().addLine(0.6, true, false);// p(x2|~a) = 0.6 x3.getTable().addLine(0.2, true, true); // p(x3|a) = 0.2 x3.getTable().addLine(0.6, true, false);// p(x3|~a) = 0.6 network.validate(); EnumerationQuery query = new EnumerationQuery(network); query.defineEventType(x1, EventType.Evidence); query.defineEventType(x2, EventType.Evidence); query.defineEventType(x3, EventType.Evidence); query.defineEventType(a, EventType.Outcome); query.setEventValue(a, true); query.setEventValue(x1, true); query.setEventValue(x2, true); query.setEventValue(x3, false); query.execute(); testPercent(query.getProbability(), 18); } public void testEnumeration3() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.createEvent("a"); BayesianEvent x1 = network.createEvent("x1"); BayesianEvent x2 = network.createEvent("x2"); BayesianEvent x3 = network.createEvent("x3"); network.createDependency(a, x1, x2, x3); network.finalizeStructure(); a.getTable().addLine(0.5, true); // P(A) = 0.5 x1.getTable().addLine(0.2, true, true); // p(x1|a) = 0.2 x1.getTable().addLine(0.6, true, false);// p(x1|~a) = 0.6 x2.getTable().addLine(0.2, true, true); // p(x2|a) = 0.2 x2.getTable().addLine(0.6, true, false);// p(x2|~a) = 0.6 x3.getTable().addLine(0.2, true, true); // p(x3|a) = 0.2 x3.getTable().addLine(0.6, true, false);// p(x3|~a) = 0.6 network.validate(); EnumerationQuery query = new EnumerationQuery(network); query.defineEventType(x1, EventType.Evidence); query.defineEventType(x3, EventType.Outcome); query.setEventValue(x1, true); query.setEventValue(x3, true); query.execute(); testPercent(query.getProbability(), 50); } }
ladygagapowerbot/bachelor-thesis-implementation
lib/Encog/src/test/java/org/encog/ml/bayesian/TestEnumerationQuery.java
Java
mit
4,674
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as SsnProvider import random class Provider(SsnProvider): #in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum #this function essentially reverses the checksum steps to create a random valid SIN (Social Insurance Number) @classmethod def ssn(cls): #create an array of 8 elements initialized randomly digits = random.sample(range(10), 8) # All of the digits must sum to a multiple of 10. # sum the first 8 and set 9th to the value to get to a multiple of 10 digits.append(10 - (sum(digits) % 10)) #digits is now the digital root of the number we want multiplied by the magic number 121 212 121 #reverse the multiplication which occurred on every other element for i in range(1, len(digits), 2): if digits[i] % 2 == 0: digits[i] = (digits[i] / 2) else: digits[i] = (digits[i] + 9) / 2 #build the resulting SIN string sin = "" for i in range(0, len(digits), 1): sin += str(digits[i]) #add a space to make it conform to normal standards in Canada if i % 3 == 2: sin += " " #finally return our random but valid SIN return sin
venmo/faker
faker/providers/ssn/en_CA/__init__.py
Python
mit
1,457
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import * as Json from 'jsonc-parser'; import { isNumber, equals, isBoolean, isString, isDefined } from '../utils/objects'; import { ErrorCode, Diagnostic, DiagnosticSeverity, Range } from '../jsonLanguageTypes'; import * as nls from 'vscode-nls'; var localize = nls.loadMessageBundle(); var formats = { 'color-hex': { errorMessage: localize('colorHexFormatWarning', 'Invalid color format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.'), pattern: /^#([0-9A-Fa-f]{3,4}|([0-9A-Fa-f]{2}){3,4})$/ }, 'date-time': { errorMessage: localize('dateTimeFormatWarning', 'String is not a RFC3339 date-time.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i }, 'date': { errorMessage: localize('dateFormatWarning', 'String is not a RFC3339 date.'), pattern: /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/i }, 'time': { errorMessage: localize('timeFormatWarning', 'String is not a RFC3339 time.'), pattern: /^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))$/i }, 'email': { errorMessage: localize('emailFormatWarning', 'String is not an e-mail address.'), pattern: /^(([^<>()\[\]\\.,;:\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,}))$/ } }; var ASTNodeImpl = /** @class */ (function () { function ASTNodeImpl(parent, offset, length) { this.offset = offset; this.length = length; this.parent = parent; } Object.defineProperty(ASTNodeImpl.prototype, "children", { get: function () { return []; }, enumerable: true, configurable: true }); ASTNodeImpl.prototype.toString = function () { return 'type: ' + this.type + ' (' + this.offset + '/' + this.length + ')' + (this.parent ? ' parent: {' + this.parent.toString() + '}' : ''); }; return ASTNodeImpl; }()); export { ASTNodeImpl }; var NullASTNodeImpl = /** @class */ (function (_super) { __extends(NullASTNodeImpl, _super); function NullASTNodeImpl(parent, offset) { var _this = _super.call(this, parent, offset) || this; _this.type = 'null'; _this.value = null; return _this; } return NullASTNodeImpl; }(ASTNodeImpl)); export { NullASTNodeImpl }; var BooleanASTNodeImpl = /** @class */ (function (_super) { __extends(BooleanASTNodeImpl, _super); function BooleanASTNodeImpl(parent, boolValue, offset) { var _this = _super.call(this, parent, offset) || this; _this.type = 'boolean'; _this.value = boolValue; return _this; } return BooleanASTNodeImpl; }(ASTNodeImpl)); export { BooleanASTNodeImpl }; var ArrayASTNodeImpl = /** @class */ (function (_super) { __extends(ArrayASTNodeImpl, _super); function ArrayASTNodeImpl(parent, offset) { var _this = _super.call(this, parent, offset) || this; _this.type = 'array'; _this.items = []; return _this; } Object.defineProperty(ArrayASTNodeImpl.prototype, "children", { get: function () { return this.items; }, enumerable: true, configurable: true }); return ArrayASTNodeImpl; }(ASTNodeImpl)); export { ArrayASTNodeImpl }; var NumberASTNodeImpl = /** @class */ (function (_super) { __extends(NumberASTNodeImpl, _super); function NumberASTNodeImpl(parent, offset) { var _this = _super.call(this, parent, offset) || this; _this.type = 'number'; _this.isInteger = true; _this.value = Number.NaN; return _this; } return NumberASTNodeImpl; }(ASTNodeImpl)); export { NumberASTNodeImpl }; var StringASTNodeImpl = /** @class */ (function (_super) { __extends(StringASTNodeImpl, _super); function StringASTNodeImpl(parent, offset, length) { var _this = _super.call(this, parent, offset, length) || this; _this.type = 'string'; _this.value = ''; return _this; } return StringASTNodeImpl; }(ASTNodeImpl)); export { StringASTNodeImpl }; var PropertyASTNodeImpl = /** @class */ (function (_super) { __extends(PropertyASTNodeImpl, _super); function PropertyASTNodeImpl(parent, offset) { var _this = _super.call(this, parent, offset) || this; _this.type = 'property'; _this.colonOffset = -1; return _this; } Object.defineProperty(PropertyASTNodeImpl.prototype, "children", { get: function () { return this.valueNode ? [this.keyNode, this.valueNode] : [this.keyNode]; }, enumerable: true, configurable: true }); return PropertyASTNodeImpl; }(ASTNodeImpl)); export { PropertyASTNodeImpl }; var ObjectASTNodeImpl = /** @class */ (function (_super) { __extends(ObjectASTNodeImpl, _super); function ObjectASTNodeImpl(parent, offset) { var _this = _super.call(this, parent, offset) || this; _this.type = 'object'; _this.properties = []; return _this; } Object.defineProperty(ObjectASTNodeImpl.prototype, "children", { get: function () { return this.properties; }, enumerable: true, configurable: true }); return ObjectASTNodeImpl; }(ASTNodeImpl)); export { ObjectASTNodeImpl }; export function asSchema(schema) { if (isBoolean(schema)) { return schema ? {} : { "not": {} }; } return schema; } export var EnumMatch; (function (EnumMatch) { EnumMatch[EnumMatch["Key"] = 0] = "Key"; EnumMatch[EnumMatch["Enum"] = 1] = "Enum"; })(EnumMatch || (EnumMatch = {})); var SchemaCollector = /** @class */ (function () { function SchemaCollector(focusOffset, exclude) { if (focusOffset === void 0) { focusOffset = -1; } if (exclude === void 0) { exclude = null; } this.focusOffset = focusOffset; this.exclude = exclude; this.schemas = []; } SchemaCollector.prototype.add = function (schema) { this.schemas.push(schema); }; SchemaCollector.prototype.merge = function (other) { var _a; (_a = this.schemas).push.apply(_a, other.schemas); }; SchemaCollector.prototype.include = function (node) { return (this.focusOffset === -1 || contains(node, this.focusOffset)) && (node !== this.exclude); }; SchemaCollector.prototype.newSub = function () { return new SchemaCollector(-1, this.exclude); }; return SchemaCollector; }()); var NoOpSchemaCollector = /** @class */ (function () { function NoOpSchemaCollector() { } Object.defineProperty(NoOpSchemaCollector.prototype, "schemas", { get: function () { return []; }, enumerable: true, configurable: true }); NoOpSchemaCollector.prototype.add = function (schema) { }; NoOpSchemaCollector.prototype.merge = function (other) { }; NoOpSchemaCollector.prototype.include = function (node) { return true; }; NoOpSchemaCollector.prototype.newSub = function () { return this; }; NoOpSchemaCollector.instance = new NoOpSchemaCollector(); return NoOpSchemaCollector; }()); var ValidationResult = /** @class */ (function () { function ValidationResult() { this.problems = []; this.propertiesMatches = 0; this.propertiesValueMatches = 0; this.primaryValueMatches = 0; this.enumValueMatch = false; this.enumValues = null; } ValidationResult.prototype.hasProblems = function () { return !!this.problems.length; }; ValidationResult.prototype.mergeAll = function (validationResults) { for (var _i = 0, validationResults_1 = validationResults; _i < validationResults_1.length; _i++) { var validationResult = validationResults_1[_i]; this.merge(validationResult); } }; ValidationResult.prototype.merge = function (validationResult) { this.problems = this.problems.concat(validationResult.problems); }; ValidationResult.prototype.mergeEnumValues = function (validationResult) { if (!this.enumValueMatch && !validationResult.enumValueMatch && this.enumValues && validationResult.enumValues) { this.enumValues = this.enumValues.concat(validationResult.enumValues); for (var _i = 0, _a = this.problems; _i < _a.length; _i++) { var error = _a[_i]; if (error.code === ErrorCode.EnumValueMismatch) { error.message = localize('enumWarning', 'Value is not accepted. Valid values: {0}.', this.enumValues.map(function (v) { return JSON.stringify(v); }).join(', ')); } } } }; ValidationResult.prototype.mergePropertyMatch = function (propertyValidationResult) { this.merge(propertyValidationResult); this.propertiesMatches++; if (propertyValidationResult.enumValueMatch || !propertyValidationResult.hasProblems() && propertyValidationResult.propertiesMatches) { this.propertiesValueMatches++; } if (propertyValidationResult.enumValueMatch && propertyValidationResult.enumValues && propertyValidationResult.enumValues.length === 1) { this.primaryValueMatches++; } }; ValidationResult.prototype.compare = function (other) { var hasProblems = this.hasProblems(); if (hasProblems !== other.hasProblems()) { return hasProblems ? -1 : 1; } if (this.enumValueMatch !== other.enumValueMatch) { return other.enumValueMatch ? -1 : 1; } if (this.primaryValueMatches !== other.primaryValueMatches) { return this.primaryValueMatches - other.primaryValueMatches; } if (this.propertiesValueMatches !== other.propertiesValueMatches) { return this.propertiesValueMatches - other.propertiesValueMatches; } return this.propertiesMatches - other.propertiesMatches; }; return ValidationResult; }()); export { ValidationResult }; export function newJSONDocument(root, diagnostics) { if (diagnostics === void 0) { diagnostics = []; } return new JSONDocument(root, diagnostics, []); } export function getNodeValue(node) { return Json.getNodeValue(node); } export function getNodePath(node) { return Json.getNodePath(node); } export function contains(node, offset, includeRightBound) { if (includeRightBound === void 0) { includeRightBound = false; } return offset >= node.offset && offset < (node.offset + node.length) || includeRightBound && offset === (node.offset + node.length); } var JSONDocument = /** @class */ (function () { function JSONDocument(root, syntaxErrors, comments) { if (syntaxErrors === void 0) { syntaxErrors = []; } if (comments === void 0) { comments = []; } this.root = root; this.syntaxErrors = syntaxErrors; this.comments = comments; } JSONDocument.prototype.getNodeFromOffset = function (offset, includeRightBound) { if (includeRightBound === void 0) { includeRightBound = false; } if (this.root) { return Json.findNodeAtOffset(this.root, offset, includeRightBound); } return void 0; }; JSONDocument.prototype.visit = function (visitor) { if (this.root) { var doVisit_1 = function (node) { var ctn = visitor(node); var children = node.children; if (Array.isArray(children)) { for (var i = 0; i < children.length && ctn; i++) { ctn = doVisit_1(children[i]); } } return ctn; }; doVisit_1(this.root); } }; JSONDocument.prototype.validate = function (textDocument, schema) { if (this.root && schema) { var validationResult = new ValidationResult(); validate(this.root, schema, validationResult, NoOpSchemaCollector.instance); return validationResult.problems.map(function (p) { var range = Range.create(textDocument.positionAt(p.location.offset), textDocument.positionAt(p.location.offset + p.location.length)); return Diagnostic.create(range, p.message, p.severity, p.code); }); } return null; }; JSONDocument.prototype.getMatchingSchemas = function (schema, focusOffset, exclude) { if (focusOffset === void 0) { focusOffset = -1; } if (exclude === void 0) { exclude = null; } var matchingSchemas = new SchemaCollector(focusOffset, exclude); if (this.root && schema) { validate(this.root, schema, new ValidationResult(), matchingSchemas); } return matchingSchemas.schemas; }; return JSONDocument; }()); export { JSONDocument }; function validate(node, schema, validationResult, matchingSchemas) { if (!node || !matchingSchemas.include(node)) { return; } switch (node.type) { case 'object': _validateObjectNode(node, schema, validationResult, matchingSchemas); break; case 'array': _validateArrayNode(node, schema, validationResult, matchingSchemas); break; case 'string': _validateStringNode(node, schema, validationResult, matchingSchemas); break; case 'number': _validateNumberNode(node, schema, validationResult, matchingSchemas); break; case 'property': return validate(node.valueNode, schema, validationResult, matchingSchemas); } _validateNode(); matchingSchemas.add({ node: node, schema: schema }); function _validateNode() { function matchesType(type) { return node.type === type || (type === 'integer' && node.type === 'number' && node.isInteger); } if (Array.isArray(schema.type)) { if (!schema.type.some(matchesType)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: schema.errorMessage || localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', schema.type.join(', ')) }); } } else if (schema.type) { if (!matchesType(schema.type)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: schema.errorMessage || localize('typeMismatchWarning', 'Incorrect type. Expected "{0}".', schema.type) }); } } if (Array.isArray(schema.allOf)) { for (var _i = 0, _a = schema.allOf; _i < _a.length; _i++) { var subSchemaRef = _a[_i]; validate(node, asSchema(subSchemaRef), validationResult, matchingSchemas); } } var notSchema = asSchema(schema.not); if (notSchema) { var subValidationResult = new ValidationResult(); var subMatchingSchemas = matchingSchemas.newSub(); validate(node, notSchema, subValidationResult, subMatchingSchemas); if (!subValidationResult.hasProblems()) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('notSchemaWarning', "Matches a schema that is not allowed.") }); } for (var _b = 0, _c = subMatchingSchemas.schemas; _b < _c.length; _b++) { var ms = _c[_b]; ms.inverted = !ms.inverted; matchingSchemas.add(ms); } } var testAlternatives = function (alternatives, maxOneMatch) { var matches = []; // remember the best match that is used for error messages var bestMatch = null; for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) { var subSchemaRef = alternatives_1[_i]; var subSchema = asSchema(subSchemaRef); var subValidationResult = new ValidationResult(); var subMatchingSchemas = matchingSchemas.newSub(); validate(node, subSchema, subValidationResult, subMatchingSchemas); if (!subValidationResult.hasProblems()) { matches.push(subSchema); } if (!bestMatch) { bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas }; } else { if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) { // no errors, both are equally good matches bestMatch.matchingSchemas.merge(subMatchingSchemas); bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches; bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches; } else { var compareResult = subValidationResult.compare(bestMatch.validationResult); if (compareResult > 0) { // our node is the best matching so far bestMatch = { schema: subSchema, validationResult: subValidationResult, matchingSchemas: subMatchingSchemas }; } else if (compareResult === 0) { // there's already a best matching but we are as good bestMatch.matchingSchemas.merge(subMatchingSchemas); bestMatch.validationResult.mergeEnumValues(subValidationResult); } } } } if (matches.length > 1 && maxOneMatch) { validationResult.problems.push({ location: { offset: node.offset, length: 1 }, severity: DiagnosticSeverity.Warning, message: localize('oneOfWarning', "Matches multiple schemas when only one must validate.") }); } if (bestMatch !== null) { validationResult.merge(bestMatch.validationResult); validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches; validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches; matchingSchemas.merge(bestMatch.matchingSchemas); } return matches.length; }; if (Array.isArray(schema.anyOf)) { testAlternatives(schema.anyOf, false); } if (Array.isArray(schema.oneOf)) { testAlternatives(schema.oneOf, true); } var testBranch = function (schema) { var subValidationResult = new ValidationResult(); var subMatchingSchemas = matchingSchemas.newSub(); validate(node, asSchema(schema), subValidationResult, subMatchingSchemas); validationResult.merge(subValidationResult); validationResult.propertiesMatches += subValidationResult.propertiesMatches; validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches; matchingSchemas.merge(subMatchingSchemas); }; var testCondition = function (ifSchema, thenSchema, elseSchema) { var subSchema = asSchema(ifSchema); var subValidationResult = new ValidationResult(); var subMatchingSchemas = matchingSchemas.newSub(); validate(node, subSchema, subValidationResult, subMatchingSchemas); matchingSchemas.merge(subMatchingSchemas); if (!subValidationResult.hasProblems()) { if (thenSchema) { testBranch(thenSchema); } } else if (elseSchema) { testBranch(elseSchema); } }; var ifSchema = asSchema(schema.if); if (ifSchema) { testCondition(ifSchema, asSchema(schema.then), asSchema(schema.else)); } if (Array.isArray(schema.enum)) { var val = getNodeValue(node); var enumValueMatch = false; for (var _d = 0, _e = schema.enum; _d < _e.length; _d++) { var e = _e[_d]; if (equals(val, e)) { enumValueMatch = true; break; } } validationResult.enumValues = schema.enum; validationResult.enumValueMatch = enumValueMatch; if (!enumValueMatch) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, code: ErrorCode.EnumValueMismatch, message: schema.errorMessage || localize('enumWarning', 'Value is not accepted. Valid values: {0}.', schema.enum.map(function (v) { return JSON.stringify(v); }).join(', ')) }); } } if (isDefined(schema.const)) { var val = getNodeValue(node); if (!equals(val, schema.const)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, code: ErrorCode.EnumValueMismatch, message: schema.errorMessage || localize('constWarning', 'Value must be {0}.', JSON.stringify(schema.const)) }); validationResult.enumValueMatch = false; } else { validationResult.enumValueMatch = true; } validationResult.enumValues = [schema.const]; } if (schema.deprecationMessage && node.parent) { validationResult.problems.push({ location: { offset: node.parent.offset, length: node.parent.length }, severity: DiagnosticSeverity.Warning, message: schema.deprecationMessage }); } } function _validateNumberNode(node, schema, validationResult, matchingSchemas) { var val = node.value; if (isNumber(schema.multipleOf)) { if (val % schema.multipleOf !== 0) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf) }); } } function getExclusiveLimit(limit, exclusive) { if (isNumber(exclusive)) { return exclusive; } if (isBoolean(exclusive) && exclusive) { return limit; } return void 0; } function getLimit(limit, exclusive) { if (!isBoolean(exclusive) || !exclusive) { return limit; } return void 0; } var exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum); if (isNumber(exclusiveMinimum) && val <= exclusiveMinimum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum) }); } var exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum); if (isNumber(exclusiveMaximum) && val >= exclusiveMaximum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum) }); } var minimum = getLimit(schema.minimum, schema.exclusiveMinimum); if (isNumber(minimum) && val < minimum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum) }); } var maximum = getLimit(schema.maximum, schema.exclusiveMaximum); if (isNumber(maximum) && val > maximum) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum) }); } } function _validateStringNode(node, schema, validationResult, matchingSchemas) { if (isNumber(schema.minLength) && node.value.length < schema.minLength) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength) }); } if (isNumber(schema.maxLength) && node.value.length > schema.maxLength) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength) }); } if (isString(schema.pattern)) { var regex = new RegExp(schema.pattern); if (!regex.test(node.value)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: schema.patternErrorMessage || schema.errorMessage || localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern) }); } } if (schema.format) { switch (schema.format) { case 'uri': case 'uri-reference': { var errorMessage = void 0; if (!node.value) { errorMessage = localize('uriEmpty', 'URI expected.'); } else { var match = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/.exec(node.value); if (!match) { errorMessage = localize('uriMissing', 'URI is expected.'); } else if (!match[2] && schema.format === 'uri') { errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.'); } } if (errorMessage) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: schema.patternErrorMessage || schema.errorMessage || localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage) }); } } break; case 'color-hex': case 'date-time': case 'date': case 'time': case 'email': var format = formats[schema.format]; if (!node.value || !format.pattern.exec(node.value)) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage }); } default: } } } function _validateArrayNode(node, schema, validationResult, matchingSchemas) { if (Array.isArray(schema.items)) { var subSchemas = schema.items; for (var index = 0; index < subSchemas.length; index++) { var subSchemaRef = subSchemas[index]; var subSchema = asSchema(subSchemaRef); var itemValidationResult = new ValidationResult(); var item = node.items[index]; if (item) { validate(item, subSchema, itemValidationResult, matchingSchemas); validationResult.mergePropertyMatch(itemValidationResult); } else if (node.items.length >= subSchemas.length) { validationResult.propertiesValueMatches++; } } if (node.items.length > subSchemas.length) { if (typeof schema.additionalItems === 'object') { for (var i = subSchemas.length; i < node.items.length; i++) { var itemValidationResult = new ValidationResult(); validate(node.items[i], schema.additionalItems, itemValidationResult, matchingSchemas); validationResult.mergePropertyMatch(itemValidationResult); } } else if (schema.additionalItems === false) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('additionalItemsWarning', 'Array has too many items according to schema. Expected {0} or fewer.', subSchemas.length) }); } } } else { var itemSchema = asSchema(schema.items); if (itemSchema) { for (var _i = 0, _a = node.items; _i < _a.length; _i++) { var item = _a[_i]; var itemValidationResult = new ValidationResult(); validate(item, itemSchema, itemValidationResult, matchingSchemas); validationResult.mergePropertyMatch(itemValidationResult); } } } var containsSchema = asSchema(schema.contains); if (containsSchema) { var doesContain = node.items.some(function (item) { var itemValidationResult = new ValidationResult(); validate(item, containsSchema, itemValidationResult, NoOpSchemaCollector.instance); return !itemValidationResult.hasProblems(); }); if (!doesContain) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.') }); } } if (isNumber(schema.minItems) && node.items.length < schema.minItems) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems) }); } if (isNumber(schema.maxItems) && node.items.length > schema.maxItems) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems) }); } if (schema.uniqueItems === true) { var values_1 = getNodeValue(node); var duplicates = values_1.some(function (value, index) { return index !== values_1.lastIndexOf(value); }); if (duplicates) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('uniqueItemsWarning', 'Array has duplicate items.') }); } } } function _validateObjectNode(node, schema, validationResult, matchingSchemas) { var seenKeys = Object.create(null); var unprocessedProperties = []; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var propertyNode = _a[_i]; var key = propertyNode.keyNode.value; seenKeys[key] = propertyNode.valueNode; unprocessedProperties.push(key); } if (Array.isArray(schema.required)) { for (var _b = 0, _c = schema.required; _b < _c.length; _b++) { var propertyName = _c[_b]; if (!seenKeys[propertyName]) { var keyNode = node.parent && node.parent.type === 'property' && node.parent.keyNode; var location = keyNode ? { offset: keyNode.offset, length: keyNode.length } : { offset: node.offset, length: 1 }; validationResult.problems.push({ location: location, severity: DiagnosticSeverity.Warning, message: localize('MissingRequiredPropWarning', 'Missing property "{0}".', propertyName) }); } } } var propertyProcessed = function (prop) { var index = unprocessedProperties.indexOf(prop); while (index >= 0) { unprocessedProperties.splice(index, 1); index = unprocessedProperties.indexOf(prop); } }; if (schema.properties) { for (var _d = 0, _e = Object.keys(schema.properties); _d < _e.length; _d++) { var propertyName = _e[_d]; propertyProcessed(propertyName); var propertySchema = schema.properties[propertyName]; var child = seenKeys[propertyName]; if (child) { if (isBoolean(propertySchema)) { if (!propertySchema) { var propertyNode = child.parent; validationResult.problems.push({ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length }, severity: DiagnosticSeverity.Warning, message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName) }); } else { validationResult.propertiesMatches++; validationResult.propertiesValueMatches++; } } else { var propertyValidationResult = new ValidationResult(); validate(child, propertySchema, propertyValidationResult, matchingSchemas); validationResult.mergePropertyMatch(propertyValidationResult); } } } } if (schema.patternProperties) { for (var _f = 0, _g = Object.keys(schema.patternProperties); _f < _g.length; _f++) { var propertyPattern = _g[_f]; var regex = new RegExp(propertyPattern); for (var _h = 0, _j = unprocessedProperties.slice(0); _h < _j.length; _h++) { var propertyName = _j[_h]; if (regex.test(propertyName)) { propertyProcessed(propertyName); var child = seenKeys[propertyName]; if (child) { var propertySchema = schema.patternProperties[propertyPattern]; if (isBoolean(propertySchema)) { if (!propertySchema) { var propertyNode = child.parent; validationResult.problems.push({ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length }, severity: DiagnosticSeverity.Warning, message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName) }); } else { validationResult.propertiesMatches++; validationResult.propertiesValueMatches++; } } else { var propertyValidationResult = new ValidationResult(); validate(child, propertySchema, propertyValidationResult, matchingSchemas); validationResult.mergePropertyMatch(propertyValidationResult); } } } } } } if (typeof schema.additionalProperties === 'object') { for (var _k = 0, unprocessedProperties_1 = unprocessedProperties; _k < unprocessedProperties_1.length; _k++) { var propertyName = unprocessedProperties_1[_k]; var child = seenKeys[propertyName]; if (child) { var propertyValidationResult = new ValidationResult(); validate(child, schema.additionalProperties, propertyValidationResult, matchingSchemas); validationResult.mergePropertyMatch(propertyValidationResult); } } } else if (schema.additionalProperties === false) { if (unprocessedProperties.length > 0) { for (var _l = 0, unprocessedProperties_2 = unprocessedProperties; _l < unprocessedProperties_2.length; _l++) { var propertyName = unprocessedProperties_2[_l]; var child = seenKeys[propertyName]; if (child) { var propertyNode = child.parent; validationResult.problems.push({ location: { offset: propertyNode.keyNode.offset, length: propertyNode.keyNode.length }, severity: DiagnosticSeverity.Warning, message: schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName) }); } } } } if (isNumber(schema.maxProperties)) { if (node.properties.length > schema.maxProperties) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties) }); } } if (isNumber(schema.minProperties)) { if (node.properties.length < schema.minProperties) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('MinPropWarning', 'Object has fewer properties than the required number of {0}', schema.minProperties) }); } } if (schema.dependencies) { for (var _m = 0, _o = Object.keys(schema.dependencies); _m < _o.length; _m++) { var key = _o[_m]; var prop = seenKeys[key]; if (prop) { var propertyDep = schema.dependencies[key]; if (Array.isArray(propertyDep)) { for (var _p = 0, propertyDep_1 = propertyDep; _p < propertyDep_1.length; _p++) { var requiredProp = propertyDep_1[_p]; if (!seenKeys[requiredProp]) { validationResult.problems.push({ location: { offset: node.offset, length: node.length }, severity: DiagnosticSeverity.Warning, message: localize('RequiredDependentPropWarning', 'Object is missing property {0} required by property {1}.', requiredProp, key) }); } else { validationResult.propertiesValueMatches++; } } } else { var propertySchema = asSchema(propertyDep); if (propertySchema) { var propertyValidationResult = new ValidationResult(); validate(node, propertySchema, propertyValidationResult, matchingSchemas); validationResult.mergePropertyMatch(propertyValidationResult); } } } } } var propertyNames = asSchema(schema.propertyNames); if (propertyNames) { for (var _q = 0, _r = node.properties; _q < _r.length; _q++) { var f = _r[_q]; var key = f.keyNode; if (key) { validate(key, propertyNames, validationResult, NoOpSchemaCollector.instance); } } } } } export function parse(textDocument, config) { var problems = []; var lastProblemOffset = -1; var text = textDocument.getText(); var scanner = Json.createScanner(text, false); var commentRanges = config && config.collectComments ? [] : void 0; function _scanNext() { while (true) { var token_1 = scanner.scan(); _checkScanError(); switch (token_1) { case 12 /* LineCommentTrivia */: case 13 /* BlockCommentTrivia */: if (Array.isArray(commentRanges)) { commentRanges.push(Range.create(textDocument.positionAt(scanner.getTokenOffset()), textDocument.positionAt(scanner.getTokenOffset() + scanner.getTokenLength()))); } break; case 15 /* Trivia */: case 14 /* LineBreakTrivia */: break; default: return token_1; } } } function _accept(token) { if (scanner.getToken() === token) { _scanNext(); return true; } return false; } function _errorAtRange(message, code, startOffset, endOffset, severity) { if (severity === void 0) { severity = DiagnosticSeverity.Error; } if (problems.length === 0 || startOffset !== lastProblemOffset) { var range = Range.create(textDocument.positionAt(startOffset), textDocument.positionAt(endOffset)); problems.push(Diagnostic.create(range, message, severity, code, textDocument.languageId)); lastProblemOffset = startOffset; } } function _error(message, code, node, skipUntilAfter, skipUntil) { if (node === void 0) { node = null; } if (skipUntilAfter === void 0) { skipUntilAfter = []; } if (skipUntil === void 0) { skipUntil = []; } var start = scanner.getTokenOffset(); var end = scanner.getTokenOffset() + scanner.getTokenLength(); if (start === end && start > 0) { start--; while (start > 0 && /\s/.test(text.charAt(start))) { start--; } end = start + 1; } _errorAtRange(message, code, start, end); if (node) { _finalize(node, false); } if (skipUntilAfter.length + skipUntil.length > 0) { var token_2 = scanner.getToken(); while (token_2 !== 17 /* EOF */) { if (skipUntilAfter.indexOf(token_2) !== -1) { _scanNext(); break; } else if (skipUntil.indexOf(token_2) !== -1) { break; } token_2 = _scanNext(); } } return node; } function _checkScanError() { switch (scanner.getTokenError()) { case 4 /* InvalidUnicode */: _error(localize('InvalidUnicode', 'Invalid unicode sequence in string.'), ErrorCode.InvalidUnicode); return true; case 5 /* InvalidEscapeCharacter */: _error(localize('InvalidEscapeCharacter', 'Invalid escape character in string.'), ErrorCode.InvalidEscapeCharacter); return true; case 3 /* UnexpectedEndOfNumber */: _error(localize('UnexpectedEndOfNumber', 'Unexpected end of number.'), ErrorCode.UnexpectedEndOfNumber); return true; case 1 /* UnexpectedEndOfComment */: _error(localize('UnexpectedEndOfComment', 'Unexpected end of comment.'), ErrorCode.UnexpectedEndOfComment); return true; case 2 /* UnexpectedEndOfString */: _error(localize('UnexpectedEndOfString', 'Unexpected end of string.'), ErrorCode.UnexpectedEndOfString); return true; case 6 /* InvalidCharacter */: _error(localize('InvalidCharacter', 'Invalid characters in string. Control characters must be escaped.'), ErrorCode.InvalidCharacter); return true; } return false; } function _finalize(node, scanNext) { node.length = scanner.getTokenOffset() + scanner.getTokenLength() - node.offset; if (scanNext) { _scanNext(); } return node; } function _parseArray(parent) { if (scanner.getToken() !== 3 /* OpenBracketToken */) { return null; } var node = new ArrayASTNodeImpl(parent, scanner.getTokenOffset()); _scanNext(); // consume OpenBracketToken var count = 0; var needsComma = false; while (scanner.getToken() !== 4 /* CloseBracketToken */ && scanner.getToken() !== 17 /* EOF */) { if (scanner.getToken() === 5 /* CommaToken */) { if (!needsComma) { _error(localize('ValueExpected', 'Value expected'), ErrorCode.ValueExpected); } var commaOffset = scanner.getTokenOffset(); _scanNext(); // consume comma if (scanner.getToken() === 4 /* CloseBracketToken */) { if (needsComma) { _errorAtRange(localize('TrailingComma', 'Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1); } continue; } } else if (needsComma) { _error(localize('ExpectedComma', 'Expected comma'), ErrorCode.CommaExpected); } var item = _parseValue(node, count++); if (!item) { _error(localize('PropertyExpected', 'Value expected'), ErrorCode.ValueExpected, null, [], [4 /* CloseBracketToken */, 5 /* CommaToken */]); } else { node.items.push(item); } needsComma = true; } if (scanner.getToken() !== 4 /* CloseBracketToken */) { return _error(localize('ExpectedCloseBracket', 'Expected comma or closing bracket'), ErrorCode.CommaOrCloseBacketExpected, node); } return _finalize(node, true); } function _parseProperty(parent, keysSeen) { var node = new PropertyASTNodeImpl(parent, scanner.getTokenOffset()); var key = _parseString(node); if (!key) { if (scanner.getToken() === 16 /* Unknown */) { // give a more helpful error message _error(localize('DoubleQuotesExpected', 'Property keys must be doublequoted'), ErrorCode.Undefined); var keyNode = new StringASTNodeImpl(node, scanner.getTokenOffset(), scanner.getTokenLength()); keyNode.value = scanner.getTokenValue(); key = keyNode; _scanNext(); // consume Unknown } else { return null; } } node.keyNode = key; var seen = keysSeen[key.value]; if (seen) { _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, node.keyNode.offset, node.keyNode.offset + node.keyNode.length, DiagnosticSeverity.Warning); if (typeof seen === 'object') { _errorAtRange(localize('DuplicateKeyWarning', "Duplicate object key"), ErrorCode.DuplicateKey, seen.keyNode.offset, seen.keyNode.offset + seen.keyNode.length, DiagnosticSeverity.Warning); } keysSeen[key.value] = true; // if the same key is duplicate again, avoid duplicate error reporting } else { keysSeen[key.value] = node; } if (scanner.getToken() === 6 /* ColonToken */) { node.colonOffset = scanner.getTokenOffset(); _scanNext(); // consume ColonToken } else { _error(localize('ColonExpected', 'Colon expected'), ErrorCode.ColonExpected); if (scanner.getToken() === 10 /* StringLiteral */ && textDocument.positionAt(key.offset + key.length).line < textDocument.positionAt(scanner.getTokenOffset()).line) { node.length = key.length; return node; } } var value = _parseValue(node, key.value); if (!value) { return _error(localize('ValueExpected', 'Value expected'), ErrorCode.ValueExpected, node, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]); } node.valueNode = value; node.length = value.offset + value.length - node.offset; return node; } function _parseObject(parent) { if (scanner.getToken() !== 1 /* OpenBraceToken */) { return null; } var node = new ObjectASTNodeImpl(parent, scanner.getTokenOffset()); var keysSeen = Object.create(null); _scanNext(); // consume OpenBraceToken var needsComma = false; while (scanner.getToken() !== 2 /* CloseBraceToken */ && scanner.getToken() !== 17 /* EOF */) { if (scanner.getToken() === 5 /* CommaToken */) { if (!needsComma) { _error(localize('PropertyExpected', 'Property expected'), ErrorCode.PropertyExpected); } var commaOffset = scanner.getTokenOffset(); _scanNext(); // consume comma if (scanner.getToken() === 2 /* CloseBraceToken */) { if (needsComma) { _errorAtRange(localize('TrailingComma', 'Trailing comma'), ErrorCode.TrailingComma, commaOffset, commaOffset + 1); } continue; } } else if (needsComma) { _error(localize('ExpectedComma', 'Expected comma'), ErrorCode.CommaExpected); } var property = _parseProperty(node, keysSeen); if (!property) { _error(localize('PropertyExpected', 'Property expected'), ErrorCode.PropertyExpected, null, [], [2 /* CloseBraceToken */, 5 /* CommaToken */]); } else { node.properties.push(property); } needsComma = true; } if (scanner.getToken() !== 2 /* CloseBraceToken */) { return _error(localize('ExpectedCloseBrace', 'Expected comma or closing brace'), ErrorCode.CommaOrCloseBraceExpected, node); } return _finalize(node, true); } function _parseString(parent) { if (scanner.getToken() !== 10 /* StringLiteral */) { return null; } var node = new StringASTNodeImpl(parent, scanner.getTokenOffset()); node.value = scanner.getTokenValue(); return _finalize(node, true); } function _parseNumber(parent) { if (scanner.getToken() !== 11 /* NumericLiteral */) { return null; } var node = new NumberASTNodeImpl(parent, scanner.getTokenOffset()); if (scanner.getTokenError() === 0 /* None */) { var tokenValue = scanner.getTokenValue(); try { var numberValue = JSON.parse(tokenValue); if (!isNumber(numberValue)) { return _error(localize('InvalidNumberFormat', 'Invalid number format.'), ErrorCode.Undefined, node); } node.value = numberValue; } catch (e) { return _error(localize('InvalidNumberFormat', 'Invalid number format.'), ErrorCode.Undefined, node); } node.isInteger = tokenValue.indexOf('.') === -1; } return _finalize(node, true); } function _parseLiteral(parent) { var node; switch (scanner.getToken()) { case 7 /* NullKeyword */: return _finalize(new NullASTNodeImpl(parent, scanner.getTokenOffset()), true); case 8 /* TrueKeyword */: return _finalize(new BooleanASTNodeImpl(parent, true, scanner.getTokenOffset()), true); case 9 /* FalseKeyword */: return _finalize(new BooleanASTNodeImpl(parent, false, scanner.getTokenOffset()), true); default: return null; } } function _parseValue(parent, name) { return _parseArray(parent) || _parseObject(parent) || _parseString(parent) || _parseNumber(parent) || _parseLiteral(parent); } var _root = null; var token = _scanNext(); if (token !== 17 /* EOF */) { _root = _parseValue(null, null); if (!_root) { _error(localize('Invalid symbol', 'Expected a JSON object, array or literal.'), ErrorCode.Undefined); } else if (scanner.getToken() !== 17 /* EOF */) { _error(localize('End of file expected', 'End of file expected.'), ErrorCode.Undefined); } } return new JSONDocument(_root, problems, commentRanges); }
karan/dotfiles
.vscode/extensions/redhat.vscode-yaml-0.7.2/node_modules/yaml-language-server/out/server/node_modules/vscode-json-languageservice/lib/esm/parser/jsonParser.js
JavaScript
mit
57,377
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M4.41 22H21c.55 0 1-.45 1-1V4.41c0-.89-1.08-1.34-1.71-.71L3.71 20.29c-.63.63-.19 1.71.7 1.71zM20 20h-3V9.83l3-3V20z" }), 'NetworkCellRounded');
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/NetworkCellRounded.js
JavaScript
mit
307
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.ws.rs.uma; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.xdi.oxauth.client.uma.ScopeService; import org.xdi.oxauth.client.uma.UmaClientFactory; import org.xdi.oxauth.model.uma.UmaConfiguration; import org.xdi.oxauth.model.uma.ScopeDescription; import org.xdi.oxauth.model.uma.UmaTestUtil; /** * @author Yuriy Zabrovarnyy * @version 0.9, 22/04/2013 */ public class ScopeHttpTest { @Test @Parameters({"umaMetaDataUrl"}) public void scopePresence(final String umaMetaDataUrl) { final UmaConfiguration conf = UmaClientFactory.instance().createMetaDataConfigurationService(umaMetaDataUrl).getMetadataConfiguration(); final ScopeService scopeService = UmaClientFactory.instance().createScopeService(conf); final ScopeDescription modifyScope = scopeService.getScope("modify"); UmaTestUtil.assert_(modifyScope); } }
diedertimmers/oxAuth
Client/src/test/java/org/xdi/oxauth/ws/rs/uma/ScopeHttpTest.java
Java
mit
1,075
using System.Diagnostics.Contracts; using LanguageExt.Attributes; namespace LanguageExt.TypeClasses { /// <summary> /// Fractional number type-class /// </summary> /// <typeparam name="A">The type for which fractional /// operations are being defined.</typeparam> [Typeclass("Fraction*")] public interface Fraction<A> : Num<A> { /// <summary> /// Generates a fractional value from an integer ratio. /// </summary> /// <param name="x">The ratio to convert</param> /// <returns>The equivalent of x in the implementing type.</returns> [Pure] A FromRational(Ratio<int> x); } }
StanJav/language-ext
LanguageExt.Core/TypeClasses/Fraction/Fraction.cs
C#
mit
670
<?php /* FilmwebWebsiteBundle:Order:order_information.html.twig */ class __TwigTemplate_faeebbfa7b62f5cd62c9c149e2739a6decc2df0faf94344f589c73bc191c7784 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 try { $this->parent = $this->env->loadTemplate("FilmwebWebsiteBundle::base.html.twig"); } catch (Twig_Error_Loader $e) { $e->setTemplateFile($this->getTemplateName()); $e->setTemplateLine(1); throw $e; } $this->blocks = array( 'title' => array($this, 'block_title'), 'filmPreview' => array($this, 'block_filmPreview'), ); } protected function doGetParent(array $context) { return "FilmwebWebsiteBundle::base.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_title($context, array $blocks = array()) { echo "Zamówienie"; } // line 4 public function block_filmPreview($context, array $blocks = array()) { // line 5 echo " <style> </style> <h1 align=\"center\">Zamówienie</h1> <table class=\"tftable\" border=\"0\"> <tr><td><b>Imię:</b></td><td>"; // line 10 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["user"]) ? $context["user"] : $this->getContext($context, "user")), "getName", array()), "html", null, true); echo "</td></tr> <tr><td><b>Nazwisko:</b></td><td>"; // line 11 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["user"]) ? $context["user"] : $this->getContext($context, "user")), "getSurname", array()), "html", null, true); echo "</td></tr> <tr><td><b>Nazwa filmu:</b></td><td>"; // line 12 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["film"]) ? $context["film"] : $this->getContext($context, "film")), "getNazwa", array()), "html", null, true); echo "</td></tr> <tr><td><b>Email:</b></td><td>"; // line 13 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["user"]) ? $context["user"] : $this->getContext($context, "user")), "getEmail", array()), "html", null, true); echo "</td></tr> <tr><td><b>Cena:</b></td><td>"; // line 14 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["film"]) ? $context["film"] : $this->getContext($context, "film")), "getCena", array()), "html", null, true); echo " zł</td></tr> <tr><td><b>Data wypożyczenia:</b></td><td>"; // line 15 echo twig_escape_filter($this->env, (isset($context["dataWypozyczenia"]) ? $context["dataWypozyczenia"] : $this->getContext($context, "dataWypozyczenia")), "html", null, true); echo "</td></tr> <tr><td><b>Data zwrotu:</b></td><td>"; // line 16 echo twig_escape_filter($this->env, (isset($context["dataZwrotu"]) ? $context["dataZwrotu"] : $this->getContext($context, "dataZwrotu")), "html", null, true); echo "</td></tr> </table> <br /> <form action=\""; // line 19 echo $this->env->getExtension('routing')->getPath("order"); echo "\" method=\"POST\" align=\"center\"> <input type=\"hidden\" name=\"movieId\" value=\""; // line 20 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["film"]) ? $context["film"] : $this->getContext($context, "film")), "getId", array()), "html", null, true); echo "\"/> <input type=\"submit\" value=\"Dalej\"/> </form> "; } public function getTemplateName() { return "FilmwebWebsiteBundle:Order:order_information.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 87 => 20, 83 => 19, 77 => 16, 73 => 15, 69 => 14, 65 => 13, 61 => 12, 57 => 11, 53 => 10, 46 => 5, 43 => 4, 37 => 3, 11 => 1,); } }
paskalov/webs
app/cache/dev/twig/fa/ee/bbfa7b62f5cd62c9c149e2739a6decc2df0faf94344f589c73bc191c7784.php
PHP
mit
4,259
using System.Web.Mvc; using System.Web.Routing; namespace MySite.WebUI.App_Start { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
michaelmello/mysite-retired
MySite.WebUI/App_Start/RouteConfig.cs
C#
mit
506
<script type="text/javascript"> $(document).ready(function(){ $('#spm_tab a').click(function(e) { e.preventDefault(); $(this).tab('show'); }); // store the currently selected tab in the hash value $("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) { var id = $(e.target).attr("href").substr(1); window.location.hash = id; }); // on load of the page: switch to the currently selected tab var hash = window.location.hash; $('#spm_tab a[href="' + hash + '"]').tab('show'); var id_cetak = 'div-cetak' ; var id_cetak_2 = 'div-cetak-2' ; var id_cetak_3 = 'div-cetak-lampiran-spj' ; var id_cetak_4 = 'div-cetak-lampiran-rekappajak' ; var id_xls_1 = 'table_spp' ; var id_xls_2 = 'table_spm' ; var id_xls_3 = 'table_spj' ; var id_xls_4 = 'table_rekappajak' ; var keluaran = []; // var pj_p_nilai_all = []; $('#myCarousel').on('slid.bs.carousel', function (e) { // do something… var id = e.relatedTarget.id; // console.log(id); if(id == 'a'){ id_cetak = 'div-cetak' ; id_xls_1 = 'table_spp' ; }else if(id == 'b'){ id_cetak = 'div-cetak-f1a' ; id_xls_1 = 'table_f1a' ; } }); $('#myCarouselSPM').on('slid.bs.carousel', function (e) { // do something… var id = e.relatedTarget.id; // console.log(id); if(id == 'e'){ id_cetak_2 = 'div-cetak-2' ; id_xls_2 = 'table_spm' ; }else if(id == 'f'){ id_cetak_2 = 'div-cetak-f1a-2' ; id_xls_2 = 'table_f2a' ; } }); $('#myCarouselLampiran').on('slid.bs.carousel', function (e) { // do something… var id = e.relatedTarget.id; // console.log(id); if(id == 'c'){ id_cetak_3 = 'div-cetak-lampiran-spj' ; id_xls_3 = 'table_spj' ; }else if(id == 'd'){ id_cetak_3 = 'div-cetak-lampiran-rekapakun' ; id_xls_3 = 'table_rekapakun' ; } }); $("#cetak").click(function(){ var mode = 'iframe'; //popup var close = mode == "popup"; var options = { mode : mode, popClose : close}; // console.log($("#" + id_cetak).html()); $("#" + id_cetak).printArea( options ); }); $("#cetak-spm").click(function(){ var mode = 'iframe'; //popup var close = mode == "popup"; var options = { mode : mode, popClose : close}; // console.log($("#" + id_cetak_2).html()); $("#" + id_cetak_2).printArea( options ); }); $("#cetak-lampiran").click(function(){ var mode = 'iframe'; //popup var close = mode == "popup"; var options = { mode : mode, popClose : close}; // console.log($("#" + id_cetak).html()); $("#" + id_cetak_3).printArea( options ); }); $("#cetak-kuitansi").click(function(){ var mode = 'iframe'; //popup var close = mode == "popup"; var options = { mode : mode, popClose : close}; // console.log($("#" + id_cetak).html()); $("#div-cetak-kuitansi").printArea( options ); }); $("#cetak-rekappajak").click(function(){ var mode = 'iframe'; //popup var close = mode == "popup"; var options = { mode : mode, popClose : close}; // console.log($("#" + id_cetak).html()); $("#" + id_cetak_4).printArea( options ); }); $("#xls_spp").click(function(){ var uri = $("#" + id_xls_1).excelexportjs({ containerid: id_xls_1 , datatype: "table" , returnUri: true }); var blob = b64toBlob(uri, "application/vnd.ms-excel;charset=charset=utf-8"); saveAs(blob, 'download_rsa_excel.xls'); }); $("#xls_spm").click(function(){ var uri = $("#" + id_xls_2).excelexportjs({ containerid: id_xls_2 , datatype: "table" , returnUri: true }); var blob = b64toBlob(uri, "application/vnd.ms-excel;charset=charset=utf-8"); saveAs(blob, 'download_rsa_excel.xls'); }); $("#xls_lamp").click(function(){ var uri = $("#" + id_xls_3).excelexportjs({ containerid: id_xls_3 , datatype: "table" , returnUri: true }); var blob = b64toBlob(uri, "application/vnd.ms-excel;charset=charset=utf-8"); saveAs(blob, 'download_rsa_excel.xls'); }); $("#xls_rekappajak").click(function(){ var uri = $("#" + id_xls_3).excelexportjs({ containerid: id_xls_4 , datatype: "table" , returnUri: true }); var blob = b64toBlob(uri, "application/vnd.ms-excel;charset=charset=utf-8"); saveAs(blob, 'download_rsa_excel.xls'); }); var pos = $('.ttd').position(); // .outerWidth() takes into account border and padding. var width = $('.ttd').width(); //show the menu directly over the placeholder // $("#status_spp").css({ // position: "absolute", // top: (pos.top - 10) + "px", // left: (pos.left - 10) + "px" // }).show(); $('#myModalKonfirm').on('hidden.bs.modal', function (e) { // do something... $('#proses_spm_').hide(); $('#proses_spm').show(); }) $(document).on("click",'#proses_spm_kpa',function(){ if(confirm('Apakah anda yakin ?')){ var data = 'proses=' +'SPM-FINAL-VERIFIKATOR' + '&nomor_trx=' + $('#nomor_trx_spm').html() + '&jenis=' + 'SPM' + '&kd_unit=' + '<?=$kd_unit?>' + '&tahun=' + '<?=$cur_tahun?>'; $.ajax({ type:"POST", url :"<?=site_url('rsa_tup/proses_spm_tup')?>", data:data, success:function(data){ // console.log(data) // $('#no_bukti').html(data); // $('#myModalKuitansi').modal('show'); if(data=='sukses'){ location.reload(); } // } }); } }); $(document).on("click",'#tolak_spm_kpa',function(){ if(confirm('Apakah anda yakin ?')){ var data = 'proses=' + 'SPM-DITOLAK-VERIFIKATOR' + '&nomor_trx=' + $('#nomor_trx_spm').html() + '&jenis=' + 'SPM' + '&ket=' + $('#ket').val() + '&rel_kuitansi=' + encodeURIComponent('<?=$rel_kuitansi?>') + '&kd_unit=' + '<?=$kd_unit?>' + '&tahun=' + '<?=$cur_tahun?>'; $.ajax({ type:"POST", url :"<?=site_url('rsa_tup/proses_spm_tup')?>", data:data, success:function(data){ // console.log(data) // $('#no_bukti').html(data); // $('#myModalKuitansi').modal('show'); if(data=='sukses'){ location.reload(); } // } }); } }); $('#myModalTolakSPMPPK').on('shown.bs.modal', function (e) { // do something... $('#ket').focus(); }) $(document).on("click","#down",function(){ var uri = $("#table_spp_up").excelexportjs({ containerid: "table_spp_up" , datatype: "table" , returnUri: true }); $('#dtable').val(uri); $('#form_spp').submit(); }); $(document).on("click","#down_2",function(){ var uri = $("#table_spm_up").excelexportjs({ containerid: "table_spm_up" , datatype: "table" , returnUri: true }); $('#dtable_2').val(uri); $('#form_spm').submit(); }); $(document).on("click",'#btn-lihat',function(){ var rel = $(this).attr('rel'); $.ajax({ type:"POST", url :"<?=site_url("kuitansi/get_data_kuitansi")?>", data:'id=' + rel, success:function(data){ // console.log(data); var obj = jQuery.parseJSON(data); var kuitansi = obj.kuitansi ; var kuitansi_detail = obj.kuitansi_detail ; var kuitansi_detail_pajak = obj.kuitansi_detail_pajak ; $('#kode_badge').text('GP'); $('#kuitansi_tahun').text(kuitansi.tahun); $('#kuitansi_no_bukti').text(kuitansi.no_bukti); $('#kuitansi_txt_akun').text(kuitansi.nama_akun); $('#uraian').text(decodeURIComponent(kuitansi.uraian)); $('#nm_subkomponen').text(kuitansi.nama_subkomponen); $('#penerima_uang').text(decodeURIComponent(kuitansi.penerima_uang)); // var s = kuitansi.penerima_uang_nip ; // console.log(s.trim()); // if((s.trim() != '-')&&(s.trim() != '.')){ // console.log('t'); $('#penerima_uang_nip').text(kuitansi.penerima_uang_nip); // } // else{ // console.log('f'); // $('#snip').hide(); // } var a = moment(kuitansi.tgl_kuitansi); // var b = moment(a).add('hours', 1); // var c = b.format("YYYY-MM-DD HH-mm-ss"); $('#tgl_kuitansi').text(a.locale("id").format("D MMMM YYYY"));//kuitansi.tgl_kuitansi); $('#nmpppk').text(kuitansi.nmpppk); $('#nippppk').text(kuitansi.nippppk); $('#nmbendahara_kuitansi').text(kuitansi.nmbendahara); $('#nipbendahara_kuitansi').text(kuitansi.nipbendahara); if(kuitansi.nmpumk != ''){ $('#td_tglpumk').show(); $('#td_nmpumk').show(); }else{ $('#td_tglpumk').hide(); $('#td_nmpumk').hide(); } $('#nmpumk').text(kuitansi.nmpumk); $('#nippumk').text(kuitansi.nippumk); $('#penerima_barang').text(kuitansi.penerima_barang); $('#penerima_barang_nip').text(kuitansi.penerima_barang_nip); $('#tr_isi').remove(); $('.tr_new').remove(); $('<tr id="tr_isi"><td colspan="11">&nbsp;</td></tr>').insertAfter($('#before_tr_isi')); var str_isi = ''; $.each(kuitansi_detail,function(i,v){ str_isi = str_isi + '<tr class="tr_new">'; str_isi = str_isi + '<td colspan="3">' + (i+1) + '. ' + v.deskripsi + '</td>' ; str_isi = str_isi + '<td style="text-align:center">' + (v.volume * 1) + '</td>' ; str_isi = str_isi + '<td style="padding: 0 5px 0 5px;">' + v.satuan + '</td>' ; str_isi = str_isi + '<td style="text-align:right;padding: 0 5px 0 5px;">' + angka_to_string(v.harga_satuan) + '</td>' ; str_isi = str_isi + '<td style="text-align:right;padding: 0 5px 0 5px;" class="sub_tot_bruto_' + i +'">' + angka_to_string((v.bruto * 1)) + '</td>' ; var str_pajak = '' ; var str_pajak_nom = '' ; $.each(kuitansi_detail_pajak,function(ii,vv){ if(vv.id_kuitansi_detail == v.id_kuitansi_detail){ var jenis_pajak_ = vv.jenis_pajak ; var jenis_pajak = jenis_pajak_.split("_").join(" "); var dpp = vv.dpp == '0' ? '' : '(dpp)'; // console.log(vv.persen_pajak); var str_99 = (vv.persen_pajak == '99')||(vv.persen_pajak == '98')||(vv.persen_pajak == '97')||(vv.persen_pajak == '96')||(vv.persen_pajak == '95')||(vv.persen_pajak == '94')||(vv.persen_pajak == '89')? '' : vv.persen_pajak + '% ' ; str_pajak = str_pajak + jenis_pajak + ' ' + str_99 + dpp + '<br>' ; str_pajak_nom = str_pajak_nom + '<span rel="'+ i +'" class="sub_tot_pajak_'+ i +'">'+ angka_to_string(vv.rupiah_pajak) +'</span><br>' ; } }); str_isi = str_isi + '<td style="padding: 0 5px 0 5px;">'+ str_pajak +'</td>' ; str_pajak_nom = (str_pajak_nom=='')?'<span rel="'+ i +'" class="sub_tot_pajak_'+ i +'">'+'0'+'</span>':str_pajak_nom; str_isi = str_isi + '<td style="text-align:right;" >'+ str_pajak_nom +'</td>' ; str_isi = str_isi + '<td><span style="margin-left:10px;margin-right:10px;">=</span><span style="margin-left:10px;margin-right:10px;">Rp.</span></td>' ; str_isi = str_isi + '<td style="text-align:right" rel="'+ i +'" class="sub_tot_netto_'+ i +'">0</td>' ; str_isi = str_isi + '</tr>' ; }); $('#tr_isi').replaceWith(str_isi); var sum_tot_bruto = 0 ; $('[class^="sub_tot_bruto_"').each(function(){ sum_tot_bruto = sum_tot_bruto + parseInt(string_to_angka($(this).html())); }); $('.sum_tot_bruto').html(angka_to_string(sum_tot_bruto)); var sub_tot_pajak = 0 ; $('[class^="sub_tot_pajak_"]').each(function(){ sub_tot_pajak = sub_tot_pajak + parseInt(string_to_angka($(this).text())) ; }); $('.sum_tot_pajak').html(angka_to_string(sub_tot_pajak)); $('[class^="sub_tot_netto_"]').each(function(){ var prel = $(this).attr('rel'); var sub_tot_pajak__ = 0 ; // console.log(prel + ' ' + sub_tot_pajak__); $('.sub_tot_pajak_' + prel).each(function(){ sub_tot_pajak__ = sub_tot_pajak__ + parseInt(string_to_angka($(this).text())) ; }); var sub_tot_bruto_ = parseInt(string_to_angka($('.sub_tot_bruto_' + prel ).text())) ; $(this).html(angka_to_string(sub_tot_bruto_ - sub_tot_pajak__)); }); var sum_tot_netto = 0 ; $('[class^="sub_tot_netto_"').each(function(){ sum_tot_netto = sum_tot_netto + parseInt(string_to_angka($(this).html())); }); $('.sum_tot_netto').html(angka_to_string(sum_tot_netto)); $('.text_tot').html(terbilang(sum_tot_bruto)); $('#nbukti').val(kuitansi.no_bukti); $('#myModalKuitansi').modal('show'); // i++ ; } // location.reload(); }); }); }); function string_to_angka(str){ //I.S str merupakan string yang berisi angka berformat (.000.000,00) //F.S num merupakan angka tanpa format // var num; // if (!isNaN(str)){ // return 0; // } // // str = str.replace(/\./g,""); // str = str.split('.').join(""); // //num = parseInt(str); // return str; return str.split('.').join(""); } function angka_to_string(num){ //I.S num merupakan angka tanpa format //F.S str_hasil merupakan string yang berisi angka berformat (.000.000,00) // var str; // var str_hasil=""; // str = num +""; // for (var j=str.length-1;j>=0;j--){ // if (((str.length-1-j)%3==0) && (j!=(str.length-1)) && ((str[0]!='-') || (j!=0))){ // str_hasil="."+str_hasil; // } // str_hasil=str[j]+str_hasil; // } var str_hasil = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); return str_hasil; } function b64toBlob(b64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = atob(b64Data); var byteArrays = []; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, {type: contentType}); return blob; } function terbilang(bilangan) { bilangan = String(bilangan); var angka = new Array('0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'); var kata = new Array('','Satu','Dua','Tiga','Empat','Lima','Enam','Tujuh','Delapan','Sembilan'); var tingkat = new Array('','Ribu','Juta','Milyar','Triliun'); var panjang_bilangan = bilangan.length; /* pengujian panjang bilangan */ if (panjang_bilangan > 15) { kaLimat = "Diluar Batas"; return kaLimat; } /* mengambil angka-angka yang ada dalam bilangan, dimasukkan ke dalam array */ for (i = 1; i <= panjang_bilangan; i++) { angka[i] = bilangan.substr(-(i),1); } i = 1; j = 0; kaLimat = ""; /* mulai proses iterasi terhadap array angka */ while (i <= panjang_bilangan) { subkaLimat = ""; kata1 = ""; kata2 = ""; kata3 = ""; /* untuk Ratusan */ if (angka[i+2] != "0") { if (angka[i+2] == "1") { kata1 = "Seratus"; } else { kata1 = kata[angka[i+2]] + " Ratus"; } } /* untuk Puluhan atau Belasan */ if (angka[i+1] != "0") { if (angka[i+1] == "1") { if (angka[i] == "0") { kata2 = "Sepuluh"; } else if (angka[i] == "1") { kata2 = "Sebelas"; } else { kata2 = kata[angka[i]] + " Belas"; } } else { kata2 = kata[angka[i+1]] + " Puluh"; } } /* untuk Satuan */ if (angka[i] != "0") { if (angka[i+1] != "1") { kata3 = kata[angka[i]]; } } /* pengujian angka apakah tidak nol semua, lalu ditambahkan tingkat */ if ((angka[i] != "0") || (angka[i+1] != "0") || (angka[i+2] != "0")) { subkaLimat = kata1+" "+kata2+" "+kata3+" "+tingkat[j]+" "; } /* gabungkan variabe sub kaLimat (untuk Satu blok 3 angka) ke variabel kaLimat */ kaLimat = subkaLimat + kaLimat; i = i + 3; j = j + 1; } /* mengganti Satu Ribu jadi Seribu jika diperlukan */ if ((angka[5] == "0") && (angka[6] == "0")) { kaLimat = kaLimat.replace("Satu Ribu","Seribu"); } return kaLimat + "Rupiah"; } </script> <div id="page-wrapper" > <div id="page-inner"> <div class="row"> <div class="col-lg-12"> <h2>SPP/SPM</h2> </div> </div> <hr /> <div class="row"> <div class="col-lg-12"> <?php $stts_bendahara = ''; $stts_ppk = ''; $stts_kpa = ''; $stts_verifikator = ''; $stts_kbuu = ''; ?> <?php if($doc_up == ''){ $stts_bendahara = 'active'; ?> <div class="alert alert-warning" style="border:1px solid #a94442;">SPP TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> belum diusulkan oleh bendahara.</div> <?php }elseif($doc_up == 'SPP-DRAFT'){ $stts_bendahara = 'done'; $stts_ppk = 'active'; ?> <div class="alert alert-info" style="border:1px solid #a94442;">SPP TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> menunggu persetujuan <b><span class="text-danger" >PPK SUKPA</span></b> .</div> <?php }elseif($doc_up == 'SPP-DITOLAK'){ $stts_bendahara = 'active'; ?> <div class="alert alert-warning" style="border:1px solid #a94442;">SPP TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah ditolak oleh <b><span class="text-danger" >PPK SUKPA</span></b> <b>[ <a href="#" data-toggle="modal" data-target="#myModalLihatKet" >alasan</a> ]</b>.</div> <?php }elseif($doc_up == 'SPP-FINAL'){ $stts_bendahara = 'done'; $stts_ppk = 'done'; ?> <div class="alert alert-info" style="border:1px solid #a94442;">SPP TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah diterima oleh <b><span class="text-danger" >PPK SUKPA</span></b> .</div> <?php }elseif($doc_up == 'SPM-DRAFT-PPK'){ $stts_bendahara = 'done'; $stts_ppk = 'done'; $stts_kpa = 'active'; ?> <div class="alert alert-info" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> menunggu persetujuan <b><span class="text-danger" >KPA </span></b> .</div> <?php }elseif($doc_up == 'SPM-DRAFT-KPA'){ $stts_bendahara = 'done'; $stts_ppk = 'done'; $stts_kpa = 'done' ; $stts_verifikator = 'active'; ?> <div class="alert alert-info" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> menunggu persetujuan <b><span class="text-danger" >VERIFIKATOR </span></b> .</div> <?php }elseif($doc_up == 'SPM-DITOLAK-KPA'){ $stts_bendahara = 'active'; ?> <div class="alert alert-warning" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah ditolak oleh <b><span class="text-danger" >KPA </span></b> <b>[ <a href="#" data-toggle="modal" data-target="#myModalLihatKet" >alasan</a> ]</b>.</div> <?php }elseif($doc_up == 'SPM-FINAL-VERIFIKATOR'){ $stts_bendahara = 'done'; $stts_ppk = 'done'; $stts_kpa = 'done' ; $stts_verifikator = 'done'; $stts_kbuu = 'active' ?> <div class="alert alert-success" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> menunggu persetujuan <b><span class="text-danger" >KUASA BUU </span></b> .</div> <?php }elseif($doc_up == 'SPM-DITOLAK-VERIFIKATOR'){ $stts_bendahara = 'active'; ?> <div class="alert alert-warning" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah ditolak oleh <b><span class="text-danger" >VERIFIKATOR </span></b> <b>[ <a href="#" data-toggle="modal" data-target="#myModalLihatKet" >alasan</a> ]</b>.</div> <?php }elseif($doc_up == 'SPM-FINAL-KBUU'){ $stts_bendahara = 'done'; $stts_ppk = 'done'; $stts_kpa = 'done' ; $stts_verifikator = 'done'; $stts_kbuu = 'done' ?> <div class="alert alert-success" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah disetujui oleh <b><span class="text-danger" >KUASA BUU </span></b> .</div> <?php }elseif($doc_up == 'SPM-DITOLAK-KBUU'){ $stts_bendahara = 'active'; ?> <div class="alert alert-warning" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah ditolak oleh <b><span class="text-danger" >KUASA BUU </span></b> <b>[ <a href="#" data-toggle="modal" data-target="#myModalLihatKet" >alasan</a> ]</b>.</div> <?php }elseif($doc_up == 'SPM-FINAL-BUU'){ $stts_bendahara = 'done'; ?> <div class="alert alert-success" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah difinalisasi oleh <b><span class="text-danger" >BUU </span></b> .</div> <?php }elseif($doc_up == 'SPM-DITOLAK-BUU'){ $stts_bendahara = 'active'; ?> <div class="alert alert-warning" style="border:1px solid #a94442;">SPM TUP-NIHIL Tahun <b><span class="text-danger" ><?=$cur_tahun?></span></b> telah ditolak oleh <b><span class="text-danger" >BUU </span></b> <b>[ <a href="#" data-toggle="modal" data-target="#myModalLihatKet" >alasan</a> ]</b>.</div> <?php } ?> <div class="progress-round"> <div class="circle <?=$stts_bendahara?>"> <span class="label">1</span> <span class="title">Bendahara</span> </div> <span class="bar <?=$stts_bendahara?>"></span> <div class="circle <?=$stts_ppk?>"> <span class="label">2</span> <span class="title">PPK</span> </div> <span class="bar <?=$stts_ppk?>"></span> <div class="circle <?=$stts_kpa?>"> <span class="label">3</span> <span class="title">KPA</span> </div> <span class="bar <?=$stts_kpa?>"></span> <div class="circle <?=$stts_verifikator?>"> <span class="label">4</span> <span class="title">Verifikator</span> </div> <span class="bar <?=$stts_verifikator?>"></span> <div class="circle <?=$stts_kbuu?>"> <span class="label">5</span> <span class="title">KBUU</span> </div> </div> <div id="temp" style="display:none"></div> <div> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist" id="spm_tab"> <li role="presentation" class="active"><a href="#spp" aria-controls="home" role="tab" data-toggle="tab">SPP</a></li> <li role="presentation"><a href="#spm" aria-controls="profile" role="tab" data-toggle="tab">SPM</a></li> <li role="presentation"><a href="#lampiran" aria-controls="profile" role="tab" data-toggle="tab">LAMPIRAN</a></li> <li role="presentation"><a href="#kuitansi" aria-controls="profile" role="tab" data-toggle="tab">KUITANSI</a></li> <li role="presentation"><a href="#rekappajak" aria-controls="profile" role="tab" data-toggle="tab">REKAP PAJAK</a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="spp"> <div style="background-color: #EEE; padding: 10px;"> <div id="myCarousel" class="carousel slide" data-ride="carousel" data-interval="false"> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active">1</li> <li data-target="#myCarousel" data-slide-to="1">2</li> </ol> <div class="carousel-inner" role="listbox"> <div class="item active" id="a"> <div id="div-cetak"> <table id="table_spp" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 900px;border: 1px solid #000;background-color: #FFF;" cellspacing="0" border="1" cellpadding="0" > <tbody> <tr > <td colspan="5" style="text-align: right;font-size: 30px;padding: 10px;"><b>F1</b></td> </tr> <tr > <td colspan="5" style="text-align: center;padding-top: 5px;padding-bottom: 5px;height: 72px;" align="center"> <img src="<?php echo base_url(); ?>/assets/img/logo_1.png" width="60"> </td> </tr> <tr style=""> <td colspan="5" style="text-align: center;font-size: 20px;border-bottom: none;"><b>UNIVERSITAS DIPONEGORO</b></td> </tr> <tr style="border-top: none;"> <td colspan="5" style="text-align: center;font-size: 16px;border-bottom: none;border-top: none;"><b>SURAT PERMINTAAN PEMBAYARAN</b></td> </tr> <tr style="border-top: none;border-bottom: none;"> <td colspan="2" style="border-right: none;border-right: none;border-top: none;border-bottom: none;"><b>TAHUN ANGGARAN : <?=$cur_tahun?></b></td> <td style="text-align: center;border-right: none;border-left: none;border-top: none;border-bottom: none;" colspan="2">&nbsp;</td> <td style="border-left: none;border-top: none;border-bottom: none;"><b>JENIS : TUP-NIHIL</b></td> </tr> <tr style="border-top: none;"> <td colspan="2" style="border-right: none;border-top:none;"><b>Tanggal : <?php setlocale(LC_ALL, 'id_ID.utf8'); echo !isset($tgl_spp)?'':strftime("%d %B %Y", strtotime($tgl_spp)); ?></b></td> <td style="text-align: center;border-left: none;border-right: none;border-top:none;" colspan="2" >&nbsp;</td> <td style="border-left: none;border-top:none;"><b>Nomor : <span id="nomor_trx"><?=$nomor_spp?></span><!--00001/<?=$alias?>/SPP-UP/JAN/<?=$cur_tahun?>--></b></td> </tr> <tr > <td colspan="5"><b>Satuan Unit Kerja Pengguna Anggaran (SUKPA) : <?=$unit_kerja?></b></td> </tr> <tr > <td colspan="5" ><b>Unit Kerja : <?=$unit_kerja?> &nbsp;&nbsp; Kode Unit Kerja : <?=$unit_id?></b></td> </tr> <tr style="border-bottom: none;"> <td colspan="4" style="border-right: none;border-bottom: none;">&nbsp;</td> <td style="line-height: 16px;border-left: none;border-bottom: none;">Kepada Yth.<br> Pengguna Anggaran<br> SUKPA <?=$unit_kerja?><br> di Semarang </td> </tr> <tr > <td colspan="5" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr > <td colspan="5" style="border-bottom: none;border-top: none;">Dengan Berpedoman pada Dokumen RKAT yang telah disetujui oleh MWA, bersama ini kami mengajukan Surat Permintaan Pembayaran sebagai berikut:</td> </tr> <tr> <td colspan="5" style="line-height: 16px;border-bottom: none;border-top: none;"> <ol style="list-style-type: lower-alpha;margin-top: 0px;margin-bottom: 0px;" > <li>Jumlah pembayaran yang diminta : Rp. <span id="jumlah_bayar_spp" style='mso-number-format:"\@";'><?php echo isset($detail_tup['nom'])?number_format($detail_tup['nom'], 0, ",", "."):''; ?></span>,-<br> &nbsp;&nbsp;&nbsp;(Terbilang : <b><span id="terbilang_spp"><?php echo isset($detail_tup['terbilang'])?ucwords($detail_tup['terbilang']):''; ?></span></b>)</li> <li>Untuk keperluan : <span id="untuk_bayar_spp"><?=isset($detail_pic->untuk_bayar)?$detail_pic->untuk_bayar:''?></span></li> <li>Nama bendahara pengeluaran : <span id="penerima_spp"><?=isset($detail_pic->penerima)?$detail_pic->penerima:''?></span></li> <li>Alamat : <span id="alamat_spp"><?=isset($detail_pic->alamat_penerima)?$detail_pic->alamat_penerima:''?></span></li> <li>Nama Bank : <span id="nmbank_spp"><?=isset($detail_pic->nama_bank_penerima)?$detail_pic->nama_bank_penerima:''?></span></li> <li>No. Rekening Bank : <span id="rekening_spp"><?=isset($detail_pic->no_rek_penerima)?$detail_pic->no_rek_penerima:''?></span></li> <li>No. NPWP : <span id="npwp_spp"><?=isset($detail_pic->npwp_penerima)?$detail_pic->npwp_penerima:''?></span></li> </ol> </td> </tr> <tr> <td colspan="5" style="border-top: none;"> Pembayaran sebagaimana tersebut diatas, dibebankan pada pengeluaran dengan uraian sebagai berikut :<br> </td> </tr> <tr > <td colspan="3" style="vertical-align: top;border-top:none;padding-left: 0;"> <table style="font-family:arial;font-size:12px;line-height: 21px;border-collapse: collapse;width: 100%;border: 1px solid #000;background-color: #FFF;border-left: none;border-right:none;" cellspacing="0" border="1" cellpadding="0"> <tr> <td style="text-align: center" colspan="3"><b>PENGELUARAN</b></td> </tr> <tr> <td style="border-right: solid 1px #000;text-align: center;">NAMA AKUN</td> <td style="border-right: solid 1px #000;text-align: center;">KODE AKUN</td> <td style="text-align: center;">JUMLAH UANG</td> </tr> <?php $jml_pengeluaran = 0; ?> <?php $sub_kegiatan = '' ; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php foreach($data_akun_pengeluaran as $data):?> <?php if($sub_kegiatan != $data->nama_subkomponen): ?> <tr> <td colspan="3"> <b><?=$data->nama_subkomponen?></b> </td> </tr> <?php $sub_kegiatan = $data->nama_subkomponen ; ?> <?php endif; ?> <tr> <td style="border-right: solid 1px #000"> <?=$data->nama_akun5digit?> </td> <td style="text-align: center;border-right: solid 1px #000;"> <?=$data->kode_akun5digit?> </td> <td style='text-align: right;mso-number-format:"\@";'> <?php $jml_pengeluaran = $jml_pengeluaran + $data->pengeluaran ; ?> Rp. <?=number_format($data->pengeluaran, 0, ",", ".")?> </td> </tr> <?php endforeach;?> <?php else: ?> <tr> <td style="border-right: solid 1px #000"> &nbsp; </td> <td style="text-align: center;border-right: solid 1px #000;"> &nbsp; </td> <td style="text-align: right;"> Rp. 0 </td> </tr> <?php endif; ?> <tr> <td colspan="2" style="border-right: solid 1px #000"> Jumlah Pengeluaran </td> <td style='text-align: right;mso-number-format:"\@";'> Rp. <?=number_format($jml_pengeluaran, 0, ",", ".")?> </td> </tr> <tr> <td colspan="2" style="border-right: solid 1px #000"> Dikurangi : Jumlah potongan untuk pihak lain </td> <td style='text-align: right;mso-number-format:"\@";'> <?php $tot_pajak__ = 0 ; if(!empty($data_spp_pajak)){ foreach($data_spp_pajak as $data){ $tot_pajak__ = $tot_pajak__ + $data->rupiah ; } } ?> Rp. <?=number_format($tot_pajak__, 0, ",", ".")?> </td> </tr> <td colspan="2" style="border-right: solid 1px #000"> <strong>Jumlah dana yang dikeluarkan</strong> </td> <td style='text-align: right;mso-number-format:"\@";'> Rp. <?=number_format(($jml_pengeluaran - $tot_pajak__), 0, ",", ".")?> </td> </table> </td> <td colspan="2" style="vertical-align: top;border-top:none;padding-right: 0;"> <table style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 100%;border: 1px solid #000;background-color: #FFF;border-left: none;border-right:none;" cellspacing="0" border="1" cellpadding="0"> <tr> <td style="text-align: center" colspan="2"><b>PERHITUNGAN TERKAIT PIHAK LAIN</b></td> </tr> <tr> <td style="text-align: center" colspan="2">PENERIMAAN DARI PIHAK KE-3</td> </tr> <tr> <td style="border-right: solid 1px #000;width: 50%;text-align: center;">Akun</td> <td style="width: 50%;text-align: center;">Jumlah Uang</td> </tr> <tr> <td style="border-right: solid 1px #000;text-align: center;">-</td> <td style="text-align: right;">Rp. 0</td> </tr> <tr> <td style="border-right: solid 1px #000;"><b>Jumlah Penerimaan</b></td> <td style="text-align: right;">Rp. 0</td> </tr> <tr> <td colspan="2" style="text-align: center"> POTONGAN UNTUK PIHAK LAIN </td> </tr> <tr> <td style="text-align: center;border-right: solid 1px #000;"> Akun Pajak dan Potongan Lainnya </td> <td style="text-align: center"> Jumlah Uang </td> </tr> <?php $tot_pajak_ = 0 ; ?> <?php if(!empty($data_spp_pajak)): ?> <?php foreach($data_spp_pajak as $data):?> <tr> <td style="border-right: solid 1px #000;"> <?php if($data->jenis == 'PPN'){ echo 'Pajak Pertambahan Nilai'; }elseif($data->jenis == 'PPh'){ echo 'Pajak Penghasilan'; }else{ echo 'Lainnya'; } ?> </td> <td style='text-align: right;mso-number-format:"\@";'> <?php $tot_pajak_ = $tot_pajak_ + $data->rupiah ?> Rp. <?=number_format($data->rupiah, 0, ",", ".")?> </td> </tr> <?php endforeach;?> <?php else: ?> <tr> <td style="border-right: solid 1px #000;"> &nbsp; </td> <td style="text-align: right;"> &nbsp; </td> </tr> <?php endif; ?> <tr> <td style="border-right: solid 1px #000;"> <b>Jumlah Potongan</b> </td> <td style='text-align: right;mso-number-format:"\@";'> Rp. <?=number_format($tot_pajak_, 0, ",", ".")?> </td> </tr> </table> </td> </tr> <tr > <td colspan="5" style="border-bottom: none;">&nbsp;</td> </tr> <tr style="border-bottom: none;"> <td colspan="5" style="line-height: 16px;border-bottom: none;border-top:none;"> SPP Sebagaimana dimaksud diatas, disusun sesuai dengan dokumen lampiran yang persyaratkan dan disampaikan secara bersamaan serta merupakan bagian yang tidak terpisahkan dari surat ini.<br><br> </td> <tr> <tr style="border-top: none;"> <td colspan="4" style="border-right: none;border-top:none;">&nbsp;</td> <td style="line-height: 16px;border-left: none;border-top:none;" class="ttd"> Semarang, <?php setlocale(LC_ALL, 'id_ID.utf8'); echo !isset($tgl_spp)?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?> <br> Bendahara Pengeluaran SUKPA<br> <br> <br> <br> <br> <span id="nmbendahara"><?=isset($detail_pic->nmbendahara)?$detail_pic->nmbendahara:''?></span><br> NIP. <span id="nipbendahara"><?=isset($detail_pic->nipbendahara)?$detail_pic->nipbendahara:''?></span><br> </td> </tr> <tr> <td colspan="5" style="line-height: 16px;"> <strong>Keterangan:</strong> <ul> <li>Semua bukti pengeluaran untuk pekerjaan dengan perjanjian yang disahkan Pejabat Pembuat Komitmen telah diuji dan dinyatakan memenuhi persyaratan untuk dilakukan pembayaran atas beban RKAT Undip, selanjutnya bukti-bukti pengeluaran dimaksud disimpan dan ditatausahakan oleh Pejabat Penatausahaan Keuangan SUKPA</li> <li>Semua bukti-bukti pengeluaran untuk pekerjaan yang disahkan Pejabat Pelaksana dan Pengendali Kegiatan (PPPK) telah diuji dan dinyatakan memenuhi persyaratan untuk dilakukan pembayaran atas beban RKAT Undip, selanjutnya bukti-bukti pengeluaran dimaksud disimpan dan ditatausahakan oleh Pejabat Penatausahaan SUKPA.</li> <li>Kebenaran perhitungan dan isi tertuang dalam SPP ini menjadi tanggung jawab Bendahara Pengeluaran sepanjang sesuai dengan bukti-bukti pengeluaran yang telah ditandatangani oleh PPPK atau PPK</li> </ul> </td> </tr> </tbody> </table> </div> </div> <div class="item" id="b"> <div id="div-cetak-f1a"> <table id="table_f1a" class="table_lamp" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 900px;border: 1px solid #000;background-color: #FFF;" cellspacing="0" border="1" cellpadding="0" > <tbody> <tr > <td colspan="7" style="text-align: right;font-size: 30px;padding: 10px;"><b>F1A</b></td> </tr> <tr > <td colspan="7" style="text-align: center;border-bottom: none;height: 72px;"> <img src="<?php echo base_url(); ?>/assets/img/logo_1.png" width="60"> </td> </tr> <tr > <td colspan="7" style="text-align: center;border-bottom: none;"> <h4><b>UNIVERSITAS DIPONEGORO</b></h4> <h5><b>RINCIAN SURAT PERMINTAAN PEMBAYARAN TUP-NIHIL</b></h5> </td> </tr> <tr> <td style="border-right: none;border-top: none;border-bottom: none;">&nbsp;</td> <td colspan="2" style="border: none;"> <b>NO SPP : <?=$nomor_spp?></b> </td> <td style="border: none;">&nbsp;</td> <td colspan="3" style="border-left: none;border-top: none;border-bottom: none;"> <b>TANGGAL : <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spp==''?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?></b> </td> </tr> <tr> <td style="border-right: none;border-top: none;border-bottom: none;">&nbsp;</td> <td colspan="2" style="border: none;text-transform: uppercase"> <b>SUKPA : <?=$unit_kerja?></b> </td> <td style="border: none;">&nbsp;</td> <td colspan="3" style="border-left: none;border-top: none;border-bottom: none;text-transform: uppercase"> <b>UNIT KERJA : <?=$unit_kerja?></b> </td> </tr> <tr> <td class="text-center" colspan="7" style="border-top: none;border-bottom: none;">&nbsp;</td> </tr> <tr> <td colspan="2" style="border-right: none;border-top: none;"> <ol> <li>Nomor dan tanggal SPK / Kontrak </li> <li>Nilai SPK / Kontrak </li> <li>Total nilai SPK / Kontrak yang terbayar</li> <li>Termin pembayaran saat ini</li> <li>Jenis kegiatan</li> <li>Nomer / tanggal berita acara pembayaran</li> <li>Nomer / tanggal berita acara penerimaan barang</li> <li>Rincian pembebanan belanja</li> </ol> </td> <td colspan="5" style="border-left: none;border-top: none;"> <ol style="list-style: none;"> <li>: -</li> <li>: -</li> <li>: -</li> <li>: Lunas</li> <li>: Non Fisik</li> <li>: Terlampir</li> <li>: Terlampir</li> <li>:</li> </ol> </td> </tr> <tr> <td class="text-center" rowspan="2" style="width: 50px;">NO</td> <td class="text-center">KEGIATAN DAN AKUN</td> <td class="text-center">PAGU DALAM RKAT<br>( Rp )</td> <td class="text-center">SPP/SPM S.D.<br>YANG LALU( Rp )</td> <td class="text-center">SPP INI<br>( Rp )</td> <td class="text-center">JUMLAH S.D.<br>SPP INI( Rp )</td> <td class="text-center">SISA DANA<br>( Rp )</td> </tr> <tr> <td class="text-center">a</td> <td class="text-center">b</td> <td class="text-center">c</td> <td class="text-center">d</td> <td class="text-center">e = c + d</td> <td class="text-center">f = b - e</td> </tr> <?php $jml_pengeluaran = 0; ?> <?php $sub_kegiatan = '' ; ?> <?php $i = 1 ; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php foreach($data_akun_pengeluaran as $data):?> <?php if($sub_kegiatan != $data->nama_subkomponen): ?> <tr> <td class="text-center"><?=$i?></td> <td style="padding-left: 10px;"> <b><?=$data->nama_subkomponen?></b> </td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> </tr> <?php $pagu_rkat = 0 ;?> <?php $jml_spm_lalu = 0 ;?> <?php $sub_kegiatan = $data->nama_subkomponen ; ?> <?php $i = $i + 1 ; ?> <?php endif; ?> <tr> <td class="text-center">&nbsp;</td> <td style="padding-left: 10px;"><?=$data->nama_akun5digit?></td> <?php if(!empty($data_akun_rkat)):?> <?php foreach($data_akun_rkat as $da): ?> <?php if($da->kode_usulan_rkat == $data->kode_usulan_rkat):?> <?php if($da->kode_akun5digit == $data->kode_akun5digit):?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format($da->pagu_rkat, 0, ",", ".")?></td> <?php $pagu_rkat = $da->pagu_rkat ;?> <?php endif;?> <?php endif;?> <?php endforeach; ?> <?php else: ?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format('0', 0, ",", ".")?></td> <?php $pagu_rkat = 0 ;?> <?php endif;?> <?php $empty_pengeluaran_lalu = false ; ?> <?php if(!empty($data_akun_pengeluaran_lalu)): ?> <?php foreach($data_akun_pengeluaran_lalu as $da): ?> <?php if($da->kode_usulan_rkat == $data->kode_usulan_rkat):?> <?php if($da->kode_akun5digit == $data->kode_akun5digit):?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format($da->jml_spm_lalu, 0, ",", ".")?></td> <?php $jml_spm_lalu = $da->jml_spm_lalu ;?> <?php $empty_pengeluaran_lalu = true ; ?> <?php endif;?> <?php endif; ?> <?php endforeach; ?> <?php endif;?> <?php if(!$empty_pengeluaran_lalu): ?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format('0', 0, ",", ".")?></td> <?php $jml_spm_lalu = 0 ;?> <?php endif;?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'> <?php $jml_pengeluaran = $jml_pengeluaran + $data->pengeluaran ; ?> <?=number_format($data->pengeluaran, 0, ",", ".")?> </td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?php echo number_format(($jml_spm_lalu + $data->pengeluaran), 0, ",", "."); ?></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?php echo number_format(($pagu_rkat - ($jml_spm_lalu + $data->pengeluaran)), 0, ",", "."); ?></td> </tr> <?php endforeach;?> <?php else: ?> <tr> <td class="text-center" colspan="7">- data kosong -</td> </tr> <?php endif; ?> <!-- <tr> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> </tr>--> <tr> <td class="text-center" colspan="4"><b>Total Nilai ( Rp )</b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($jml_pengeluaran, 0, ",", ".")?></b></td> <td class="text-center" style="background-color:#ccc">&nbsp;</td> <td class="text-center" style="background-color:#ccc">&nbsp;</td> </tr> <tr> <td class="" style="border-right:none;" colspan="2"> <ol start="9" style=""> <li>Laporan keluaran kegiatan non fisik</li> </ol> </td> <td class="text-left" style="border-left: none; border-right:none;" colspan="2" > <ol style="list-style: none;margin: 10px;"> <li>: </li> </ol> </td> <td colspan="3" style="border-bottom: none;border-left: none;">&nbsp;</td> </tr> <tr> <td class="text-center" rowspan="2">NO</td> <td class="text-center" >RINCIAN KELUARAN YANG<br>DIHASILKAN PER KEGIATAN</td> <td class="text-center" >VOLUME<br>KUANTITAS</td> <td class="text-center" >SATUAN<br>VOLUME</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr> <td class="text-center" >a</td> <td class="text-center" >b</td> <td class="text-center" >c</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php $i = 1; ?> <?php $sub_kegiatan = '' ; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php // var_dump($data_akun_pengeluaran); die; ?> <?php foreach($data_akun_pengeluaran as $data):?> <?php if($sub_kegiatan != $data->nama_subkomponen): ?> <tr> <td class="text-center" ><?=$i?></td> <td style="padding-left: 10px;" rel="<?=$data->kode_usulan_rkat?>" class="nm_subkomponen"><b><?=$data->nama_subkomponen?></b></td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php if(!empty($rincian_keluaran)): ?> <?php foreach($rincian_keluaran as $kel):?> <?php if($kel->kode_usulan_rka == $data->rka):?> <tr class="keluaran_<?=$data->rka?>"> <td class="text-center" >&nbsp;</td> <td style="padding-left: 10px;"><?=$kel->keluaran?></td> <td class="text-center"><?=$kel->volume?></td> <td class="text-center"><?=$kel->satuan?></td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php endif; ?> <?php endforeach;?> <?php else: ?> <tr class="keluaran_<?=$data->rka?>"> <td class="text-center" >&nbsp;</td> <td style="padding-left: 10px;" class="td_zonk">[ <a href="#" rel="<?=$data->rka?>" id="" class="a_tambah_keluaran">tambah</a> ]</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php endif; ?> <?php $sub_kegiatan = $data->nama_subkomponen ; ?> <?php $i = $i + 1 ; ?> <?php endif; ?> <?php endforeach;?> <?php else: ?> <tr> <td class="text-center" colspan="4">- data kosong -</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php endif; ?> <tr> <td class="text-center" >&nbsp;</td> <td class="text-center" >&nbsp;</td> <td class="text-center" >&nbsp;</td> <td class="text-center" >&nbsp;</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr> <td class="text-center" colspan="4" style="height: 50px;border-right:none;border-bottom: none;">&nbsp;</td> <td class="text-center" colspan="3" style="height: 50px;border-left:none;border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr> <td colspan="4" style="border-right:none;border-top: none;border-bottom: none;">&nbsp;</td> <td colspan="3" style="border-left:none;border-top: none;border-bottom: none;"> Semarang, <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spp==''?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?> <br> Bendahara Pengeluaran SUKPA<br> <br> <br> <br> <br> <span ><?=isset($detail_pic->nmbendahara)?$detail_pic->nmbendahara:''?></span><br> NIP. <span ><?=isset($detail_pic->nipbendahara)?$detail_pic->nipbendahara:''?></span><br> </td> </tr> <tr> <td class="text-center" colspan="7" style="border-top: none;">&nbsp;</td> </tr> </tbody> </table> </div> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev" style="background-image: none;width: 25px;"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true" style="color: #f00"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next" style="background-image: none;width: 25px;"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true" style="color: #f00"></span> <span class="sr-only">Next</span> </a> </div> </div> <br /> <form action="<?=site_url('rsa_up/cetak_spp')?>" id="form_spp" method="post" style="display: none" > <input type="text" name="dtable" id="dtable" value="" /> </form> <div class="alert alert-warning" style="text-align:center"> <?php if($doc_up == 'SPP-DRAFT'){ ?> <!--<a href="#" class="btn btn-warning" id="proses_spp"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> Setujui SPP</a>--> <!--<a href="#" class="btn btn-warning" id="tolak_spp" data-toggle="modal" data-target="#myModalTolakSPP"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Tolak SPP</a>--> <button type="button" class="btn btn-info" id="cetak" rel=""><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Cetak</button> <button type="button" class="btn btn-default" id="xls_spp" rel=""><span class="fa fa-file-excel-o" aria-hidden="true"></span> Unduh .xls</button> <!--<a href="#" class="btn btn-success" id="down"><span class="glyphicon glyphicon-save-file" aria-hidden="true"></span> Download</a>--> <?php }else{ ?> <!--<a href="#" class="btn btn-warning" disabled="disabled" ><span class="glyphicon glyphicon-check" aria-hidden="true"></span> Setujui SPP</a>--> <!--<a href="#" class="btn btn-warning" disabled="disabled"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Tolak SPP</a>--> <button type="button" class="btn btn-info" id="cetak" rel=""><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Cetak</button> <button type="button" class="btn btn-default" id="xls_spp" rel=""><span class="fa fa-file-excel-o" aria-hidden="true"></span> Unduh .xls</button> <!--<a href="#" class="btn btn-success" id="down"><span class="glyphicon glyphicon-save-file" aria-hidden="true"></span> Download</a>--> <?php } ?> </div> </div> <div role="tabpanel" class="tab-pane" id="spm"> <div style="background-color: #EEE; padding: 10px;"> <div id="myCarouselSPM" class="carousel slide" data-ride="carousel" data-interval="false"> <ol class="carousel-indicators"> <li data-target="#myCarouselSPM" data-slide-to="0" class="active">1</li> <li data-target="#myCarouselSPM" data-slide-to="1">2</li> </ol> <div class="carousel-inner" role="listbox"> <div class="item active" id="e"> <div id="div-cetak-2"> <table id="table_spm" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 900px;border: 1px solid #000;background-color: #FFF;" cellspacing="0" border="1" cellpadding="0" > <tbody> <tr > <td colspan="5" style="text-align: right;font-size: 30px;padding: 10px;"><b>F2</b></td> </tr> <tr > <td colspan="5" style="text-align: center;padding-top: 5px;padding-bottom: 5px;height: 72px;" align="center"> <img src="<?php echo base_url(); ?>/assets/img/logo_1.png" width="60"> </td> </tr> <tr style=""> <td colspan="5" style="text-align: center;font-size: 20px;border-bottom: none;"><b>UNIVERSITAS DIPONEGORO</b></td> </tr> <tr style="border-top: none;"> <td colspan="5" style="text-align: center;font-size: 16px;border-bottom: none;border-top: none;"><b>SURAT PERINTAH MEMBAYAR</b></td> </tr> <tr style="border-top: none;border-bottom: none;"> <td colspan="2" style="border-right: none;border-right: none;border-top: none;border-bottom: none;"><b>TAHUN ANGGARAN : <?=$cur_tahun_spm?></b></td> <td style="text-align: center;border-right: none;border-left: none;border-top: none;border-bottom: none;" colspan="2">&nbsp;</td> <td style="border-left: none;border-top: none;border-bottom: none;"><b>JENIS : TUP-NIHIL</b></td> </tr> <tr style="border-top: none;"> <td colspan="2" style="border-right: none;border-top:none;"><b>Tanggal : <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spm==''?'':strftime("%d %B %Y", strtotime($tgl_spm)); ?></td> <td style="text-align: center;border-left: none;border-right: none;border-top:none;" colspan="2" >&nbsp;</td> <td style="border-left: none;border-top:none;"><b>Nomor : <span id="nomor_trx_spm"><?=$nomor_spm?></span><!--01/<?=$alias?>/SPM-UP/JAN/<?=$cur_tahun?>--></b></td> </tr> <tr > <td colspan="5"><b>Satuan Unit Kerja Pengguna Anggaran (SUKPA) : <?=$unit_kerja?></b></td> </tr> <tr > <td colspan="5"><b>Unit Kerja : <?=$unit_kerja?> &nbsp;&nbsp; Kode Unit Kerja : <?=$unit_id?></b></td> </tr> <tr style="border-bottom: none;"> <td colspan="4" style="border-right: none;border-bottom: none;">&nbsp;</td> <td style="line-height: 16px;border-left: none;border-bottom: none;">Kepada Yth.<br> Bendahara Umum Undip ( BUU )<br> di Semarang </td> </tr> <tr > <td colspan="5" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr > <td colspan="5" style="border-bottom: none;border-top: none;">Dengan Berpedoman pada Dokumen SPP yang disampaikan bendahara pengeluaran dan telah diteliti keabsahan dan kebenarannya oleh PPK-SUKPA. bersama ini kami memerintahkan kepada Kuasa BUU untuk membayar sebagai berikut : </tr> <tr> <td colspan="5" style="line-height: 16px;border-bottom: none;border-top: none;"> <ol style="list-style-type: lower-alpha;margin-top: 0px;margin-bottom: 0px;" > <li>Jumlah pembayaran yang diminta : Rp. <span id="jumlah_bayar" style='mso-number-format:"\@";'><?php echo isset($detail_tup_spm['nom'])?number_format($detail_tup_spm['nom'], 0, ",", "."):''; ?></span>,-<br> &nbsp;&nbsp;&nbsp;(Terbilang : <b><span id="terbilang"><?php echo isset($detail_tup_spm['terbilang'])?ucwords($detail_tup_spm['terbilang']):''; ?></span></b>)</li> <li>Untuk keperluan : <span id="untuk_bayar"><?=isset($detail_pic->untuk_bayar)?$detail_pic->untuk_bayar:''?></span></li> <li>Nama bendahara pengeluaran : <span id="penerima"><?=isset($detail_pic->penerima)?$detail_pic->penerima:''?></span></li> <li>Alamat : <span id="alamat"><?=isset($detail_pic->alamat_penerima)?$detail_pic->alamat_penerima:''?></span></li> <li>Nama Bank : <span id="nmbank"><?=isset($detail_pic->nama_bank_penerima)?$detail_pic->nama_bank_penerima:''?></span></li> <li>No. Rekening Bank : <span id="rekening"><?=isset($detail_pic->no_rek_penerima)?$detail_pic->no_rek_penerima:''?></span></li> <li>No. NPWP : <span id="npwp"><?=isset($detail_pic->npwp_penerima)?$detail_pic->npwp_penerima:''?></span></li> </ol> </td> </tr> <tr> <td colspan="5" style="border-top: none;"> Pembayaran sebagaimana tersebut diatas, dibebankan pada pengeluaran dengan uraian sebagai berikut :<br> </td> </tr> </tr> <tr > <td colspan="3" style="vertical-align: top;border-top:none;padding-left: 0;"> <table style="font-family:arial;font-size:12px;line-height: 21px;border-collapse: collapse;width: 100%;border: 1px solid #000;background-color: #FFF;border-left: none;border-right:none;" cellspacing="0" border="1" cellpadding="0"> <tr> <td style="text-align: center" colspan="3"><b>PENGELUARAN</b></td> </tr> <tr> <td style="border-right: solid 1px #000;text-align: center;">NAMA AKUN</td> <td style="border-right: solid 1px #000;text-align: center;">KODE AKUN</td> <td style="text-align: center;">JUMLAH UANG</td> </tr> <?php $jml_pengeluaran = 0; ?> <?php $sub_kegiatan = '' ; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php foreach($data_akun_pengeluaran as $data):?> <?php if($sub_kegiatan != $data->nama_subkomponen): ?> <tr> <td colspan="3"> <b><?=$data->nama_subkomponen?></b> </td> </tr> <?php $sub_kegiatan = $data->nama_subkomponen ; ?> <?php endif; ?> <tr> <td style="border-right: solid 1px #000"> <?=$data->nama_akun5digit?> </td> <td style="text-align: center;border-right: solid 1px #000;"> <?=$data->kode_akun5digit?> </td> <td style='text-align: right;mso-number-format:"\@";'> <?php $jml_pengeluaran = $jml_pengeluaran + $data->pengeluaran ; ?> Rp. <?=number_format($data->pengeluaran, 0, ",", ".")?> </td> </tr> <?php endforeach;?> <?php else: ?> <tr> <td style="border-right: solid 1px #000"> &nbsp; </td> <td style="text-align: center;border-right: solid 1px #000;"> &nbsp; </td> <td style="text-align: right;"> Rp. 0 </td> </tr> <?php endif; ?> <tr> <td colspan="2" style="border-right: solid 1px #000"> Jumlah Pengeluaran </td> <td style='text-align: right;mso-number-format:"\@";'> Rp. <?=number_format($jml_pengeluaran, 0, ",", ".")?> </td> </tr> <tr> <td colspan="2" style="border-right: solid 1px #000"> Dikurangi : Jumlah potongan untuk pihak lain </td> <td style='text-align: right;mso-number-format:"\@";'> <?php $tot_pajak__ = 0 ; if(!empty($data_spp_pajak)){ foreach($data_spp_pajak as $data){ $tot_pajak__ = $tot_pajak__ + $data->rupiah ; } } ?> Rp. <?=number_format($tot_pajak__, 0, ",", ".")?> </td> </tr> <td colspan="2" style="border-right: solid 1px #000"> <strong>Jumlah dana yang dikeluarkan</strong> </td> <td style='text-align: right;mso-number-format:"\@";'> Rp. <?=number_format(($jml_pengeluaran - $tot_pajak__), 0, ",", ".")?> </td> </table> </td> <td colspan="2" style="vertical-align: top;border-top:none;padding-right: 0;"> <table style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 100%;border: 1px solid #000;background-color: #FFF;border-left: none;border-right:none;" cellspacing="0" border="1" cellpadding="0"> <tr> <td style="text-align: center" colspan="2"><b>PERHITUNGAN TERKAIT PIHAK LAIN</b></td> </tr> <tr> <td style="text-align: center" colspan="2">PENERIMAAN DARI PIHAK KE-3</td> </tr> <tr> <td style="border-right: solid 1px #000;width: 50%;text-align: center;">Akun</td> <td style="width: 50%;text-align: center;">Jumlah Uang</td> </tr> <tr> <td style="border-right: solid 1px #000;text-align: center;">-</td> <td style="text-align: right;">Rp. 0</td> </tr> <tr> <td style="border-right: solid 1px #000;"><b>Jumlah Penerimaan</b></td> <td style="text-align: right;">Rp. 0</td> </tr> <tr> <td colspan="2" style="text-align: center"> POTONGAN UNTUK PIHAK LAIN </td> </tr> <tr> <td style="text-align: center;border-right: solid 1px #000;"> Akun Pajak dan Potongan Lainnya </td> <td style="text-align: center"> Jumlah Uang </td> </tr> <?php $tot_pajak_ = 0 ; ?> <?php if(!empty($data_spp_pajak)): ?> <?php foreach($data_spp_pajak as $data):?> <tr> <td style="border-right: solid 1px #000;"> <?php if($data->jenis == 'PPN'){ echo 'Pajak Pertambahan Nilai'; }elseif($data->jenis == 'PPh'){ echo 'Pajak Penghasilan'; }else{ echo 'Lainnya'; } ?> </td> <td style='text-align: right;mso-number-format:"\@";'> <?php $tot_pajak_ = $tot_pajak_ + $data->rupiah ?> Rp. <?=number_format($data->rupiah, 0, ",", ".")?> </td> </tr> <?php endforeach;?> <?php else: ?> <tr> <td style="border-right: solid 1px #000;"> &nbsp; </td> <td style="text-align: right;"> &nbsp; </td> </tr> <?php endif; ?> <tr> <td style="border-right: solid 1px #000;"> <b>Jumlah Potongan</b> </td> <td style='text-align: right;mso-number-format:"\@";'> Rp. <?=number_format($tot_pajak_, 0, ",", ".")?> </td> </tr> </table> </td> </tr> <tr > <td colspan="5" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr style="border-bottom: none;"> <td colspan="5" style="line-height: 16px;border-bottom: none;border-top:none;"> Surat Perintah Membayar ( SPM ) Sebagaimana dimaksud diatas, disusun sesuai dengan dokumen lampiran yang persyaratkan dan disampaikan secara bersamaan serta merupakan bagian yang tidak terpisahkan dari surat ini.<br><br> </td> <tr> <tr style="border-top: none;"> <td colspan="3" style="line-height: 16px;border-right: none;border-top:none;"> Dokumen SPM, dan lampirannya telah diverifikasi keabsahannya<br> PPK-SUKPA<br> <br> <br> <br> <br> <span id="nmppk"><?=isset($detail_ppk->nm_lengkap)?$detail_ppk->nm_lengkap:''?></span><br> NIP. <span id="nipppk"><?=isset($detail_ppk->nomor_induk)?$detail_ppk->nomor_induk:''?></span><br> </td> <td style="border-left: none;border-right: none;border-top:none;">&nbsp;</td> <td style="line-height: 16px;border-left: none;border-top:none;"> Semarang, <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spm_kpa==''?'':strftime("%d %B %Y", strtotime($tgl_spm_kpa)); ?><br /> <?php if($unit_id==91){ ?> Pejabat Penandatangan SPM <?php }else{ ?> Kuasa Pengguna Anggaran <?php }?><br> <br> <br> <br> <br> <span id="nmkpa"><?=isset($detail_kpa->nm_lengkap)?$detail_kpa->nm_lengkap:''?></span><br> NIP. <span id="nipkpa"><?=isset($detail_kpa->nomor_induk)?$detail_kpa->nomor_induk:''?></span><br> </td> </tr> <tr> <td colspan="5" style="line-height: 16px;"> <strong>Keterangan:</strong> <ul> <li>Semua bukti pengeluaran untuk pekerjaan dengan perjanjian yang disahkan Pejabat Pembuat Komitmen telah diuji dan dinyatakan memenuhi persyaratan untuk dilakukan pembayaran atas beban RKAT Undip, selanjutnya bukti-bukti pengeluaran dimaksud disimpan dan ditatausahakan oleh Pejabat Penatausahaan Keuangan SUKPA</li> <li>Semua bukti-bukti pengeluaran untuk pekerjaan yang disahkan Pejabat Pelaksana dan Pengendali Kegiatan (PPPK) telah diuji dan dinyatakan memenuhi persyaratan untuk dilakukan pembayaran atas beban RKAT Undip, selanjutnya bukti-bukti pengeluaran dimaksud disimpan dan ditatausahakan oleh Pejabat Penatausahaan SUKPA.</li> <li>Kebenaran perhitungan dan isi tertuang dalam SPP ini menjadi tanggung jawab Bendahara Pengeluaran sepanjang sesuai dengan bukti-bukti pengeluaran yang telah ditandatangani oleh PPPK atau PPK</li> </ul> </td> </tr> <tr> <td colspan="2" style="vertical-align: top;line-height: 16px;"> Dokumen SPM. dan Lampirannya telah <br> diverifikasi kelengkapannya<br> Tanggal : <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spm_verifikator==''?'':strftime("%d %B %Y", strtotime($tgl_spm_verifikator)); ?><br /> <br> <br> <br> <br> <span id="nmverifikator"><?php echo isset($detail_verifikator->nm_lengkap)? $detail_verifikator->nm_lengkap : '' ; ?></span><br> NIP. <span id="nipverifikator"><?php echo isset($detail_verifikator->nomor_induk)? $detail_verifikator->nomor_induk : '' ;?></span><br> </td> <td colspan="2" style="vertical-align: top;line-height: 16px;padding-left: 10px;"> <?php if(isset($detail_tup_spm['nom'])){ ?> <?php if($detail_tup_spm['nom'] >= 100000000){ ?> Setuju dibayar : <br> Kuasa Bendahara Umum Undip harap membayar<br> kepada nama yang tersebut sesuai SPM dari KPA<br> Bendahara Umum Undip<br> <br> <br> <br> <span id="nmbuu"><?=$detail_buu->nm_lengkap?></span><br> NIP. <span id="nipbuu"><?=$detail_buu->nomor_induk?></span><br> <?php }else{ ?> <span style="display: inline-block;width: 280px;">&nbsp;</span> <?php } ?> <?php }else{ ?> <span style="display: inline-block;width: 280px;">&nbsp;</span> <?php } ?> </td> <td style="vertical-align: top;line-height: 16px;padding-left: 10px;"> Tanggal : <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spm_kbuu==''?'':strftime("%d %B %Y", strtotime($tgl_spm_kbuu)); ?><br /> Telah dibayar oleh <br> Kuasa Bendahara Umum Undip<br> <br> <br> <br> <br> <span id="nmkbuu"><?=$detail_kuasa_buu->nm_lengkap?></span><br> NIP. <span id="nipkbuu"><?=$detail_kuasa_buu->nomor_induk?></span><br> </td> </tr> </tbody> </table> </div> </div> <div class="item" id="f"> <div id="div-cetak-f1a-2"> <table id="table_f2a" class="table_lamp" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 900px;border: 1px solid #000;background-color: #FFF;" cellspacing="0" border="1" cellpadding="0" > <tbody> <tr > <td colspan="7" style="text-align: right;font-size: 30px;padding: 10px;"><b>F2A</b></td> </tr> <tr > <td colspan="7" style="text-align: center;border-bottom: none;height: 72px;"> <img src="<?php echo base_url(); ?>/assets/img/logo_1.png" width="60"> </td> </tr> <tr > <td colspan="7" style="text-align: center;border-bottom: none;"> <h4><b>UNIVERSITAS DIPONEGORO</b></h4> <h5><b>RINCIAN SURAT PERINTAH MEMBAYAR TUP-NIHIL</b></h5> </td> </tr> <tr> <td style="border-right: none;border-top: none;border-bottom: none;">&nbsp;</td> <td colspan="2" style="border: none;"> <b>NO SPM : <?=$nomor_spm?></b> </td> <td style="border: none;">&nbsp;</td> <td colspan="3" style="border-left: none;border-top: none;border-bottom: none;"> <b>TANGGAL : <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spp==''?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?></b> </td> </tr> <tr> <td style="border-right: none;border-top: none;border-bottom: none;">&nbsp;</td> <td colspan="2" style="border: none;text-transform: uppercase"> <b>SUKPA : <?=$unit_kerja?></b> </td> <td style="border: none;">&nbsp;</td> <td colspan="3" style="border-left: none;border-top: none;border-bottom: none;text-transform: uppercase"> <b>UNIT KERJA : <?=$unit_kerja?></b> </td> </tr> <tr> <td class="text-center" colspan="7" style="border-top: none;border-bottom: none;">&nbsp;</td> </tr> <tr> <td colspan="2" style="border-right: none;border-top: none;"> <ol> <li>Nomor dan tanggal SPK / Kontrak </li> <li>Nilai SPK / Kontrak </li> <li>Total nilai SPK / Kontrak yang terbayar</li> <li>Termin pembayaran saat ini</li> <li>Jenis kegiatan</li> <li>Nomer / tanggal berita acara pembayaran</li> <li>Nomer / tanggal berita acara penerimaan barang</li> <li>Rincian pembebanan belanja</li> </ol> </td> <td colspan="5" style="border-left: none;border-top: none;"> <ol style="list-style: none;"> <li>: -</li> <li>: -</li> <li>: -</li> <li>: Lunas</li> <li>: Non Fisik</li> <li>: Terlampir</li> <li>: Terlampir</li> <li>:</li> </ol> </td> </tr> <tr> <td class="text-center" rowspan="2" style="width: 50px;">NO</td> <td class="text-center">KEGIATAN DAN AKUN</td> <td class="text-center">PAGU DALAM RKAT<br>( Rp )</td> <td class="text-center">SPP/SPM S.D.<br>YANG LALU( Rp )</td> <td class="text-center">SPP INI<br>( Rp )</td> <td class="text-center">JUMLAH S.D.<br>SPP INI( Rp )</td> <td class="text-center">SISA DANA<br>( Rp )</td> </tr> <tr> <td class="text-center">a</td> <td class="text-center">b</td> <td class="text-center">c</td> <td class="text-center">d</td> <td class="text-center">e = c + d</td> <td class="text-center">f = b - e</td> </tr> <?php $jml_pengeluaran = 0; ?> <?php $sub_kegiatan = '' ; ?> <?php $i = 1 ; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php foreach($data_akun_pengeluaran as $data):?> <?php if($sub_kegiatan != $data->nama_subkomponen): ?> <tr> <td class="text-center"><?=$i?></td> <td style="padding-left: 10px;"> <b><?=$data->nama_subkomponen?></b> </td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> </tr> <?php $pagu_rkat = 0 ;?> <?php $jml_spm_lalu = 0 ;?> <?php $sub_kegiatan = $data->nama_subkomponen ; ?> <?php $i = $i + 1 ; ?> <?php endif; ?> <tr> <td class="text-center">&nbsp;</td> <td style="padding-left: 10px;"><?=$data->nama_akun5digit?></td> <?php if(!empty($data_akun_rkat)):?> <?php foreach($data_akun_rkat as $da): ?> <?php if($da->kode_usulan_rkat == $data->kode_usulan_rkat):?> <?php if($da->kode_akun5digit == $data->kode_akun5digit):?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format($da->pagu_rkat, 0, ",", ".")?></td> <?php $pagu_rkat = $da->pagu_rkat ;?> <?php endif;?> <?php endif;?> <?php endforeach; ?> <?php else: ?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format('0', 0, ",", ".")?></td> <?php $pagu_rkat = 0 ;?> <?php endif;?> <?php $empty_pengeluaran_lalu = false ; ?> <?php if(!empty($data_akun_pengeluaran_lalu)): ?> <?php foreach($data_akun_pengeluaran_lalu as $da): ?> <?php if($da->kode_usulan_rkat == $data->kode_usulan_rkat):?> <?php if($da->kode_akun5digit == $data->kode_akun5digit):?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format($da->jml_spm_lalu, 0, ",", ".")?></td> <?php $jml_spm_lalu = $da->jml_spm_lalu ;?> <?php $empty_pengeluaran_lalu = true ; ?> <?php endif;?> <?php endif; ?> <?php endforeach; ?> <?php endif;?> <?php if(!$empty_pengeluaran_lalu): ?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format('0', 0, ",", ".")?></td> <?php $jml_spm_lalu = 0 ;?> <?php endif;?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'> <?php $jml_pengeluaran = $jml_pengeluaran + $data->pengeluaran ; ?> <?=number_format($data->pengeluaran, 0, ",", ".")?> </td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?php echo number_format(($jml_spm_lalu + $data->pengeluaran), 0, ",", "."); ?></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?php echo number_format(($pagu_rkat - ($jml_spm_lalu + $data->pengeluaran)), 0, ",", "."); ?></td> </tr> <?php endforeach;?> <?php else: ?> <tr> <td class="text-center" colspan="7">- data kosong -</td> </tr> <?php endif; ?> <!-- <tr> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> </tr>--> <tr> <td class="text-center" colspan="4"><b>Total Nilai ( Rp )</b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($jml_pengeluaran, 0, ",", ".")?></b></td> <td class="text-center" style="background-color:#ccc">&nbsp;</td> <td class="text-center" style="background-color:#ccc">&nbsp;</td> </tr> <tr> <td class="" style="border-right:none;" colspan="2"> <ol start="9" style=""> <li>Laporan keluaran kegiatan non fisik</li> </ol> </td> <td class="text-left" style="border-left: none; border-right:none;" colspan="2" > <ol style="list-style: none;margin: 10px;"> <li>: </li> </ol> </td> <td colspan="3" style="border-bottom: none;border-left: none;">&nbsp;</td> </tr> <tr> <td class="text-center" rowspan="2">NO</td> <td class="text-center" >RINCIAN KELUARAN YANG<br>DIHASILKAN PER KEGIATAN</td> <td class="text-center" >VOLUME<br>KUANTITAS</td> <td class="text-center" >SATUAN<br>VOLUME</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr> <td class="text-center" >a</td> <td class="text-center" >b</td> <td class="text-center" >c</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php $i = 1; ?> <?php $sub_kegiatan = '' ; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php // var_dump($data_akun_pengeluaran); die; ?> <?php foreach($data_akun_pengeluaran as $data):?> <?php if($sub_kegiatan != $data->nama_subkomponen): ?> <tr> <td class="text-center" ><?=$i?></td> <td style="padding-left: 10px;" rel="<?=$data->kode_usulan_rkat?>" class="nm_subkomponen"><b><?=$data->nama_subkomponen?></b></td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php if(!empty($rincian_keluaran)): ?> <?php foreach($rincian_keluaran as $kel):?> <?php if($kel->kode_usulan_rka == $data->rka):?> <tr class="keluaran_<?=$data->rka?>"> <td class="text-center" >&nbsp;</td> <td style="padding-left: 10px;"><?=$kel->keluaran?></td> <td class="text-center"><?=$kel->volume?></td> <td class="text-center"><?=$kel->satuan?></td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php endif; ?> <?php endforeach;?> <?php else: ?> <tr class="keluaran_<?=$data->rka?>"> <td class="text-center" >&nbsp;</td> <td style="padding-left: 10px;" class="td_zonk">[ <a href="#" rel="<?=$data->rka?>" id="" class="a_tambah_keluaran">tambah</a> ]</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php endif; ?> <?php $sub_kegiatan = $data->nama_subkomponen ; ?> <?php $i = $i + 1 ; ?> <?php endif; ?> <?php endforeach;?> <?php else: ?> <tr> <td class="text-center" colspan="4">- data kosong -</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <?php endif; ?> <tr> <td class="text-center" >&nbsp;</td> <td class="text-center" >&nbsp;</td> <td class="text-center" >&nbsp;</td> <td class="text-center" >&nbsp;</td> <td class="text-center" colspan="3" style="border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr> <td class="text-center" colspan="4" style="height: 50px;border-right:none;border-bottom: none;">&nbsp;</td> <td class="text-center" colspan="3" style="height: 50px;border-left:none;border-bottom: none;border-top: none;">&nbsp;</td> </tr> <tr> <td colspan="4" style="border-right:none;border-top: none;border-bottom: none;">&nbsp;</td> <td colspan="3" style="border-left:none;border-top: none;border-bottom: none;"> <!--Semarang, <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spp==''?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?> --><br> <!--Bendahara Pengeluaran SUKPA--><br> <br> <br> <br> <br> <!--<span ><?=isset($detail_pic->nmbendahara)?$detail_pic->nmbendahara:''?></span>--><br> <!--NIP. <span ><?=isset($detail_pic->nipbendahara)?$detail_pic->nipbendahara:''?></span>--><br> </td> </tr> <tr> <td class="text-center" colspan="7" style="border-top: none;">&nbsp;</td> </tr> </tbody> </table> </div> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarouselSPM" role="button" data-slide="prev" style="background-image: none;width: 25px;"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true" style="color: #f00"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarouselSPM" role="button" data-slide="next" style="background-image: none;width: 25px;"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true" style="color: #f00"></span> <span class="sr-only">Next</span> </a> </div> </div> <br /> <form action="<?=site_url('rsa_up/cetak_spp')?>" id="form_spp" method="post" style="display: none" > <input type="text" name="dtable" id="dtable" value="" /> </form> <div class="alert alert-warning" style="text-align:center"> <?php if($doc_up == 'SPM-DRAFT-KPA'){ ?> <a href="#" class="btn btn-warning" id="proses_spm_kpa"><span class="glyphicon glyphicon-check" aria-hidden="true"></span> Setujui SPM</a> <a href="#" class="btn btn-warning" data-toggle="modal" data-target="#myModalTolakSPMPPK"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Tolak SPM</a> <!--<a href="#" class="btn btn-success" id="down_2"><span class="glyphicon glyphicon-save-file" aria-hidden="true"></span> Download</a>--> <button type="button" class="btn btn-info" id="cetak-spm" rel=""><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Cetak</button> <button type="button" class="btn btn-default" id="xls_spm" rel=""><span class="fa fa-file-excel-o" aria-hidden="true"></span> Unduh .xls</button> <?php }else{ ?> <a href="#" class="btn btn-warning" disabled="disabled" ><span class="glyphicon glyphicon-check" aria-hidden="true"></span> Setujui SPM</a> <a href="#" class="btn btn-warning" disabled="disabled"><span class="glyphicon glyphicon-remove-sign" aria-hidden="true"></span> Tolak SPM</a> <!--<a href="#" class="btn btn-success" id="down_2"><span class="glyphicon glyphicon-save-file" aria-hidden="true"></span> Download</a>--> <button type="button" class="btn btn-info" id="cetak-spm" rel=""><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Cetak</button> <button type="button" class="btn btn-default" id="xls_spm" rel=""><span class="fa fa-file-excel-o" aria-hidden="true"></span> Unduh .xls</button> <?php } ?> </div> </div> <div role="tabpanel" class="tab-pane" id="lampiran"> <div style="background-color: #EEE; padding: 10px;"> <div id="myCarouselLampiran" class="carousel slide" data-ride="carousel" data-interval="false"> <ol class="carousel-indicators"> <li data-target="#myCarouselLampiran" data-slide-to="0" class="active">1</li> <li data-target="#myCarouselLampiran" data-slide-to="1">2</li> </ol> <div class="carousel-inner" role="listbox"> <div class="item active" id="c"> <div id="div-cetak-lampiran-spj"> <table id="table_spj" class="table_lamp" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 900px;border: 1px solid #000;background-color: #FFF;" cellspacing="0" border="1" cellpadding="0" > <tbody> <tr > <td colspan="6" style="text-align: center;height: 72px;"> <img src="<?php echo base_url(); ?>/assets/img/logo_1.png" width="60"> </td> </tr> <tr > <td colspan="6" class="text-center" style="text-align: center;border: none;"> <h4><b>UNIVERSITAS DIPONEGORO</b></h4> <h5><b>SURAT PERTANGGUNGJAWABAN UANG PERSEDIAAN BENDAHARA PENGELUARAN</b></h5> </td> </tr> <tr> <td colspan="2" style="border: none;">&nbsp;</td> <td colspan="2" style="text-transform: uppercase;border: none;"><b>SUKPA : <?=$unit_kerja?></b></td> <td colspan="2" style="text-transform: uppercase;border: none;"><b>UNIT KERJA : <?=$unit_kerja?></b></td> </tr> <tr> <td style="border-top:none;" colspan="6">&nbsp;</td> </tr> <tr> <td class="text-center" style="width: 50px;">NO</td> <td class="text-center">KODE SUB KEGIATAN<br>/ RINCIAN AKUN</td> <td class="text-center">URAIAN</td> <td class="text-center">SPJ TUP-NIHIL s.d BULAN LALU<br>( Rp )</td> <td class="text-center">SPJ TUP-NIHIL BULAN INI<br>( Rp )</td> <td class="text-center">SPJ TUP-NIHIL s.d BULAN INI<br>( Rp )</td> </tr> <tr > <td style="">&nbsp;</td> <td style="">&nbsp;</td> <td style="">&nbsp;</td> <td style="">&nbsp;</td> <td style="">&nbsp;</td> <td style="">&nbsp;</td> </tr> <?php $jml_pengeluaran = 0; ?> <?php $sub_kegiatan = '' ; ?> <?php $i = 1 ; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php foreach($data_akun_pengeluaran as $data):?> <?php if($sub_kegiatan != $data->nama_subkomponen): ?> <tr> <td class="text-center"><?=$i?></td> <td class="text-center">&nbsp;</td> <td style="padding-left: 10px;"> <b><?=$data->nama_subkomponen?></b> </td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> </tr> <?php $pagu_rkat = 0 ;?> <?php $jml_spm_lalu = 0 ;?> <?php $sub_kegiatan = $data->nama_subkomponen ; ?> <?php $i = $i + 1 ; ?> <?php endif; ?> <tr> <td class="text-center">&nbsp;</td> <td class="text-center"><?=$data->kode_akun5digit?></td> <td style="padding-left: 10px;"><?=$data->nama_akun5digit?></td> <?php $empty_pengeluaran_lalu = false ; ?> <?php if(!empty($data_akun_pengeluaran_lalu)):?> <?php foreach($data_akun_pengeluaran_lalu as $da): ?> <?php if($da->kode_usulan_rkat == $data->kode_usulan_rkat):?> <?php if($da->kode_akun5digit == $data->kode_akun5digit):?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format($da->jml_spm_lalu, 0, ",", ".")?></td> <?php $jml_spm_lalu = $da->jml_spm_lalu ;?> <?php $empty_pengeluaran_lalu = true ; ?> <?php endif;?> <?php endif;?> <?php endforeach; ?> <?php endif;?> <?php if(!$empty_pengeluaran_lalu): ?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?=number_format('0', 0, ",", ".")?></td> <?php $jml_spm_lalu = 0 ;?> <?php endif;?> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'> <?php $jml_pengeluaran = $jml_pengeluaran + $data->pengeluaran ; ?> <?=number_format($data->pengeluaran, 0, ",", ".")?> </td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><?php echo number_format(($jml_spm_lalu + $data->pengeluaran), 0, ",", "."); ?></td> </tr> <?php endforeach;?> <?php else: ?> <tr> <td class="text-center" colspan="6">- data kosong -</td> </tr> <?php endif; ?> <!-- <tr> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> <td class="text-center">&nbsp;</td> </tr>--> <tr> <td class="text-center" colspan="4"><b>Total Nilai ( Rp )</b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($jml_pengeluaran, 0, ",", ".")?></b></td> <td class="text-center" style="background-color:#ccc">&nbsp;</td> </tr> <tr> <td class="text-center" colspan="6" style="border-bottom: none;border-right: none;border-left: none;">&nbsp;</td> </tr> <tr> <td colspan="6" style="border : none;"><b>Potongan :</b></td> </tr> <?php $tot_pajak_ = 0 ; ?> <?php $n = 1 ; ?> <?php if(!empty($data_spp_pajak)): ?> <?php foreach($data_spp_pajak as $data):?> <tr> <td class="text-center" style="border:none;"> <?php echo $n; ?> </td> <td style="border:none;"> <?php if($data->jenis == 'PPN'){ echo 'Pajak Pertambahan Nilai'; }elseif($data->jenis == 'PPh'){ echo 'Pajak Penghasilan'; }else{ echo 'Lainnya'; } ?> </td> <td style='border:none;mso-number-format:"\@";' class="text-right"> <?php $tot_pajak_ = $tot_pajak_ + $data->rupiah ?> Rp. <?=number_format($data->rupiah, 0, ",", ".")?> </td> <td class="text-center" colspan="3" style="border: none;">&nbsp;</td> </tr> <?php $n++; ?> <?php endforeach;?> <?php else: ?> <tr> <td class="text-center" colspan="3" style="border: none;">&nbsp;</td> <td class="text-center" colspan="3" style="border: none;">&nbsp;</td> </tr> <?php endif; ?> <tr> <td class="text-center" colspan="2" style="border: none;">&nbsp;</td> <td style="border-top: none;border-right: none;border-left: none;">&nbsp;</td> <td class="text-center" colspan="3" style="border: none;">&nbsp;</td> </tr> <tr> <td colspan="2" style="border : none;"><b>Total Potongan :</b></td> <td style='border : none;mso-number-format:"\@";' class="text-right"> Rp. <?=number_format($tot_pajak_, 0, ",", ".")?> </td> <td colspan="3" style="border: none">&nbsp;</td> </tr> <tr> <td colspan="6" style="border: none">&nbsp;</td> </tr> <tr> <td colspan="2" style="border: none;">&nbsp;</td> <td colspan="2" style="border: none;"> Telah diperiksa kebenarannya oleh,<br> PPK SUKPA<br> <br> <br> <br> <br> <span ><?=isset($detail_ppk->nm_lengkap)?$detail_ppk->nm_lengkap:''?></span><br> NIP. <span ><?=isset($detail_ppk->nomor_induk)?$detail_ppk->nomor_induk:''?></span><br> </td> <td colspan="2" style="border: none;"> Semarang, <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spp==''?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?> <br> Bendahara Pengeluaran SUKPA<br> <br> <br> <br> <br> <span ><?=isset($detail_pic->nmbendahara)?$detail_pic->nmbendahara:''?></span><br> NIP. <span ><?=isset($detail_pic->nipbendahara)?$detail_pic->nipbendahara:''?></span><br> </td> </tr> <tr> <td colspan="6" style="border: none">&nbsp;</td> </tr> </tbody> </table> </div> </div> <div class="item" id="d"> <div class="free dragscroll" style="overflow-x: scroll;width: 900px;margin: 0 auto;cursor: pointer;"> <div id="div-cetak-lampiran-rekapakun"> <table id="table_rekapakun" class="table_lamp" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 1300px;border: 1px solid #000;background-color: #FFF;" cellspacing="0" border="1" cellpadding="0" > <tbody> <tr > <td colspan="14" class="text-center" style="text-align: center;border: none;"> <h4><b>UNIVERSITAS DIPONEGORO</b></h4> <h5>REKAPITULASI PERTANGGUNGJAWABAN PENGELUARAN</h5> <h5><b>SETIAP SUB KEGIATAN PER RINCIAN AKUN</b></h5> <b style="text-transform: uppercase;">SUKPA : <?=$unit_kerja?> <span style="display: inline-block;width: 100px;">&nbsp;</span> UNIT KERJA : <?=$unit_kerja?></b><br> </td> </tr> <tr> <td colspan="14" style="border: none;">&nbsp;</td> </tr> <?php $jk = 1; ?> <?php if(!empty($data_akun_pengeluaran)): ?> <?php $tot_bruto_ = 0 ;?> <?php $tot_pajak_ = 0 ;?> <?php foreach($data_akun_pengeluaran as $data):?> <tr> <td colspan="14" style="border-bottom: none;">&nbsp;</td> </tr> <tr > <td colspan="14" class="text-center" style="text-align: center;border: none;"> <b style="text-transform: uppercase;">KEGIATAN : <?=$data->nama_komponen?> </b><br> <b style="text-transform: uppercase;">SUB KEGIATAN : <?=$data->nama_subkomponen?> </b><br> <b style="text-transform: uppercase;">KODE AKUN : <?=$data->kode_akun5digit?> <span style="display: inline-block;width: 100px;">&nbsp;</span> URAIAN AKUN : <?=$data->nama_akun5digit?></b><br> <b style="text-transform: uppercase;">BULAN : <?=$bulan?> <span style="display: inline-block;width: 100px;">&nbsp;</span> TAHUN : <?=$cur_tahun?></b><br> </td> </tr> <tr> <td colspan="14" style="border-top: none;">&nbsp;</td> </tr> <tr> <td class="text-center" style="width: 50px;">NO</td> <td class="text-center" style="width: 100px;">TANGGAL</td> <td class="text-center" style="width: 100px;">KD UNIT</td> <td class="text-center" style="width: 150px;">RINCIAN AKUN</td> <td class="text-center" style="width: 100px;">KODE RINCIAN<br>AKUN</td> <td class="text-center" style="width: 150px;">KODE-URAIAN RINCIAN<br>AKUN</td> <td class="text-center" style="width: 100px;">NO BUKTI</td> <td class="text-center">PENGELUARAN<br>( Rp )</td> <td class="text-center">KUANTITAS<br>KELUARAN</td> <td class="text-center">SATUAN<br>KELUARAN</td> <td class="text-center" style="width: 150px;">KETERANGAN KELUARAN</td> <td class="text-center" style="width: 125px;">JENIS POT<br>PAJAK</td> <td class="text-center" style="width: 100px;">NILAI POT</td> <td class="text-center" style="width: 100px;">NETTO</td> </tr> <?php $kl = 1 ;?> <?php $tot_bruto = 0 ;?> <?php $tot_pajak = 0 ;?> <?php foreach($rincian_akun_pengeluaran as $rincian): ?> <?php if(($rincian->rka == $data->rka)&&($rincian->kode_akun5digit == $data->kode_akun5digit)):?> <tr> <td class="text-center" style="vertical-align: top"><?=$kl?></td> <td class="text-center" style="vertical-align: top"><?php echo strftime("%d-%m-%Y", strtotime($rincian->tgl_kuitansi)) ;?></td> <td class="text-center" style="vertical-align: top"><?=$rincian->kdunit?></td> <td class="text-left" style="vertical-align: top;padding-left: 10px;"><?=$rincian->nama_akun?></td> <td class="text-center" style="vertical-align: top"><?=$rincian->kode_akun?></td> <td class="text-left" style="vertical-align: top;padding-left: 10px;"><?=$rincian->kode_akun_tambah?> - <?=$rincian->deskripsi?></td> <td class="text-center" style="vertical-align: top"><?=$rincian->no_bukti?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format(($rincian->volume*$rincian->harga_satuan), 0, ",", ".")?></td> <td class="text-center" style="vertical-align: top"><?=$rincian->volume + 0?></td> <td class="text-center" style="vertical-align: top;"><?=$rincian->satuan?></td> <td class="text-left" style="vertical-align: top;padding-left: 10px;"><?=$rincian->uraian?></td> <td class="text-left" style="vertical-align: top;padding-left: 10px;"><?=$rincian->pajak_nom?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($rincian->total_pajak, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format(($rincian->bruto-$rincian->total_pajak), 0, ",", ".")?></td> <?php $tot_bruto = $tot_bruto + $rincian->bruto ;?> <?php $tot_pajak = $tot_pajak + $rincian->total_pajak ;?> </tr> <?php $kl++ ; ?> <?php endif;?> <?php endforeach;?> <tr> <td colspan="7" style="border-bottom: none; padding-left: 10px;"><b>Total Pengeluaran</b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto, 0, ",", ".")?></b></td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto - $tot_pajak, 0, ",", ".")?></b></td> </tr> <?php $tot_bruto_ = $tot_bruto_ + $tot_bruto ;?> <?php $tot_pajak_ = $tot_pajak_ + $tot_pajak ;?> <?php endforeach;?> <tr> <td colspan="7" style="border-bottom: none; padding-left: 10px;"><b>Grand Total</b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto_, 0, ",", ".")?></b></td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto_ - $tot_pajak_, 0, ",", ".")?></b></td> </tr> <tr> <td colspan="14" style="border-bottom: none;">&nbsp;</td> </tr> <?php else: ?> <tr> <td class="text-center" colspan="14">- data kosong -</td> </tr> <?php endif; ?> <tr> <td colspan="10" style="border-bottom: none;border-top: none;border-right:none;">&nbsp;</td> <td colspan="4" style="border-bottom: none;border-top: none;border-left:none;"> Semarang, <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spp==''?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?> <br> Bendahara Pengeluaran SUKPA<br> <br> <br> <br> <br> <span ><?=isset($detail_pic->nmbendahara)?$detail_pic->nmbendahara:''?></span><br> NIP. <span ><?=isset($detail_pic->nipbendahara)?$detail_pic->nipbendahara:''?></span><br> </td> </tr> <tr> <td colspan="14" style="border-top: none;">&nbsp;</td> </tr> </tbody> </table> </div> </div> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarouselLampiran" role="button" data-slide="prev" style="background-image: none;width: 25px;"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true" style="color: #f00"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarouselLampiran" role="button" data-slide="next" style="background-image: none;width: 25px;"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true" style="color: #f00"></span> <span class="sr-only">Next</span> </a> </div> </div> <br /> <div class="alert alert-warning" style="text-align:center"> <button type="button" class="btn btn-info" id="cetak-lampiran" rel=""><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Cetak</button> <button type="button" class="btn btn-default" id="xls_lamp" rel=""><span class="fa fa-file-excel-o" aria-hidden="true"></span> Unduh .xls</button> </div> </div> <div role="tabpanel" class="tab-pane" id="kuitansi"> <div style="background-color: #EEE; padding: 10px;"> <div class="row"> <div class="col-md-12 table-responsive"> <div style="background-color: #FFF;"> <table class="table table-bordered table-striped table-hover small"> <thead> <tr> <th class="text-center col-md-1" style="vertical-align: middle;">No</th> <th class="text-center col-md-2" style="vertical-align: middle;">Nomor</th> <th class="text-center col-md-2" style="vertical-align: middle;">Tanggal</th> <th class="text-center col-md-2" style="vertical-align: middle;">Uraian</th> <th class="text-center col-md-2" style="vertical-align: middle;">Pengeluaran</th> <th class="text-center col-md-1" style="vertical-align: middle;">&nbsp;</th> <!--<th class="text-center col-md-1" style="vertical-align: middle;">Status</th>--> <!--<th class="text-center col-md-1">Proses</th>--> <!-- <th class="text-center col-md-1"> <div class="input-group"> <span class="input-group-addon" style="background-color: #f9ff83;"> <input type="checkbox" aria-label="" rel="" class="all_ck"> </span> </div> </th>--> </tr> </thead> <tbody> <?php if(!empty($daftar_kuitansi)){ // echo '<pre>';var_dump($daftar_kuitansi);echo '</pre>'; $tot_kuitansi = 0 ; foreach ($daftar_kuitansi as $key => $value) { ?> <tr> <td class="text-center"><?php echo $key + 1; ?>.</td> <td class="text-center"><?php echo $value->no_bukti; ?></td> <td class="text-center"><?php setlocale(LC_ALL, 'id_ID.utf8'); echo strftime("%d %B %Y", strtotime($value->tgl_kuitansi)); ?><br /></td> <td class=""><?php echo $value->uraian; ?></td> <td class="text-right"> <?=number_format($value->pengeluaran, 0, ",", ".")?> <?php $tot_kuitansi = $tot_kuitansi + $value->pengeluaran ; ?> </td> <td class="text-center"> <div class="btn-group"> <button class="btn btn-default btn-sm" rel="<?php echo $value->id_kuitansi; ?>" id="btn-lihat" ><i class="glyphicon glyphicon-search"></i></button> </div> </td> </tr> <?php } ?> <tr class="alert-warning" style="" > <td colspan="4" class="text-right"> <b>Total :</b> </td> <td class="text-right" > <b><?=number_format($tot_kuitansi, 0, ",", ".")?></b> </td> <td > &nbsp; </td> </tr> <?php }else{ ?> <tr> <td colspan="6" class="text-center alert-warning"> Tidak ada data </td> </tr> <?php } ?> <tr> <td colspan="6" >&nbsp;</td> </tr> </tbody> </table> </div> </div> </div> </div> <br /> <div class="alert alert-warning" style="text-align:center"> &nbsp; </div> </div> <div role="tabpanel" class="tab-pane" id="rekappajak"> <div style="background-color: #EEE; padding: 10px;"> <!-- --> <div class="free dragscroll" style="overflow-x: scroll;width: 900px;margin: 0 auto;cursor: pointer;"> <div id="div-cetak-lampiran-rekappajak"> <table id="table_rekappajak" class="table_lamppajak" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 1300px;border: 1px solid #000;background-color: #FFF;" cellspacing="0" border="1" cellpadding="0" > <tbody> <tr > <td colspan="15" class="text-left" style="text-align: left;border: none;padding-left:20px;"> <!--<h4><b>UNIVERSITAS DIPONEGORO</b></h4>--> <h5><b>Lampiran Pajak</b></h5> <h5><b>Nomor SPP : <?=$nomor_spp?></b></h5> <!--<b style="text-transform: uppercase;">SUKPA : <?=$unit_kerja?> <span style="display: inline-block;width: 100px;">&nbsp;</span> UNIT KERJA : <?=$unit_kerja?></b><br>--> </td> </tr> <tr > <td colspan="2" class="text-left" style="text-align: left;border: none;padding-left:20px;"> <!--<h4><b>UNIVERSITAS DIPONEGORO</b></h4>--> <b>Nama Wajib Pajak</b> <!--<b style="text-transform: uppercase;">SUKPA : <?=$unit_kerja?> <span style="display: inline-block;width: 100px;">&nbsp;</span> UNIT KERJA : <?=$unit_kerja?></b><br>--> </td> <td colspan="13" class="text-left" style="text-align: left;border: none;padding-left:20px;"> : Bendahara Pengeluaran Undip </td> </tr> <tr > <td colspan="2" class="text-left" style="text-align: left;border: none;padding-left:20px;"> <!--<h4><b>UNIVERSITAS DIPONEGORO</b></h4>--> <b>NPWP</b> <!--<b style="text-transform: uppercase;">SUKPA : <?=$unit_kerja?> <span style="display: inline-block;width: 100px;">&nbsp;</span> UNIT KERJA : <?=$unit_kerja?></b><br>--> </td> <td colspan="13" class="text-left" style="text-align: left;border: none;padding-left:20px;"> : 00.018.856.5-517.000 </td> </tr> <tr> <td colspan="15" style="border: none;">&nbsp;</td> </tr> <?php $jk = 1; ?> <?php if(!empty($data_rekap_pajak)): ?> <?php $tot_bruto_ = 0 ;?> <?php $tot_pajak_ppn_ = 0 ;?> <?php $tot_pajak_21_ = 0 ;?> <?php $tot_pajak_22_ = 0 ;?> <?php $tot_pajak_23_ = 0 ;?> <?php $tot_pajak_4_2_ = 0 ;?> <?php $tot_pajak_26_ = 0 ;?> <?php $tot_pajak_lainnya_ = 0 ;?> <?php $tot_sub_pajak_ = 0 ;?> <?php $tot_pajak_ = 0 ;?> <?php foreach($data_rekap_pajak as $data_pajak => $akun ):?> <tr> <td colspan="15" style="border-bottom: none;">&nbsp;</td> </tr> <tr> <td class="text-center" style="width: 50px;" rowspan="3"><b>NO</b></td> <td class="text-center" style="width: 100px;" rowspan="3"><b>AKUN</b></td> <td class="text-center" style="width: 100px;" rowspan="3"><b>KUITANSI</b></td> <td class="text-center" style="width: 150px;" rowspan="3"><b>PENERIMA</b></td> <td class="text-center" style="width: 150px;" rowspan="3"><b>URAIAN</b></td> <td class="text-center" rowspan="2"><b>Jml Kotor</b></td> <td class="text-center" rowspan="2"><b>PPN</b></td> <td class="text-center" colspan="5"><b>PPh</b></td> <td class="text-center" rowspan="2"><b>Lainnya</b></td> <td class="text-center" rowspan="2"><b>Jml Pajak</b></td> <td class="text-center" rowspan="2"><b>Jml Bersih</b></td> </tr> <tr> <td class="text-center"><b>21</b></td> <td class="text-center"><b>22</b></td> <td class="text-center"><b>23</b></td> <td class="text-center"><b>4 ayat (2)</b></td> <td class="text-center"><b>26</b></td> </tr> <tr> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> <td class="text-center"><b>Rp</b></td> </tr> <?php // echo $akun ; ?> <?php $kl = 1 ;?> <?php $tot_bruto = 0 ;?> <?php $tot_pajak_ppn = 0 ;?> <?php $tot_pajak_21 = 0 ;?> <?php $tot_pajak_22 = 0 ;?> <?php $tot_pajak_23 = 0 ;?> <?php $tot_pajak_4_2 = 0 ;?> <?php $tot_pajak_26 = 0 ;?> <?php $tot_pajak_lainnya = 0 ;?> <?php $tot_sub_pajak = 0 ;?> <?php $tot_pajak = 0 ;?> <?php foreach($akun as $i => $data):?> <tr> <td class="text-center" style="vertical-align: top"><?=$kl?></td> <td class="text-center" style="vertical-align: top"><?=$data->kode_akun?></td> <td class="text-center" style="vertical-align: top"><?=$data->no_bukti?></td> <td class="text-left" style="vertical-align: top;padding-left: 10px;"><?=$data->penerima_uang?></td> <td class="text-left" style="vertical-align: top;padding-left: 10px;"><?=$data->uraian?></td> <!-- <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->jml_bruto, 0, ",", ".")?></td> --> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data_rekap_bruto[$data_pajak][$i]->jml_bruto, 0, ",", ".")?><?php var_dump(); ?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->PPN, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->PPh21, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->PPh22, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->PPh23, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->PPh4_2, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->PPh26, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data->Lainnya, 0, ",", ".")?></td> <?php $tot_sub_pajak = $data->PPN + $data->PPh21 + $data->PPh22 + $data->PPh23 + $data->PPh4_2 + $data->PPh26 + $data->Lainnya;?> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($tot_sub_pajak, 0, ",", ".")?></td> <td class="text-right" style='vertical-align: top;padding-right: 10px;mso-number-format:"\@";'><?=number_format($data_rekap_bruto[$data_pajak][$i]->jml_bruto - $tot_sub_pajak, 0, ",", ".")?></td> <?php $tot_bruto = $tot_bruto + $data_rekap_bruto[$data_pajak][$i]->jml_bruto ;?> <?php $tot_pajak_ppn = $tot_pajak_ppn + $data->PPN ;?> <?php $tot_pajak_21 = $tot_pajak_21 + $data->PPh21 ;?> <?php $tot_pajak_22 = $tot_pajak_22 + $data->PPh22 ;?> <?php $tot_pajak_23 = $tot_pajak_23 + $data->PPh23 ;?> <?php $tot_pajak_4_2 = $tot_pajak_4_2 + $data->PPh4_2 ;?> <?php $tot_pajak_26 = $tot_pajak_26 + $data->PPh26 ;?> <?php $tot_pajak_lainnya = $tot_pajak_lainnya + $data->Lainnya ;?> <?php $tot_pajak = $tot_pajak + $tot_sub_pajak ;?> </tr> <?php $kl++ ; ?> <?php endforeach;?> <tr> <td colspan="5" style="border-bottom: none; padding-left: 10px;"><b>Sub Jumlah Akun - <?=$data_pajak?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_ppn, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_21, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_22, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_23, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_4_2, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_26, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_lainnya, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto - $tot_pajak, 0, ",", ".")?></b></td> </tr> <?php $tot_bruto_ = $tot_bruto_ + $tot_bruto ;?> <?php $tot_pajak_ppn_ = $tot_pajak_ppn_ + $tot_pajak_ppn ;?> <?php $tot_pajak_21_ = $tot_pajak_21_ + $tot_pajak_21 ;?> <?php $tot_pajak_22_ = $tot_pajak_22_ + $tot_pajak_22 ;?> <?php $tot_pajak_23_ = $tot_pajak_23_ + $tot_pajak_23 ;?> <?php $tot_pajak_4_2_ = $tot_pajak_4_2_ + $tot_pajak_4_2 ;?> <?php $tot_pajak_26_ = $tot_pajak_26_ + $tot_pajak_26 ;?> <?php $tot_pajak_lainnya_ = $tot_pajak_lainnya_ + $tot_pajak_lainnya ;?> <?php $tot_pajak_ = $tot_pajak_ + $tot_pajak ;?> <?php endforeach;?> <tr> <td colspan="5" style="border-bottom: none; padding-left: 10px;"><b>Jumlah</b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_ppn_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_21_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_22_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_23_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_4_2_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_26_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_lainnya_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_pajak_, 0, ",", ".")?></b></td> <td class="text-right" style='padding-right: 10px;mso-number-format:"\@";'><b><?=number_format($tot_bruto_ - $tot_pajak_, 0, ",", ".")?></b></td> </tr> <tr> <td colspan="15" style="border-bottom: none;">&nbsp;</td> </tr> <?php else: ?> <tr> <td class="text-center" colspan="15">- data kosong -</td> </tr> <?php endif; ?> <tr> <td colspan="11" style="border-bottom: none;border-top: none;border-right:none;">&nbsp;</td> <td colspan="4" style="border-bottom: none;border-top: none;border-left:none;"> Semarang, <?php setlocale(LC_ALL, 'id_ID.utf8'); echo $tgl_spp==''?'':strftime("%d %B %Y", strtotime($tgl_spp)); // ?> <br> Bendahara Pengeluaran SUKPA<br> <br> <br> <br> <br> <span ><?=isset($detail_pic->nmbendahara)?$detail_pic->nmbendahara:''?></span><br> NIP. <span ><?=isset($detail_pic->nipbendahara)?$detail_pic->nipbendahara:''?></span><br> </td> </tr> <tr> <td colspan="15" style="border-top: none;">&nbsp;</td> </tr> </tbody> </table> </div> </div> <!-- --> </div> <br /> <div class="alert alert-warning" style="text-align:center"> <button type="button" class="btn btn-info" id="cetak-rekappajak" rel=""><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Cetak</button> <button type="button" class="btn btn-default" id="xls_rekappajak" rel=""><span class="fa fa-file-excel-o" aria-hidden="true"></span> Unduh .xls</button> </div> </div> </div> </div> </div> </div> </div> </div> </div> <img id="status_spp" style="display: none" src="<?php echo base_url(); ?>/assets/img/verified.png" width="150"> <!-- Modal --> <div class="modal" id="myModalTolakSPMPPK" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Konfirmasi</h4> </div> <div class="modal-body"> <p>Alasan penolakan :</p> <p> <div class="form-group"> <textarea class="form-control" id="ket" name="ket"> </textarea> </div> </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="tolak_spm_kpa">Submit</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <!-- Modal --> <div class="modal" id="myModalLihatKet" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Perhatian</h4> </div> <div class="modal-body"> <p>Alasan penolakan :</p> <p> <div class="form-group"> <blockquote> <p><?=$ket?></p> </blockquote> </div> </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <div class="modal " id="myModalKuitansi" role="dialog" aria-labelledby="myModalKuitansiLabel"> <div class="modal-dialog modal-xl" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="myModalLabel">Kuitansi : <span id="kode_badge">-</span></h4> </div> <div class="modal-body" style="margin:0px;padding:15px;background-color: #EEE;"> <div id="div-cetak-kuitansi"> <table class="table_print" id="kuitansi" style="font-family:arial;font-size:12px; line-height: 21px;border-collapse: collapse;width: 800px;border: 1px solid #000;background-color: #FFF;" cellspacing="0px" border="0"> <tr> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> <td class="col-md-1">&nbsp;</td> </tr> <tr> <td rowspan="3" style="text-align: center" colspan="2"> <img src="<?php echo base_url(); ?>/assets/img/logo_1.png" width="60"> </td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td colspan="2">Tahun Anggaran</td> <td style="text-align: center">:</td> <td colspan="2"><span id="kuitansi_tahun">0000</span></td> </tr> <tr> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td colspan="2">Nomor Bukti</td> <td style="text-align: center">:</td> <td colspan="2" id="kuitansi_no_bukti">-</td> </tr> <tr class="tr_up"> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td colspan="2">Anggaran</td> <td style="text-align: center">:</td> <td colspan="2" id="kuitansi_txt_akun">-</td> </tr> <tr> <td colspan="11"> &nbsp; </td> </tr> <tr> <td colspan="11"> <h4 style="text-align: center"><b>KUITANSI / BUKTI PEMBAYARAN</b></h4> </td> </tr> <tr> <td colspan="11"> &nbsp; </td> </tr> <tr class="tr_up"> <td colspan="3">Sudah Diterima dari</td> <td>: </td> <td colspan="7">Pejabat Pembuat Komitmen/ Pejabat Pelaksana dan Pengendali Kegiatan SUKPA <?=$unit_kerja?></td> </tr> <tr class="tr_up"> <td colspan="3">Jumlah Uang</td> <td>: </td> <td colspan="7"><b>Rp. <span class="sum_tot_bruto">0</span>,-</b></td> </tr> <tr class="tr_up"> <td colspan="3">Terbilang</td> <td>: </td> <td colspan="7"><b><span class="text_tot">-</span></b></td> </tr> <tr class="tr_up"> <td colspan="3">Untuk Pembayaran</td> <td>: </td> <td colspan="7"><span id="uraian">-</span></td> </tr> <tr class="tr_up"> <td colspan="3">Sub Kegiatan</td> <td>: </td> <td colspan="7"><span id="nm_subkomponen">-</span></td> </tr> <tr> <td colspan="11"> &nbsp; </td> </tr> <tr id="before_tr_isi"> <td colspan="3"><b>Deskripsi</b></td> <td style="text-align:center"><b>Kuantitas</b></td> <td style="padding: 0 5px 0 5px;"><b>Satuan</b></td> <td style="padding: 0 5px 0 5px;"><b>Harga@</b></td> <td style="padding: 0 5px 0 5px;"><b>Bruto</b></td> <td style="padding: 0 5px 0 5px;" colspan="2"><b>Pajak</b></td> <td >&nbsp;</td> <td ><b>Netto</b></td> </tr> <tr id="tr_isi"> <td colspan="11">&nbsp;</td> </tr> <tr> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td >&nbsp;</td> <td ><b>Jumlah</b></td> <td >&nbsp;</td> <td style="text-align: right"><b><span class="sum_tot_bruto">0</span></b></td> <td >&nbsp;</td> <td style="text-align: right"><b><span class="sum_tot_pajak">0</span></b></td> <td ><b><span style="margin-left:10px;margin-right:10px;">=</span><span style="margin-left:10px;margin-right:10px;">Rp.</span></b></td> <td style="text-align: right"><b><span class="sum_tot_netto">0</span></b></td> </tr> <tr> <td colspan="11"> &nbsp; </td> </tr> <tr> <td colspan="8">Setuju dibebankan pada mata anggaran berkenaan, <br /> a.n. Kuasa Pengguna Anggaran <br /> Pejabat Pelaksana dan Pengendali Kegiatan (PPPK) </td> <td colspan="3"> Semarang, <span id="tgl_kuitansi">-</span><br /> Penerima Uang </td> </tr> <tr> <td colspan="11"> <br> <br> <br> <br> </td> </tr> <tr > <td colspan="8" style="border-bottom: 1px solid #000"><span id="nmpppk">-</span><br> NIP. <span id="nippppk">-</span></td> <td colspan="3" style="border-bottom: 1px solid #000"><span class="edit_here" id="penerima_uang">-</span><br /> NIP. <span class="edit_here" id="penerima_uang_nip">-</span> </td> </tr> <tr > <td colspan="8">Setuju dibayar tgl : <br> Bendahara Pengeluaran </td> <td colspan="3" ><span style="display: none" id="td_tglpumk">Lunas dibayar tgl : <br> Pemegang Uang Muka Kerja</span> </td> </tr> <tr> <td colspan="11"> <br> <br> <br> </td> </tr> <tr> <td colspan="8"><span id="nmbendahara_kuitansi"></span><br> NIP. <span id="nipbendahara_kuitansi"></span> </td> <td colspan="3" ><span style="display: none" id="td_nmpumk"><span id="nmpumk"></span><br> NIP. <span id="nippumk"></span></span> </td> </tr> <tr > <td colspan="11" style="border-top:1px solid #000"> Barang/Pekerjaan tersebut telah diterima /diselesaikan dengan lengkap dan baik.<br> Penerima Barang/jasa </td> </tr> <tr> <td colspan="11"> <br> <br> <br> </td> </tr> <tr> <td colspan="11" ><span id="penerima_barang">-</span><br /> NIP. <span id="penerima_barang_nip">-</span> </td> </tr> </table> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-info" id="cetak-kuitansi" rel="" ><span class="glyphicon glyphicon-print" aria-hidden="true"></span> Cetak</button> </div> </div> </div> </div>
swdmnd/rsa
application/views/rsa_tup/spm_tup_verifikator.php
PHP
mit
185,786
/** * @class angular * @method routes */ var routes = module.exports = function() { }; /* EOF */
dianavermilya/todo-app
node_modules/angular/lib/node-angular/routes.js
JavaScript
mit
103
window.abi = require("ethereumjs-abi");
15chrjef/ico-wizard
assets/javascripts/application/main.js
JavaScript
mit
40
namespace TeamBuilder.App.Core { using TeamBuilder.App.Interfaces; using TeamBuilder.Models; public class UserSession : IUserSession { public User User { get; set; } public bool IsLoggedIn => this.User != null; public void LogIn(User user) => this.User = user; public void LogOut() => this.User = null; } }
RAstardzhiev/Software-University-SoftUni
Databases Advanced - Entity Framework Core/Workshop/TeamBuilder.App/Core/UserSession.cs
C#
mit
366
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'UserRole.role' db.alter_column(u'ecg_balancing_userrole', 'role', self.gf('django.db.models.fields.CharField')(max_length=10)) def backwards(self, orm): # Changing field 'UserRole.role' db.alter_column(u'ecg_balancing_userrole', 'role', self.gf('django.db.models.fields.CharField')(max_length=5)) models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'ecg_balancing.company': { 'Meta': {'object_name': 'Company'}, 'activities': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'employees_number': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'foundation_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'industry': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'managing_directors': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'model_creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'owners': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'revenue': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'street': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'website': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'zipcode': ('django.db.models.fields.PositiveIntegerField', [], {}) }, u'ecg_balancing.companybalance': { 'Meta': {'object_name': 'CompanyBalance'}, 'auditor': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'common_good': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'company': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'balance'", 'to': u"orm['ecg_balancing.Company']"}), 'end_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'internal_communication': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'matrix': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'company_balances'", 'to': u"orm['ecg_balancing.ECGMatrix']"}), 'number_participated_employees': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'peer_companies': ('django.db.models.fields.related.ManyToManyField', [], {'max_length': '255', 'to': u"orm['ecg_balancing.Company']", 'null': 'True', 'symmetrical': 'False', 'blank': 'True'}), 'points': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'max_length': '4'}), 'process_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'prospect': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'start_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'worked_hours': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'year': ('django.db.models.fields.SmallIntegerField', [], {'max_length': '4'}) }, u'ecg_balancing.companybalanceindicator': { 'Meta': {'object_name': 'CompanyBalanceIndicator'}, 'company_balance': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'company_balance'", 'to': u"orm['ecg_balancing.CompanyBalance']"}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'evaluation': ('django.db.models.fields.IntegerField', [], {'default': '0'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'company_balance'", 'to': u"orm['ecg_balancing.Indicator']"}) }, u'ecg_balancing.ecgmatrix': { 'Meta': {'object_name': 'ECGMatrix'}, 'contact': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'version': ('django.db.models.fields.CharField', [], {'default': "u'4.1'", 'max_length': '6'}) }, u'ecg_balancing.feedbackindicator': { 'Meta': {'object_name': 'FeedbackIndicator'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'indicator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'feedback'", 'to': u"orm['ecg_balancing.Indicator']"}), 'message': ('django.db.models.fields.TextField', [], {}), 'receiver_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'receiver_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'sender_email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'sender_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'ecg_balancing.indicator': { 'Meta': {'object_name': 'Indicator'}, 'contact': ('ecg_balancing.fields.CommaSeparatedEmailField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'ecg_value': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'editor': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'matrix': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'indicators'", 'to': u"orm['ecg_balancing.ECGMatrix']"}), 'max_evaluation': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'parent_indicator'", 'null': 'True', 'to': u"orm['ecg_balancing.Indicator']"}), 'relevance': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'sole_proprietorship': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'stakeholder': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'subindicator_number': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'ecg_balancing.userprofile': { 'Meta': {'object_name': 'UserProfile'}, 'avatar': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "u'profile'", 'unique': 'True', 'to': u"orm['auth.User']"}) }, u'ecg_balancing.userrole': { 'Meta': {'object_name': 'UserRole'}, 'company': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['ecg_balancing.Company']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'role': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'role'", 'to': u"orm['auth.User']"}) } } complete_apps = ['ecg_balancing']
sinnwerkstatt/ecg-balancing
ecg_balancing/migrations/0030_auto__chg_field_userrole_role.py
Python
mit
12,407
<?php namespace Oro\Bundle\ApiBundle\Collection\QueryVisitorExpression; use Doctrine\Common\Collections\Expr\Comparison; use Oro\Bundle\ApiBundle\Collection\QueryExpressionVisitor; /** * Represents MEMBER OF comparison expression. */ class MemberOfComparisonExpression implements ComparisonExpressionInterface { /** * {@inheritdoc} */ public function walkComparisonExpression( QueryExpressionVisitor $visitor, Comparison $comparison, $fieldName, $parameterName ) { // set parameter $visitor->addParameter($parameterName, $visitor->walkValue($comparison->getValue())); // generate expression return $visitor->getExpressionBuilder() ->isMemberOf($visitor->buildPlaceholder($parameterName), $fieldName); } }
Djamy/platform
src/Oro/Bundle/ApiBundle/Collection/QueryVisitorExpression/MemberOfComparisonExpression.php
PHP
mit
814
namespace Devshed.Csv { using System.Collections.Generic; using System.Globalization; /// <summary> Defines the CSV document layout. </summary> /// <typeparam name="TSource">The type of the source.</typeparam> public class TableDefinition<TSource> { private readonly ICollection<ICsvColumn<TSource>> columns; /// <summary> /// Initializes a new instance of the <see cref="CsvDefinition{TSource}"/> class. /// </summary> /// <param name="columns">The elements.</param> public TableDefinition(params ICsvColumn<TSource>[] columns) { this.columns = columns; } /// <summary> /// Gets the elements. /// </summary> /// <value> /// The elements. /// </value> public ICollection<ICsvColumn<TSource>> Columns { get { return this.columns; } } /// <summary> /// Gets or sets a value indicating whether [first row contains headers]. /// </summary> /// <value> /// <c>true</c> if [first row contains headers]; otherwise, <c>false</c>. /// </value> public bool FirstRowContainsHeaders { get; set; } /// <summary> /// Writes a the Byte Order Marker specifying the encoding. /// </summary> public ElementProcessing ElementProcessing { get; set; } /// <summary> /// Instructs the materializer to ignore readonly properties without throwing an exception. /// </summary> public bool IgnoreReadonlyProperties { get; set; } public bool ThrowExceptionOnError { get; set; } = true; public CultureInfo FormattingCulture { get; set; } = CultureInfo.CurrentCulture; } }
AppiePau/devshed
Devshed.TMapper/TableDefinition.cs
C#
mit
1,780
System.register(['aurelia-framework', 'interact', './interact-base'], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var aurelia_framework_1, Interact, interact_base_1; var InteractDraggableCustomAttribute; return { setters:[ function (aurelia_framework_1_1) { aurelia_framework_1 = aurelia_framework_1_1; }, function (Interact_1) { Interact = Interact_1; }, function (interact_base_1_1) { interact_base_1 = interact_base_1_1; }], execute: function() { InteractDraggableCustomAttribute = (function (_super) { __extends(InteractDraggableCustomAttribute, _super); function InteractDraggableCustomAttribute() { _super.apply(this, arguments); } InteractDraggableCustomAttribute.prototype.bind = function () { var _this = this; this.unsetInteractJs(); this.interactable = this.interact(this.element, this.getInteractableOptions()) .draggable(this.getActionOptions()) .on('dragstart', function (event) { return _this.dispatch('interact-dragstart', event); }) .on('dragmove', function (event) { return _this.dispatch('interact-dragmove', event); }) .on('draginertiastart', function (event) { return _this.dispatch('interact-draginertiastart', event); }) .on('dragend', function (event) { return _this.dispatch('interact-dragend', event); }); }; InteractDraggableCustomAttribute = __decorate([ aurelia_framework_1.inject(Element, Interact), __metadata('design:paramtypes', []) ], InteractDraggableCustomAttribute); return InteractDraggableCustomAttribute; }(interact_base_1.default)); exports_1("InteractDraggableCustomAttribute", InteractDraggableCustomAttribute); } } }); //# sourceMappingURL=interact-draggable.js.map
jfstephe/aurelia-interactjs
dist/system/interact-draggable.js
JavaScript
mit
3,296
// 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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute.Models { using System.Linq; /// <summary> /// The API entity reference. /// </summary> public partial class ApiEntityReference { /// <summary> /// Initializes a new instance of the ApiEntityReference class. /// </summary> public ApiEntityReference() { } /// <summary> /// Initializes a new instance of the ApiEntityReference class. /// </summary> /// <param name="id">the ARM resource id in the form of /// /subscriptions/{SubcriptionId}/resourceGroups/{ResourceGroupName}/...</param> public ApiEntityReference(string id = default(string)) { Id = id; } /// <summary> /// Gets or sets the ARM resource id in the form of /// /subscriptions/{SubcriptionId}/resourceGroups/{ResourceGroupName}/... /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "id")] public string Id { get; set; } } }
ahosnyms/azure-sdk-for-net
src/ResourceManagement/Compute/Microsoft.Azure.Management.Compute/Generated/Models/ApiEntityReference.cs
C#
mit
1,349
/** * Created by Serhei on 17.02.15. * Адаптер между вью HeaderView и модулем Player */ define([ "marionette", "backbone", "jquery", "underscore", "./Player", "./VK", "./Lastfm", "app" ], function (Marionette, Backbone, $, _, Player, VK, Lastfm, App) { var UNKNOWN_ALBUM = '../img/default-album-artwork.png'; var appChannel = Backbone.Wreqr.radio.channel('app'); var playlistChannel = Backbone.Wreqr.radio.channel('playlist'); var playerChannel = Backbone.Wreqr.radio.channel('player'); playlistChannel.vent.on('update:list', function () { if (PlayerAdapter.currentModel) { tellCurrentModel(PlayerAdapter.currentModel); } }); var PlayerAdapter = { currentModel: null, urlsCache: {}, shuffle: false, init: function (opt) { var self = this; playlistChannel.vent.on('play:song', function (data) { self.onPlayEvent(data.obj, data.fromUI); }); playlistChannel.vent.on('play:next', function () { self.onNextEvent(); }); playlistChannel.vent.on('play:prev', function () { self.onPrevEvent(); }); playlistChannel.vent.on('stop', function () { self.onStopEvent(); }); playlistChannel.vent.on('pause', function () { self.onPauseEvent(); }); playlistChannel.vent.on('add:song', function () { self.onAddSongEvent(); }); playlistChannel.vent.on('volume:change', function (vol) { Player.onChangeVolumeEvent(vol); App.UI.attributes.volume = vol.toFixed(2); }); playerChannel.vent.on('shuffle:toggle', function () { self.shuffle = !self.shuffle; playerChannel.vent.trigger('set:shuffle', self.shuffle); App.UI.attributes.shuffle = self.shuffle; }); playerChannel.vent.on('command:play-pause', self.keyboardActions.togglePlay.func); playerChannel.vent.on('command:stop', self.keyboardActions.stop.func); playerChannel.vent.on('command:prev', self.keyboardActions.prev.func); playerChannel.vent.on('command:next', self.keyboardActions.next.func); self.bindButtons(); if (App.UI.get('shuffle')) { playerChannel.vent.trigger('shuffle:toggle'); } Player.init(); Player.currentVolume = opt.volume; }, setBuffer: function (percent) { playerChannel.vent.trigger('set:buffer', percent); }, onError: function (e) { console.error(e); //TODO }, getCallbacks: function () { var self = this; return { progress: { onFinish: function (val, percent) { Player.setProgress(val); console.warn('onFinish', val, percent, this, self); } }, volume: { onChange: function (val, percent) { console.log('onSlide', val); Player.setVolume(percent.toFixed(2)); App.UI.attributes.volume = percent.toFixed(2); } } } }, setCurrentSource: function (obj) { console.log(obj); if (obj && obj.source) { App.isCurrentSongInPlaylist = obj.source == 'playlist'; } }, onPlayEvent: function (obj, fromInterface) { console.log(obj, fromInterface, this, Player); this.setCurrentSource(obj, fromInterface); var self = this; var id = null; if (obj && obj.id) { id = obj.id; if (obj.model) { Player.currentCollection = obj.model.collection; } else if (App.currentPlaylist && App.currentPlaylist.get('collection')) { Player.currentCollection = App.currentPlaylist.get('collection'); } } else if (Player.currentModel && Player.currentModel.id) { id = Player.currentModel.id } else if (Player.currentCollection.length) { id = Player.currentCollection.at(0).get('id'); } else if (App.currentPlaylist && App.currentPlaylist.get('collection')) { Player.currentCollection = App.currentPlaylist.get('collection'); var firstSong = Player.currentCollection.at(0); if (firstSong) { id = firstSong.get('id'); } else { console.warn('NO PLAYLISTS'); return; } } else { console.warn('NO PLAYLISTS'); return; } Player.currentModel = Player.currentCollection.findWhere({id: id}); self.currentModel = Player.currentModel; //console.log('fromInterface', fromInterface, Player , this); if (self.urlsCache[id]) { Player.play(self.urlsCache[id]); tellCurrentModel(Player.currentModel); playerChannel.vent.trigger('set:title', { title: self.urlsCache[id].model.title, artist: self.urlsCache[id].model.artist }); playerChannel.vent.trigger('set:albumart', { id: id, url: self.urlsCache[id].model.img }); } else if (!fromInterface || !Player.currentPlayObj) { VK.audio .getById(id) .then(function (audio) { if (audio && audio.length) { var song = audio[0]; var url = song.url; var obj = { url: url, model: song, id: id, date: Date.now() }; Player.play(obj); self.urlsCache[id] = obj; playerChannel.vent.trigger('set:title', { artist: self.urlsCache[id].model.artist, title: self.urlsCache[id].model.title }); /*get image*/ self.loadImage(id); } }) .finally(function () { tellCurrentModel(Player.currentModel); }); } }, loadImage: function (id) { var self = this; function loadByName() { Lastfm.artist .getImage({ artist: self.urlsCache[id].model.artist }) .then(function (url) { self.urlsCache[id].model.img = self._normalizeAlbumArtUrl(url); playerChannel.vent.trigger('set:albumart', { id: id, url: self.urlsCache[id].model.img }); }) .error(function (e) { throw e; }); } Lastfm.track .getImage({ artist: self.urlsCache[id].model.artist, track: self.urlsCache[id].model.title }) .then(function (url) { if (_.isObject(url) && url.artist) { loadByName(); } else { self.urlsCache[id].model.img = self._normalizeAlbumArtUrl(url); playerChannel.vent.trigger('set:albumart', { id: id, url: self.urlsCache[id].model.img }); } }) .error(function (error) { if (error.message == "Track not found") { loadByName(); } else { throw new Error(error); } }) .catch(function (error) { self.urlsCache[id].model.img = self._normalizeAlbumArtUrl(''); playerChannel.vent.trigger('set:albumart', { id: id, url: self.urlsCache[id].model.img }); }); }, _normalizeAlbumArtUrl: function (url) { if (url == '' || url.indexOf('noimage') > -1) { return UNKNOWN_ALBUM; } else { return url; } }, onStopEvent: function () { Player.stop(); }, onPauseEvent: function () { Player.pause(); }, onNextEvent: function () { if (!Player.currentCollection || !Player.currentModel) { this.onPlayEvent(); } else { //findWhere а не get, того что есть id вида "-270708_85642422" - значит песня принадлежит группе var modelCurrent = Player.currentCollection.findWhere({id: Player.currentModelId}); if (modelCurrent) { var model = modelCurrent.getNextSong(this.shuffle); this.onPlayEvent({ id: model.get('id'), model: model }); } else { this.onPlayEvent(); } } }, onPrevEvent: function () { if (!Player.currentCollection || !Player.currentModel) { this.onPlayEvent(); } else { var modelCurrent = Player.currentCollection.findWhere({id: Player.currentModelId}); if (modelCurrent) { var model = modelCurrent.getPrevSong(this.shuffle); this.onPlayEvent({ id: model.get('id'), model: model }); } else { this.onPlayEvent(); } } }, onAddSongEvent : function(){ if(!App.isCurrentSongInPlaylist && this.currentModel){ playlistChannel.vent.trigger('add:song-model', this.currentModel); } }, bindButtons: function () { var self = this; function GetDescriptionFor(e) { var special = { 32: "space", 37: "left", 38: "up", 39: "right", 40: "down" }; var keyIdentifiers = ["MediaNextTrack", "MediaPlayPause", "MediaStop", "MediaPrevTrack"]; var result = [], code, kCode; //debugger if (e.keyIdentifier && keyIdentifiers.indexOf(e.keyIdentifier) >= 0) { kCode = e.keyIdentifier; } else if ((e.charCode) && (e.keyCode == 0)) { kCode = e.charCode; code = e.charCode; } else { kCode = e.keyCode; code = e.keyCode; } if (special[kCode]) { kCode = special[kCode]; result.push(kCode); } if (keyIdentifiers.indexOf(kCode) >= 0) { result.push(kCode); } if (code == 8) result.push("bksp") else if (code == 9) result.push("tab") else if (code == 46) result.push("del") else if ((code >= 41) && (code <= 126)) result.push(String.fromCharCode(code).toLocaleLowerCase()); if (e.altKey) result.unshift("alt"); if (e.ctrlKey) result.unshift("ctrl"); if (e.shiftKey) result.unshift("shift"); return result; } function handler(e) { if (e.srcElement && e.srcElement.contentEditable == 'true') { return; } if (e.srcElement && e.srcElement.tagName.toLowerCase() == 'input') { return; } console.log(e); if (!e) e = window.event; var descr = GetDescriptionFor(e); var combination = descr.join('+'); _.each(self.keyboardActions, function (action, actionName) { if (action.keys.indexOf(combination) >= 0) { action.func(); } }); return false; } document.addEventListener('keydown', handler, false); }, keyboardActions: { togglePlay: { keys: ['space', 'p', 'c', 'з', 'с', 'MediaPlayPause'], func: function () { if (Player.isPlying) { playlistChannel.vent.trigger('pause'); } else { playlistChannel.vent.trigger('play:song', { obj: null, fromUI: true }); } } }, next: { keys: ['right', 'b', '6', 'и', 'MediaNextTrack'], func: function () { playlistChannel.vent.trigger('play:next'); } }, prev: { keys: ['left', 'z', '4', 'я', 'MediaPrevTrack'], func: function () { playlistChannel.vent.trigger('play:prev'); } }, stop: { keys: ['v', 'м', 'MediaStop'], func: function () { playlistChannel.vent.trigger('stop'); } }, volumeUp: { keys: ['up', '8'], func: function () { var vol = Player.currentVolume + 0.05; playlistChannel.vent.trigger('volume:change', vol); playerChannel.vent.trigger('set:volume', vol); } }, volumeDown: { keys: ['down', '2'], func: function () { var vol = Player.currentVolume - 0.05; playlistChannel.vent.trigger('volume:change', vol); playerChannel.vent.trigger('set:volume', vol); } }, toggleShuffle: { keys: ['s', 'ы', 'і'], func: function () { playerChannel.vent.trigger('shuffle:toggle'); } }, addToPlaylist: { keys: ['a', 'ф'], func: function () { playlistChannel.vent.trigger('add:song'); } } } }; function tellCurrentModel(currentModel) { if(currentModel && currentModel.id){ playlistChannel.vent.trigger('current', currentModel.id); } } return PlayerAdapter; });
Stryzhevskyi/vk-player
src/js/modules/PlayerAdapter.js
JavaScript
mit
17,397
package com.jasperlu.doppler; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Handler; import android.provider.MediaStore; import android.renderscript.Sampler; import android.util.Log; /** * Created by Jasper on 3/12/2015. */ public class FrequencyPlayer { private AudioTrack audioTrack; private final int duration = 5000; // milliseconds private final int sampleRate = 44100; private int numSamples; private double sample[] = new double[numSamples]; private double freqOfTone = 10000; // hz private byte generatedSound[] = new byte[2 * numSamples]; private static int MILLIS_PER_SECOND = 1000; Handler handler = new Handler(); FrequencyPlayer(double frequency) { numSamples = sampleRate * duration / MILLIS_PER_SECOND; generatedSound = new byte[2 * numSamples]; sample = new double[numSamples]; audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, generatedSound.length, AudioTrack.MODE_STATIC); setFrequency(frequency); } //sets to new frequency and continues playing public void changeFrequency(double frequency) { setFrequency(frequency); play(); } //sets frequency and stops sound public void setFrequency(double frequency) { freqOfTone = frequency; genTone(); Log.d("FreqPlayer", "" +audioTrack.write(generatedSound, 0, generatedSound.length)); audioTrack.setLoopPoints(0, generatedSound.length / 4, -1); } public void play() { //16 bit because it's supported by all phones audioTrack.play(); } public void pause() { audioTrack.pause(); } void genTone(){ // fill out the array for (int i = 0; i < numSamples; ++i) { sample[i] = Math.sin(2 * Math.PI * i / (sampleRate/freqOfTone)); } // convert to 16 bit pcm sound array // assumes the sample buffer is normalised. int idx = 0; for (final double dVal : sample) { // scale to maximum amplitude final short val = (short) ((dVal * 32767)); // in 16 bit wav PCM, first byte is the low order byte generatedSound[idx++] = (byte) (val & 0x00ff); generatedSound[idx++] = (byte) ((val & 0xff00) >>> 8); } } }
jasper-lu/doppler-android
src/main/java/com/jasperlu/doppler/FrequencyPlayer.java
Java
mit
2,478
#include "Lab5.h" #include "Content.h" #include "VectorDrawer.h" #include "LazerBeam.h" #include "FountainEffect.h" using namespace BGE; Lab5::Lab5(void) { elapsed = 10000; } Lab5::~Lab5(void) { } bool Lab5::Initialise() { std::shared_ptr<GameComponent> ground = make_shared<Ground>(); Attach(ground); ship1 = make_shared<GameComponent>(); ship1->Attach(Content::LoadModel("cobramk3", glm::rotate(glm::mat4(1), 180.0f, glm::vec3(0,1,0)))); ship1->position = glm::vec3(-10, 2, -10); ship1->Attach(make_shared<VectorDrawer>()); Attach(ship1); //ship2->drawMode = GameComponent::single_material; riftEnabled = false; fullscreen = false; width = 800; height = 600; // 500 in the constructor indicates the number of particles in the effect. // You may need to compile in release mode or reduce the number of particles to get an acceptable framerate // make a circle of fountains fountainTheta = 0.0f; for (int i = 0 ; i < NUM_FOUNTAINS ; i ++) { fountainTheta = ((glm::pi<float>() * 2.0f) / NUM_FOUNTAINS) * i; shared_ptr<FountainEffect> fountain = make_shared<FountainEffect>(500); if (i % 2 == 0) { fountain->diffuse = glm::vec3(1,0,0); } else { fountain->diffuse = glm::vec3(0,1,0); } fountain->position.x = glm::sin(fountainTheta) * FOUNTAIN_RADIUS; fountain->position.z = - glm::cos(fountainTheta) * FOUNTAIN_RADIUS; fountain->position.y = FOUNTAIN_HEIGHT; fountains.push_back(fountain); Attach(fountain); } fountainTheta = 0.0f; ship2 = make_shared<GameComponent>(); ship2->Attach(Content::LoadModel("ferdelance", glm::rotate(glm::mat4(1), 180.0f, glm::vec3(0,1,0)))); ship2->Attach(make_shared<VectorDrawer>()); ship2->diffuse= glm::vec3(1.0f,0.0f,0.0f); ship2->specular = glm::vec3(1.2f, 1.2f, 1.2f); ship2->position = glm::vec3(10, 2, -10); Attach(ship2); Game::Initialise(); camera->GetController()->position = glm::vec3(0, 4, 20); return true; } void Lab5::Update(float timeDelta) { // Movement of ship2 if (keyState[SDL_SCANCODE_UP]) { ship2->position += ship2->look * speed * timeDelta; } if (keyState[SDL_SCANCODE_DOWN]) { ship2->position -= ship2->look * speed * timeDelta; } if (keyState[SDL_SCANCODE_LEFT]) { ship2->Yaw(timeDelta * speed * speed); } if (keyState[SDL_SCANCODE_RIGHT]) { ship2->Yaw(-timeDelta * speed * speed); } for (int i = 0 ; i < fountains.size() ; i ++) { if (i % 2 == 0) { fountains[i]->position.y = FOUNTAIN_HEIGHT + (glm::sin(fountainTheta) * FOUNTAIN_HEIGHT); } else { fountains[i]->position.y = FOUNTAIN_HEIGHT - (glm::sin(fountainTheta) * FOUNTAIN_HEIGHT); } } fountainTheta += timeDelta; if (fountainTheta >= glm::pi<float>() * 2.0f) { fountainTheta = 0.0f; } Game::Update(timeDelta); float theta = 0.0f; glm::vec3 toShip2 = ship2->position - ship1->position; toShip2 = glm::normalize(toShip2); theta = glm::acos(glm::dot(GameComponent::basisLook, toShip2)); //if (toShip2.x > 0) //{ // theta = - theta; //} ship1->world = glm::translate(glm::mat4(1), ship1->position) * glm::rotate(glm::mat4(1), glm::degrees(theta), glm::vec3(0,1,0)); }
PaulKennedyDIT/GamesEnginesAssignment1
BGE/Lab5.cpp
C++
mit
3,138
import * as React from "react"; import { CarbonIconProps } from "../../"; declare const Worship24: React.ForwardRefExoticComponent< CarbonIconProps & React.RefAttributes<SVGSVGElement> >; export default Worship24;
mcliment/DefinitelyTyped
types/carbon__icons-react/lib/worship/24.d.ts
TypeScript
mit
216
var fs = require('fs'); function readCache(bank, url) { fs.readFile(url, 'utf8', function (err, data) { if (!err) { bank.dispatch(JSON.parse(data)); } }); } function writeCache(url, data) { fs.writeFile(url, JSON.stringify(data), function (err) { if (err) return console.log(err); }); } module.exports = function(bank, url) { readCache(bank, url); bank.subscribe(function(d, o, t) { var sum = []; for (var row in bank._store) { sum.push({ type: row, data: bank._store[row].data, options: bank._store[row].options }); } writeCache(url, sum); }); };
krambuhl/ganglion
licklider/bank/bank.cache.js
JavaScript
mit
636
version https://git-lfs.github.com/spec/v1 oid sha256:1eb76caa2619ae14fc6e83b2bc11a3d5af53859002ec58d29ff4f159b115b8c7 size 8342
yogeshsaroya/new-cdnjs
ajax/libs/piwik/0.4.3/piwik.js
JavaScript
mit
129
/*! * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015 * @version 1.3.3 * * Date formatter utility library that allows formatting date/time variables or Date objects using PHP DateTime format. * @see http://php.net/manual/en/function.date.php * * For more JQuery plugins visit http://plugins.krajee.com * For more Yii related demos visit http://demos.krajee.com */ var DateFormatter; (function () { "use strict"; var _compare, _lpad, _extend, defaultSettings, DAY, HOUR; DAY = 1000 * 60 * 60 * 24; HOUR = 3600; _compare = function (str1, str2) { return typeof(str1) === 'string' && typeof(str2) === 'string' && str1.toLowerCase() === str2.toLowerCase(); }; _lpad = function (value, length, char) { var chr = char || '0', val = value.toString(); return val.length < length ? _lpad(chr + val, length) : val; }; _extend = function (out) { var i, obj; out = out || {}; for (i = 1; i < arguments.length; i++) { obj = arguments[i]; if (!obj) { continue; } for (var key in obj) { if (obj.hasOwnProperty(key)) { if (typeof obj[key] === 'object') { _extend(out[key], obj[key]); } else { out[key] = obj[key]; } } } } return out; }; defaultSettings = { dateSettings: { days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], months: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], meridiem: ['AM', 'PM'], ordinal: function (number) { var n = number % 10, suffixes = {1: 'st', 2: 'nd', 3: 'rd'}; return Math.floor(number % 100 / 10) === 1 || !suffixes[n] ? 'th' : suffixes[n]; } }, separators: /[ \-+\/\.T:@]/g, validParts: /[dDjlNSwzWFmMntLoYyaABgGhHisueTIOPZcrU]/g, intParts: /[djwNzmnyYhHgGis]/g, tzParts: /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, tzClip: /[^-+\dA-Z]/g }; DateFormatter = function (options) { var self = this, config = _extend(defaultSettings, options); self.dateSettings = config.dateSettings; self.separators = config.separators; self.validParts = config.validParts; self.intParts = config.intParts; self.tzParts = config.tzParts; self.tzClip = config.tzClip; }; DateFormatter.prototype = { constructor: DateFormatter, parseDate: function (vDate, vFormat) { var self = this, vFormatParts, vDateParts, i, vDateFlag = false, vTimeFlag = false, vDatePart, iDatePart, vSettings = self.dateSettings, vMonth, vMeriIndex, vMeriOffset, len, mer, out = {date: null, year: null, month: null, day: null, hour: 0, min: 0, sec: 0}; if (!vDate) { return undefined; } if (vDate instanceof Date) { return vDate; } if (typeof vDate === 'number') { return new Date(vDate); } if (vFormat === 'U') { i = parseInt(vDate); return i ? new Date(i * 1000) : vDate; } if (typeof vDate !== 'string') { return ''; } vFormatParts = vFormat.match(self.validParts); if (!vFormatParts || vFormatParts.length === 0) { throw new Error("Invalid date format definition."); } vDateParts = vDate.replace(self.separators, '\0').split('\0'); for (i = 0; i < vDateParts.length; i++) { vDatePart = vDateParts[i]; iDatePart = parseInt(vDatePart); switch (vFormatParts[i]) { case 'y': case 'Y': len = vDatePart.length; if (len === 2) { out.year = parseInt((iDatePart < 70 ? '20' : '19') + vDatePart); } else if (len === 4) { out.year = iDatePart; } vDateFlag = true; break; case 'm': case 'n': case 'M': case 'F': if (isNaN(vDatePart)) { vMonth = vSettings.monthsShort.indexOf(vDatePart); if (vMonth > -1) { out.month = vMonth + 1; } vMonth = vSettings.months.indexOf(vDatePart); if (vMonth > -1) { out.month = vMonth + 1; } } else { if (iDatePart >= 1 && iDatePart <= 12) { out.month = iDatePart; } } vDateFlag = true; break; case 'd': case 'j': if (iDatePart >= 1 && iDatePart <= 31) { out.day = iDatePart; } vDateFlag = true; break; case 'g': case 'h': vMeriIndex = (vFormatParts.indexOf('a') > -1) ? vFormatParts.indexOf('a') : (vFormatParts.indexOf('A') > -1) ? vFormatParts.indexOf('A') : -1; mer = vDateParts[vMeriIndex]; if (vMeriIndex > -1) { vMeriOffset = _compare(mer, vSettings.meridiem[0]) ? 0 : (_compare(mer, vSettings.meridiem[1]) ? 12 : -1); if (iDatePart >= 1 && iDatePart <= 12 && vMeriOffset > -1) { out.hour = iDatePart + vMeriOffset; } else if (iDatePart >= 0 && iDatePart <= 23) { out.hour = iDatePart; } } else if (iDatePart >= 0 && iDatePart <= 23) { out.hour = iDatePart; } vTimeFlag = true; break; case 'G': case 'H': if (iDatePart >= 0 && iDatePart <= 23) { out.hour = iDatePart; } vTimeFlag = true; break; case 'i': if (iDatePart >= 0 && iDatePart <= 59) { out.min = iDatePart; } vTimeFlag = true; break; case 's': if (iDatePart >= 0 && iDatePart <= 59) { out.sec = iDatePart; } vTimeFlag = true; break; } } if (vDateFlag === true && out.year && out.month && out.day) { out.date = new Date(out.year, out.month - 1, out.day, out.hour, out.min, out.sec, 0); } else { if (vTimeFlag !== true) { return false; } out.date = new Date(0, 0, 0, out.hour, out.min, out.sec, 0); } return out.date; }, guessDate: function (vDateStr, vFormat) { if (typeof vDateStr !== 'string') { return vDateStr; } var self = this, vParts = vDateStr.replace(self.separators, '\0').split('\0'), vPattern = /^[djmn]/g, vFormatParts = vFormat.match(self.validParts), vDate = new Date(), vDigit = 0, vYear, i, iPart, iSec; if (!vPattern.test(vFormatParts[0])) { return vDateStr; } for (i = 0; i < vParts.length; i++) { vDigit = 2; iPart = vParts[i]; iSec = parseInt(iPart.substr(0, 2)); switch (i) { case 0: if (vFormatParts[0] === 'm' || vFormatParts[0] === 'n') { vDate.setMonth(iSec - 1); } else { vDate.setDate(iSec); } break; case 1: if (vFormatParts[0] === 'm' || vFormatParts[0] === 'n') { vDate.setDate(iSec); } else { vDate.setMonth(iSec - 1); } break; case 2: vYear = vDate.getFullYear(); if (iPart.length < 4) { vDate.setFullYear(parseInt(vYear.toString().substr(0, 4 - iPart.length) + iPart)); vDigit = iPart.length; } else { vDate.setFullYear = parseInt(iPart.substr(0, 4)); vDigit = 4; } break; case 3: vDate.setHours(iSec); break; case 4: vDate.setMinutes(iSec); break; case 5: vDate.setSeconds(iSec); break; } if (iPart.substr(vDigit).length > 0) { vParts.splice(i + 1, 0, iPart.substr(vDigit)); } } return vDate; }, parseFormat: function (vChar, vDate) { var self = this, vSettings = self.dateSettings, fmt, backspace = /\\?(.?)/gi, doFormat = function (t, s) { return fmt[t] ? fmt[t]() : s; }; fmt = { ///////// // DAY // ///////// /** * Day of month with leading 0: `01..31` * @return {string} */ d: function () { return _lpad(fmt.j(), 2); }, /** * Shorthand day name: `Mon...Sun` * @return {string} */ D: function () { return vSettings.daysShort[fmt.w()]; }, /** * Day of month: `1..31` * @return {number} */ j: function () { return vDate.getDate(); }, /** * Full day name: `Monday...Sunday` * @return {number} */ l: function () { return vSettings.days[fmt.w()]; }, /** * ISO-8601 day of week: `1[Mon]..7[Sun]` * @return {number} */ N: function () { return fmt.w() || 7; }, /** * Day of week: `0[Sun]..6[Sat]` * @return {number} */ w: function () { return vDate.getDay(); }, /** * Day of year: `0..365` * @return {number} */ z: function () { var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j()), b = new Date(fmt.Y(), 0, 1); return Math.round((a - b) / DAY); }, ////////// // WEEK // ////////// /** * ISO-8601 week number * @return {number} */ W: function () { var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j() - fmt.N() + 3), b = new Date(a.getFullYear(), 0, 4); return _lpad(1 + Math.round((a - b) / DAY / 7), 2); }, /////////// // MONTH // /////////// /** * Full month name: `January...December` * @return {string} */ F: function () { return vSettings.months[vDate.getMonth()]; }, /** * Month w/leading 0: `01..12` * @return {string} */ m: function () { return _lpad(fmt.n(), 2); }, /** * Shorthand month name; `Jan...Dec` * @return {string} */ M: function () { return vSettings.monthsShort[vDate.getMonth()]; }, /** * Month: `1...12` * @return {number} */ n: function () { return vDate.getMonth() + 1; }, /** * Days in month: `28...31` * @return {number} */ t: function () { return (new Date(fmt.Y(), fmt.n(), 0)).getDate(); }, ////////// // YEAR // ////////// /** * Is leap year? `0 or 1` * @return {number} */ L: function () { var Y = fmt.Y(); return (Y % 4 === 0 && Y % 100 !== 0 || Y % 400 === 0) ? 1 : 0; }, /** * ISO-8601 year * @return {number} */ o: function () { var n = fmt.n(), W = fmt.W(), Y = fmt.Y(); return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0); }, /** * Full year: `e.g. 1980...2010` * @return {number} */ Y: function () { return vDate.getFullYear(); }, /** * Last two digits of year: `00...99` * @return {string} */ y: function () { return fmt.Y().toString().slice(-2); }, ////////// // TIME // ////////// /** * Meridian lower: `am or pm` * @return {string} */ a: function () { return fmt.A().toLowerCase(); }, /** * Meridian upper: `AM or PM` * @return {string} */ A: function () { var n = fmt.G() < 12 ? 0 : 1; return vSettings.meridiem[n]; }, /** * Swatch Internet time: `000..999` * @return {string} */ B: function () { var H = vDate.getUTCHours() * HOUR, i = vDate.getUTCMinutes() * 60, s = vDate.getUTCSeconds(); return _lpad(Math.floor((H + i + s + HOUR) / 86.4) % 1000, 3); }, /** * 12-Hours: `1..12` * @return {number} */ g: function () { return fmt.G() % 12 || 12; }, /** * 24-Hours: `0..23` * @return {number} */ G: function () { return vDate.getHours(); }, /** * 12-Hours with leading 0: `01..12` * @return {string} */ h: function () { return _lpad(fmt.g(), 2); }, /** * 24-Hours w/leading 0: `00..23` * @return {string} */ H: function () { return _lpad(fmt.G(), 2); }, /** * Minutes w/leading 0: `00..59` * @return {string} */ i: function () { return _lpad(vDate.getMinutes(), 2); }, /** * Seconds w/leading 0: `00..59` * @return {string} */ s: function () { return _lpad(vDate.getSeconds(), 2); }, /** * Microseconds: `000000-999000` * @return {string} */ u: function () { return _lpad(vDate.getMilliseconds() * 1000, 6); }, ////////////// // TIMEZONE // ////////////// /** * Timezone identifier: `e.g. Atlantic/Azores, ...` * @return {string} */ e: function () { var str = /\((.*)\)/.exec(String(vDate))[1]; return str || 'Coordinated Universal Time'; }, /** * Timezone abbreviation: `e.g. EST, MDT, ...` * @return {string} */ T: function () { var str = (String(vDate).match(self.tzParts) || [""]).pop().replace(self.tzClip, ""); return str || 'UTC'; }, /** * DST observed? `0 or 1` * @return {number} */ I: function () { var a = new Date(fmt.Y(), 0), c = Date.UTC(fmt.Y(), 0), b = new Date(fmt.Y(), 6), d = Date.UTC(fmt.Y(), 6); return ((a - c) !== (b - d)) ? 1 : 0; }, /** * Difference to GMT in hour format: `e.g. +0200` * @return {string} */ O: function () { var tzo = vDate.getTimezoneOffset(), a = Math.abs(tzo); return (tzo > 0 ? '-' : '+') + _lpad(Math.floor(a / 60) * 100 + a % 60, 4); }, /** * Difference to GMT with colon: `e.g. +02:00` * @return {string} */ P: function () { var O = fmt.O(); return (O.substr(0, 3) + ':' + O.substr(3, 2)); }, /** * Timezone offset in seconds: `-43200...50400` * @return {number} */ Z: function () { return -vDate.getTimezoneOffset() * 60; }, //////////////////// // FULL DATE TIME // //////////////////// /** * ISO-8601 date * @return {string} */ c: function () { return 'Y-m-d\\TH:i:sP'.replace(backspace, doFormat); }, /** * RFC 2822 date * @return {string} */ r: function () { return 'D, d M Y H:i:s O'.replace(backspace, doFormat); }, /** * Seconds since UNIX epoch * @return {number} */ U: function () { return vDate.getTime() / 1000 || 0; } }; return doFormat(vChar, vChar); }, formatDate: function (vDate, vFormat) { var self = this, i, n, len, str, vChar, vDateStr = ''; if (typeof vDate === 'string') { vDate = self.parseDate(vDate, vFormat); if (vDate === false) { return false; } } if (vDate instanceof Date) { len = vFormat.length; for (i = 0; i < len; i++) { vChar = vFormat.charAt(i); if (vChar === 'S') { continue; } str = self.parseFormat(vChar, vDate); if (i !== (len - 1) && self.intParts.test(vChar) && vFormat.charAt(i + 1) === 'S') { n = parseInt(str); str += self.dateSettings.ordinal(n); } vDateStr += str; } return vDateStr; } return ''; } }; })();/** * @preserve jQuery DateTimePicker plugin v2.5.4 * @homepage http://xdsoft.net/jqplugins/datetimepicker/ * @author Chupurnov Valeriy (<chupurnov@gmail.com>) */ /*global DateFormatter, document,window,jQuery,setTimeout,clearTimeout,HighlightedDate,getCurrentValue*/ ;(function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define(['jquery', 'jquery-mousewheel'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }(function ($) { 'use strict'; var currentlyScrollingTimeDiv = false; var default_options = { i18n: { ar: { // Arabic months: [ "كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول" ], dayOfWeekShort: [ "ن", "ث", "ع", "خ", "ج", "س", "ح" ], dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"] }, ro: { // Romanian months: [ "Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie" ], dayOfWeekShort: [ "Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ" ], dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"] }, id: { // Indonesian months: [ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember" ], dayOfWeekShort: [ "Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab" ], dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] }, is: { // Icelandic months: [ "Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember" ], dayOfWeekShort: [ "Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau" ], dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"] }, bg: { // Bulgarian months: [ "Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември" ], dayOfWeekShort: [ "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб" ], dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"] }, fa: { // Persian/Farsi months: [ 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند' ], dayOfWeekShort: [ 'یکشنبه', 'دوشنبه', 'سه شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه', 'شنبه' ], dayOfWeek: ["یک‌شنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنج‌شنبه", "جمعه", "شنبه", "یک‌شنبه"] }, ru: { // Russian months: [ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' ], dayOfWeekShort: [ "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб" ], dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"] }, uk: { // Ukrainian months: [ 'Січень', 'Лютий', 'Березень', 'Квітень', 'Травень', 'Червень', 'Липень', 'Серпень', 'Вересень', 'Жовтень', 'Листопад', 'Грудень' ], dayOfWeekShort: [ "Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт" ], dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"] }, en: { // English months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], dayOfWeekShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] }, el: { // Ελληνικά months: [ "Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος" ], dayOfWeekShort: [ "Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ" ], dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"] }, de: { // German months: [ 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember' ], dayOfWeekShort: [ "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa" ], dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"] }, nl: { // Dutch months: [ "januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december" ], dayOfWeekShort: [ "zo", "ma", "di", "wo", "do", "vr", "za" ], dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"] }, tr: { // Turkish months: [ "Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık" ], dayOfWeekShort: [ "Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts" ], dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"] }, fr: { //French months: [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre" ], dayOfWeekShort: [ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam" ], dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"] }, es: { // Spanish months: [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" ], dayOfWeekShort: [ "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb" ], dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"] }, th: { // Thai months: [ 'มกราคม', 'กุมภาพันธ์', 'มีนาคม', 'เมษายน', 'พฤษภาคม', 'มิถุนายน', 'กรกฎาคม', 'สิงหาคม', 'กันยายน', 'ตุลาคม', 'พฤศจิกายน', 'ธันวาคม' ], dayOfWeekShort: [ 'อา.', 'จ.', 'อ.', 'พ.', 'พฤ.', 'ศ.', 'ส.' ], dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"] }, pl: { // Polish months: [ "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień" ], dayOfWeekShort: [ "nd", "pn", "wt", "śr", "cz", "pt", "sb" ], dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"] }, pt: { // Portuguese months: [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ], dayOfWeekShort: [ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab" ], dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"] }, ch: { // Simplified Chinese months: [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ], dayOfWeekShort: [ "日", "一", "二", "三", "四", "五", "六" ] }, se: { // Swedish months: [ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December" ], dayOfWeekShort: [ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör" ] }, kr: { // Korean months: [ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월" ], dayOfWeekShort: [ "일", "월", "화", "수", "목", "금", "토" ], dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"] }, it: { // Italian months: [ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre" ], dayOfWeekShort: [ "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab" ], dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"] }, da: { // Dansk months: [ "January", "Februar", "Marts", "April", "Maj", "Juni", "July", "August", "September", "Oktober", "November", "December" ], dayOfWeekShort: [ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør" ], dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"] }, no: { // Norwegian months: [ "Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember" ], dayOfWeekShort: [ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør" ], dayOfWeek: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'] }, ja: { // Japanese months: [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ], dayOfWeekShort: [ "日", "月", "火", "水", "木", "金", "土" ], dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"] }, vi: { // Vietnamese months: [ "Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12" ], dayOfWeekShort: [ "CN", "T2", "T3", "T4", "T5", "T6", "T7" ], dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"] }, sl: { // Slovenščina months: [ "Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December" ], dayOfWeekShort: [ "Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob" ], dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"] }, cs: { // Čeština months: [ "Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec" ], dayOfWeekShort: [ "Ne", "Po", "Út", "St", "Čt", "Pá", "So" ] }, hu: { // Hungarian months: [ "Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December" ], dayOfWeekShort: [ "Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo" ], dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"] }, az: { //Azerbaijanian (Azeri) months: [ "Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr" ], dayOfWeekShort: [ "B", "Be", "Ça", "Ç", "Ca", "C", "Ş" ], dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"] }, bs: { //Bosanski months: [ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar" ], dayOfWeekShort: [ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub" ], dayOfWeek: ["Nedjelja","Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"] }, ca: { //Català months: [ "Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre" ], dayOfWeekShort: [ "Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds" ], dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"] }, 'en-GB': { //English (British) months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], dayOfWeekShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] }, et: { //"Eesti" months: [ "Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember" ], dayOfWeekShort: [ "P", "E", "T", "K", "N", "R", "L" ], dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"] }, eu: { //Euskara months: [ "Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua" ], dayOfWeekShort: [ "Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La." ], dayOfWeek: ['Igandea', 'Astelehena', 'Asteartea', 'Asteazkena', 'Osteguna', 'Ostirala', 'Larunbata'] }, fi: { //Finnish (Suomi) months: [ "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu" ], dayOfWeekShort: [ "Su", "Ma", "Ti", "Ke", "To", "Pe", "La" ], dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"] }, gl: { //Galego months: [ "Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec" ], dayOfWeekShort: [ "Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab" ], dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"] }, hr: { //Hrvatski months: [ "Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac" ], dayOfWeekShort: [ "Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub" ], dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"] }, ko: { //Korean (한국어) months: [ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월" ], dayOfWeekShort: [ "일", "월", "화", "수", "목", "금", "토" ], dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"] }, lt: { //Lithuanian (lietuvių) months: [ "Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio" ], dayOfWeekShort: [ "Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš" ], dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"] }, lv: { //Latvian (Latviešu) months: [ "Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris" ], dayOfWeekShort: [ "Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St" ], dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"] }, mk: { //Macedonian (Македонски) months: [ "јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември" ], dayOfWeekShort: [ "нед", "пон", "вто", "сре", "чет", "пет", "саб" ], dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"] }, mn: { //Mongolian (Монгол) months: [ "1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар" ], dayOfWeekShort: [ "Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням" ], dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"] }, 'pt-BR': { //Português(Brasil) months: [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" ], dayOfWeekShort: [ "Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb" ], dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"] }, sk: { //Slovenčina months: [ "Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December" ], dayOfWeekShort: [ "Ne", "Po", "Ut", "St", "Št", "Pi", "So" ], dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"] }, sq: { //Albanian (Shqip) months: [ "Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor" ], dayOfWeekShort: [ "Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu" ], dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"] }, 'sr-YU': { //Serbian (Srpski) months: [ "Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar" ], dayOfWeekShort: [ "Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub" ], dayOfWeek: ["Nedelja","Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"] }, sr: { //Serbian Cyrillic (Српски) months: [ "јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар" ], dayOfWeekShort: [ "нед", "пон", "уто", "сре", "чет", "пет", "суб" ], dayOfWeek: ["Недеља","Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"] }, sv: { //Svenska months: [ "Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December" ], dayOfWeekShort: [ "Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör" ], dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"] }, 'zh-TW': { //Traditional Chinese (繁體中文) months: [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ], dayOfWeekShort: [ "日", "一", "二", "三", "四", "五", "六" ], dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] }, zh: { //Simplified Chinese (简体中文) months: [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" ], dayOfWeekShort: [ "日", "一", "二", "三", "四", "五", "六" ], dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] }, he: { //Hebrew (עברית) months: [ 'ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר' ], dayOfWeekShort: [ 'א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת' ], dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"] }, hy: { // Armenian months: [ "Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր" ], dayOfWeekShort: [ "Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ" ], dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"] }, kg: { // Kyrgyz months: [ 'Үчтүн айы', 'Бирдин айы', 'Жалган Куран', 'Чын Куран', 'Бугу', 'Кулжа', 'Теке', 'Баш Оона', 'Аяк Оона', 'Тогуздун айы', 'Жетинин айы', 'Бештин айы' ], dayOfWeekShort: [ "Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише" ], dayOfWeek: [ "Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб" ] }, rm: { // Romansh months: [ "Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December" ], dayOfWeekShort: [ "Du", "Gli", "Ma", "Me", "Gie", "Ve", "So" ], dayOfWeek: [ "Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda" ] }, ka: { // Georgian months: [ 'იანვარი', 'თებერვალი', 'მარტი', 'აპრილი', 'მაისი', 'ივნისი', 'ივლისი', 'აგვისტო', 'სექტემბერი', 'ოქტომბერი', 'ნოემბერი', 'დეკემბერი' ], dayOfWeekShort: [ "კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ" ], dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"] }, }, value: '', rtl: false, format: 'Y/m/d H:i', formatTime: 'H:i', formatDate: 'Y/m/d', startDate: false, // new Date(), '1986/12/08', '-1970/01/05','-1970/01/05', step: 60, monthChangeSpinner: true, closeOnDateSelect: false, closeOnTimeSelect: true, closeOnWithoutClick: true, closeOnInputClick: true, timepicker: true, datepicker: true, weeks: false, defaultTime: false, // use formatTime format (ex. '10:00' for formatTime: 'H:i') defaultDate: false, // use formatDate format (ex new Date() or '1986/12/08' or '-1970/01/05' or '-1970/01/05') minDate: false, maxDate: false, minTime: false, maxTime: false, disabledMinTime: false, disabledMaxTime: false, allowTimes: [], opened: false, initTime: true, inline: false, theme: '', onSelectDate: function () {}, onSelectTime: function () {}, onChangeMonth: function () {}, onGetWeekOfYear: function () {}, onChangeYear: function () {}, onChangeDateTime: function () {}, onShow: function () {}, onClose: function () {}, onGenerate: function () {}, withoutCopyright: true, inverseButton: false, hours12: false, next: 'xdsoft_next', prev : 'xdsoft_prev', dayOfWeekStart: 0, parentID: 'body', timeHeightInTimePicker: 25, timepickerScrollbar: true, todayButton: true, prevButton: true, nextButton: true, defaultSelect: true, scrollMonth: true, scrollTime: true, scrollInput: true, lazyInit: false, mask: false, validateOnBlur: true, allowBlank: true, yearStart: 1950, yearEnd: 2050, monthStart: 0, monthEnd: 11, style: '', id: '', fixed: false, roundTime: 'round', // ceil, floor className: '', weekends: [], highlightedDates: [], highlightedPeriods: [], allowDates : [], allowDateRe : null, disabledDates : [], disabledWeekDays: [], yearOffset: 0, beforeShowDay: null, enterLikeTab: true, showApplyButton: false }; var dateHelper = null, globalLocaleDefault = 'ru', globalLocale = 'ru'; var dateFormatterOptionsDefault = { meridiem: ['AM', 'PM'] }; var initDateFormatter = function(){ var locale = default_options.i18n[globalLocale], opts = { days: locale.dayOfWeek, daysShort: locale.dayOfWeekShort, months: locale.months, monthsShort: $.map(locale.months, function(n){ return n.substring(0, 3) }), }; dateHelper = new DateFormatter({ dateSettings: $.extend({}, dateFormatterOptionsDefault, opts) }); }; // for locale settings $.datetimepicker = { setLocale: function(locale){ var newLocale = default_options.i18n[locale]?locale:globalLocaleDefault; if(globalLocale != newLocale){ globalLocale = newLocale; // reinit date formatter initDateFormatter(); } }, setDateFormatter: function(dateFormatter) { dateHelper = dateFormatter; }, RFC_2822: 'D, d M Y H:i:s O', ATOM: 'Y-m-d\TH:i:sP', ISO_8601: 'Y-m-d\TH:i:sO', RFC_822: 'D, d M y H:i:s O', RFC_850: 'l, d-M-y H:i:s T', RFC_1036: 'D, d M y H:i:s O', RFC_1123: 'D, d M Y H:i:s O', RSS: 'D, d M Y H:i:s O', W3C: 'Y-m-d\TH:i:sP' }; // first init date formatter initDateFormatter(); // fix for ie8 if (!window.getComputedStyle) { window.getComputedStyle = function (el, pseudo) { this.el = el; this.getPropertyValue = function (prop) { var re = /(\-([a-z]){1})/g; if (prop === 'float') { prop = 'styleFloat'; } if (re.test(prop)) { prop = prop.replace(re, function (a, b, c) { return c.toUpperCase(); }); } return el.currentStyle[prop] || null; }; return this; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (obj, start) { var i, j; for (i = (start || 0), j = this.length; i < j; i += 1) { if (this[i] === obj) { return i; } } return -1; }; } Date.prototype.countDaysInMonth = function () { return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate(); }; $.fn.xdsoftScroller = function (percent) { return this.each(function () { var timeboxparent = $(this), pointerEventToXY = function (e) { var out = {x: 0, y: 0}, touch; if (e.type === 'touchstart' || e.type === 'touchmove' || e.type === 'touchend' || e.type === 'touchcancel') { touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; out.x = touch.clientX; out.y = touch.clientY; } else if (e.type === 'mousedown' || e.type === 'mouseup' || e.type === 'mousemove' || e.type === 'mouseover' || e.type === 'mouseout' || e.type === 'mouseenter' || e.type === 'mouseleave') { out.x = e.clientX; out.y = e.clientY; } return out; }, timebox, parentHeight, height, scrollbar, scroller, maximumOffset = 100, start = false, startY = 0, startTop = 0, h1 = 0, touchStart = false, startTopScroll = 0, calcOffset = function () {}; if (percent === 'hide') { timeboxparent.find('.xdsoft_scrollbar').hide(); return; } if (!$(this).hasClass('xdsoft_scroller_box')) { timebox = timeboxparent.children().eq(0); parentHeight = timeboxparent[0].clientHeight; height = timebox[0].offsetHeight; scrollbar = $('<div class="xdsoft_scrollbar"></div>'); scroller = $('<div class="xdsoft_scroller"></div>'); scrollbar.append(scroller); timeboxparent.addClass('xdsoft_scroller_box').append(scrollbar); calcOffset = function calcOffset(event) { var offset = pointerEventToXY(event).y - startY + startTopScroll; if (offset < 0) { offset = 0; } if (offset + scroller[0].offsetHeight > h1) { offset = h1 - scroller[0].offsetHeight; } timeboxparent.trigger('scroll_element.xdsoft_scroller', [maximumOffset ? offset / maximumOffset : 0]); }; scroller .on('touchstart.xdsoft_scroller mousedown.xdsoft_scroller', function (event) { if (!parentHeight) { timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]); } startY = pointerEventToXY(event).y; startTopScroll = parseInt(scroller.css('margin-top'), 10); h1 = scrollbar[0].offsetHeight; if (event.type === 'mousedown' || event.type === 'touchstart') { if (document) { $(document.body).addClass('xdsoft_noselect'); } $([document.body, window]).on('touchend mouseup.xdsoft_scroller', function arguments_callee() { $([document.body, window]).off('touchend mouseup.xdsoft_scroller', arguments_callee) .off('mousemove.xdsoft_scroller', calcOffset) .removeClass('xdsoft_noselect'); }); $(document.body).on('mousemove.xdsoft_scroller', calcOffset); } else { touchStart = true; event.stopPropagation(); event.preventDefault(); } }) .on('touchmove', function (event) { if (touchStart) { event.preventDefault(); calcOffset(event); } }) .on('touchend touchcancel', function () { touchStart = false; startTopScroll = 0; }); timeboxparent .on('scroll_element.xdsoft_scroller', function (event, percentage) { if (!parentHeight) { timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percentage, true]); } percentage = percentage > 1 ? 1 : (percentage < 0 || isNaN(percentage)) ? 0 : percentage; scroller.css('margin-top', maximumOffset * percentage); setTimeout(function () { timebox.css('marginTop', -parseInt((timebox[0].offsetHeight - parentHeight) * percentage, 10)); }, 10); }) .on('resize_scroll.xdsoft_scroller', function (event, percentage, noTriggerScroll) { var percent, sh; parentHeight = timeboxparent[0].clientHeight; height = timebox[0].offsetHeight; percent = parentHeight / height; sh = percent * scrollbar[0].offsetHeight; if (percent > 1) { scroller.hide(); } else { scroller.show(); scroller.css('height', parseInt(sh > 10 ? sh : 10, 10)); maximumOffset = scrollbar[0].offsetHeight - scroller[0].offsetHeight; if (noTriggerScroll !== true) { timeboxparent.trigger('scroll_element.xdsoft_scroller', [percentage || Math.abs(parseInt(timebox.css('marginTop'), 10)) / (height - parentHeight)]); } } }); timeboxparent.on('mousewheel', function (event) { var top = Math.abs(parseInt(timebox.css('marginTop'), 10)); top = top - (event.deltaY * 20); if (top < 0) { top = 0; } timeboxparent.trigger('scroll_element.xdsoft_scroller', [top / (height - parentHeight)]); event.stopPropagation(); return false; }); timeboxparent.on('touchstart', function (event) { start = pointerEventToXY(event); startTop = Math.abs(parseInt(timebox.css('marginTop'), 10)); }); timeboxparent.on('touchmove', function (event) { if (start) { event.preventDefault(); var coord = pointerEventToXY(event); timeboxparent.trigger('scroll_element.xdsoft_scroller', [(startTop - (coord.y - start.y)) / (height - parentHeight)]); } }); timeboxparent.on('touchend touchcancel', function () { start = false; startTop = 0; }); } timeboxparent.trigger('resize_scroll.xdsoft_scroller', [percent]); }); }; $.fn.datetimepicker = function (opt, opt2) { var result = this, KEY0 = 48, KEY9 = 57, _KEY0 = 96, _KEY9 = 105, CTRLKEY = 17, DEL = 46, ENTER = 13, ESC = 27, BACKSPACE = 8, ARROWLEFT = 37, ARROWUP = 38, ARROWRIGHT = 39, ARROWDOWN = 40, TAB = 9, F5 = 116, AKEY = 65, CKEY = 67, VKEY = 86, ZKEY = 90, YKEY = 89, ctrlDown = false, options = ($.isPlainObject(opt) || !opt) ? $.extend(true, {}, default_options, opt) : $.extend(true, {}, default_options), lazyInitTimer = 0, createDateTimePicker, destroyDateTimePicker, lazyInit = function (input) { input .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function initOnActionCallback() { if (input.is(':disabled') || input.data('xdsoft_datetimepicker')) { return; } clearTimeout(lazyInitTimer); lazyInitTimer = setTimeout(function () { if (!input.data('xdsoft_datetimepicker')) { createDateTimePicker(input); } input .off('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', initOnActionCallback) .trigger('open.xdsoft'); }, 100); }); }; createDateTimePicker = function (input) { var datetimepicker = $('<div class="xdsoft_datetimepicker xdsoft_noselect"></div>'), xdsoft_copyright = $('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'), datepicker = $('<div class="xdsoft_datepicker active"></div>'), month_picker = $('<div class="xdsoft_monthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button>' + '<div class="xdsoft_label xdsoft_month"><span></span><i></i></div>' + '<div class="xdsoft_label xdsoft_year"><span></span><i></i></div>' + '<button type="button" class="xdsoft_next"></button></div>'), calendar = $('<div class="xdsoft_calendar"></div>'), timepicker = $('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'), timeboxparent = timepicker.find('.xdsoft_time_box').eq(0), timebox = $('<div class="xdsoft_time_variant"></div>'), applyButton = $('<button type="button" class="xdsoft_save_selected blue-gradient-button">Save Selected</button>'), monthselect = $('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'), yearselect = $('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>'), triggerAfterOpen = false, XDSoft_datetime, xchangeTimer, timerclick, current_time_index, setPos, timer = 0, _xdsoft_datetime, forEachAncestorOf, throttle; if (options.id) { datetimepicker.attr('id', options.id); } if (options.style) { datetimepicker.attr('style', options.style); } if (options.weeks) { datetimepicker.addClass('xdsoft_showweeks'); } if (options.rtl) { datetimepicker.addClass('xdsoft_rtl'); } datetimepicker.addClass('xdsoft_' + options.theme); datetimepicker.addClass(options.className); month_picker .find('.xdsoft_month span') .after(monthselect); month_picker .find('.xdsoft_year span') .after(yearselect); month_picker .find('.xdsoft_month,.xdsoft_year') .on('touchstart mousedown.xdsoft', function (event) { var select = $(this).find('.xdsoft_select').eq(0), val = 0, top = 0, visible = select.is(':visible'), items, i; month_picker .find('.xdsoft_select') .hide(); if (_xdsoft_datetime.currentTime) { val = _xdsoft_datetime.currentTime[$(this).hasClass('xdsoft_month') ? 'getMonth' : 'getFullYear'](); } select[visible ? 'hide' : 'show'](); for (items = select.find('div.xdsoft_option'), i = 0; i < items.length; i += 1) { if (items.eq(i).data('value') === val) { break; } else { top += items[0].offsetHeight; } } select.xdsoftScroller(top / (select.children()[0].offsetHeight - (select[0].clientHeight))); event.stopPropagation(); return false; }); month_picker .find('.xdsoft_select') .xdsoftScroller() .on('touchstart mousedown.xdsoft', function (event) { event.stopPropagation(); event.preventDefault(); }) .on('touchstart mousedown.xdsoft', '.xdsoft_option', function () { if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) { _xdsoft_datetime.currentTime = _xdsoft_datetime.now(); } var year = _xdsoft_datetime.currentTime.getFullYear(); if (_xdsoft_datetime && _xdsoft_datetime.currentTime) { _xdsoft_datetime.currentTime[$(this).parent().parent().hasClass('xdsoft_monthselect') ? 'setMonth' : 'setFullYear']($(this).data('value')); } $(this).parent().parent().hide(); datetimepicker.trigger('xchange.xdsoft'); if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) { options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input')); } if (year !== _xdsoft_datetime.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) { options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input')); } }); datetimepicker.getValue = function () { return _xdsoft_datetime.getCurrentTime(); }; datetimepicker.setOptions = function (_options) { var highlightedDates = {}; options = $.extend(true, {}, options, _options); if (_options.allowTimes && $.isArray(_options.allowTimes) && _options.allowTimes.length) { options.allowTimes = $.extend(true, [], _options.allowTimes); } if (_options.weekends && $.isArray(_options.weekends) && _options.weekends.length) { options.weekends = $.extend(true, [], _options.weekends); } if (_options.allowDates && $.isArray(_options.allowDates) && _options.allowDates.length) { options.allowDates = $.extend(true, [], _options.allowDates); } if (_options.allowDateRe && Object.prototype.toString.call(_options.allowDateRe)==="[object String]") { options.allowDateRe = new RegExp(_options.allowDateRe); } if (_options.highlightedDates && $.isArray(_options.highlightedDates) && _options.highlightedDates.length) { $.each(_options.highlightedDates, function (index, value) { var splitData = $.map(value.split(','), $.trim), exDesc, hDate = new HighlightedDate(dateHelper.parseDate(splitData[0], options.formatDate), splitData[1], splitData[2]), // date, desc, style keyDate = dateHelper.formatDate(hDate.date, options.formatDate); if (highlightedDates[keyDate] !== undefined) { exDesc = highlightedDates[keyDate].desc; if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) { highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc; } } else { highlightedDates[keyDate] = hDate; } }); options.highlightedDates = $.extend(true, [], highlightedDates); } if (_options.highlightedPeriods && $.isArray(_options.highlightedPeriods) && _options.highlightedPeriods.length) { highlightedDates = $.extend(true, [], options.highlightedDates); $.each(_options.highlightedPeriods, function (index, value) { var dateTest, // start date dateEnd, desc, hDate, keyDate, exDesc, style; if ($.isArray(value)) { dateTest = value[0]; dateEnd = value[1]; desc = value[2]; style = value[3]; } else { var splitData = $.map(value.split(','), $.trim); dateTest = dateHelper.parseDate(splitData[0], options.formatDate); dateEnd = dateHelper.parseDate(splitData[1], options.formatDate); desc = splitData[2]; style = splitData[3]; } while (dateTest <= dateEnd) { hDate = new HighlightedDate(dateTest, desc, style); keyDate = dateHelper.formatDate(dateTest, options.formatDate); dateTest.setDate(dateTest.getDate() + 1); if (highlightedDates[keyDate] !== undefined) { exDesc = highlightedDates[keyDate].desc; if (exDesc && exDesc.length && hDate.desc && hDate.desc.length) { highlightedDates[keyDate].desc = exDesc + "\n" + hDate.desc; } } else { highlightedDates[keyDate] = hDate; } } }); options.highlightedDates = $.extend(true, [], highlightedDates); } if (_options.disabledDates && $.isArray(_options.disabledDates) && _options.disabledDates.length) { options.disabledDates = $.extend(true, [], _options.disabledDates); } if (_options.disabledWeekDays && $.isArray(_options.disabledWeekDays) && _options.disabledWeekDays.length) { options.disabledWeekDays = $.extend(true, [], _options.disabledWeekDays); } if ((options.open || options.opened) && (!options.inline)) { input.trigger('open.xdsoft'); } if (options.inline) { triggerAfterOpen = true; datetimepicker.addClass('xdsoft_inline'); input.after(datetimepicker).hide(); } if (options.inverseButton) { options.next = 'xdsoft_prev'; options.prev = 'xdsoft_next'; } if (options.datepicker) { datepicker.addClass('active'); } else { datepicker.removeClass('active'); } if (options.timepicker) { timepicker.addClass('active'); } else { timepicker.removeClass('active'); } if (options.value) { _xdsoft_datetime.setCurrentTime(options.value); if (input && input.val) { input.val(_xdsoft_datetime.str); } } if (isNaN(options.dayOfWeekStart)) { options.dayOfWeekStart = 0; } else { options.dayOfWeekStart = parseInt(options.dayOfWeekStart, 10) % 7; } if (!options.timepickerScrollbar) { timeboxparent.xdsoftScroller('hide'); } if (options.minDate && /^[\+\-](.*)$/.test(options.minDate)) { options.minDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.minDate), options.formatDate); } if (options.maxDate && /^[\+\-](.*)$/.test(options.maxDate)) { options.maxDate = dateHelper.formatDate(_xdsoft_datetime.strToDateTime(options.maxDate), options.formatDate); } applyButton.toggle(options.showApplyButton); month_picker .find('.xdsoft_today_button') .css('visibility', !options.todayButton ? 'hidden' : 'visible'); month_picker .find('.' + options.prev) .css('visibility', !options.prevButton ? 'hidden' : 'visible'); month_picker .find('.' + options.next) .css('visibility', !options.nextButton ? 'hidden' : 'visible'); setMask(options); if (options.validateOnBlur) { input .off('blur.xdsoft') .on('blur.xdsoft', function () { if (options.allowBlank && (!$.trim($(this).val()).length || (typeof options.mask == "string" && $.trim($(this).val()) === options.mask.replace(/[0-9]/g, '_')))) { $(this).val(null); datetimepicker.data('xdsoft_datetime').empty(); } else { var d = dateHelper.parseDate($(this).val(), options.format); if (d) { // parseDate() may skip some invalid parts like date or time, so make it clear for user: show parsed date/time $(this).val(dateHelper.formatDate(d, options.format)); } else { var splittedHours = +([$(this).val()[0], $(this).val()[1]].join('')), splittedMinutes = +([$(this).val()[2], $(this).val()[3]].join('')); // parse the numbers as 0312 => 03:12 if (!options.datepicker && options.timepicker && splittedHours >= 0 && splittedHours < 24 && splittedMinutes >= 0 && splittedMinutes < 60) { $(this).val([splittedHours, splittedMinutes].map(function (item) { return item > 9 ? item : '0' + item; }).join(':')); } else { $(this).val(dateHelper.formatDate(_xdsoft_datetime.now(), options.format)); } } datetimepicker.data('xdsoft_datetime').setCurrentTime($(this).val()); } datetimepicker.trigger('changedatetime.xdsoft'); datetimepicker.trigger('close.xdsoft'); }); } options.dayOfWeekStartPrev = (options.dayOfWeekStart === 0) ? 6 : options.dayOfWeekStart - 1; datetimepicker .trigger('xchange.xdsoft') .trigger('afterOpen.xdsoft'); }; datetimepicker .data('options', options) .on('touchstart mousedown.xdsoft', function (event) { event.stopPropagation(); event.preventDefault(); yearselect.hide(); monthselect.hide(); return false; }); //scroll_element = timepicker.find('.xdsoft_time_box'); timeboxparent.append(timebox); timeboxparent.xdsoftScroller(); datetimepicker.on('afterOpen.xdsoft', function () { timeboxparent.xdsoftScroller(); }); datetimepicker .append(datepicker) .append(timepicker); if (options.withoutCopyright !== true) { datetimepicker .append(xdsoft_copyright); } datepicker .append(month_picker) .append(calendar) .append(applyButton); $(options.parentID) .append(datetimepicker); XDSoft_datetime = function () { var _this = this; _this.now = function (norecursion) { var d = new Date(), date, time; if (!norecursion && options.defaultDate) { date = _this.strToDateTime(options.defaultDate); d.setFullYear(date.getFullYear()); d.setMonth(date.getMonth()); d.setDate(date.getDate()); } if (options.yearOffset) { d.setFullYear(d.getFullYear() + options.yearOffset); } if (!norecursion && options.defaultTime) { time = _this.strtotime(options.defaultTime); d.setHours(time.getHours()); d.setMinutes(time.getMinutes()); } return d; }; _this.isValidDate = function (d) { if (Object.prototype.toString.call(d) !== "[object Date]") { return false; } return !isNaN(d.getTime()); }; _this.setCurrentTime = function (dTime, requireValidDate) { if (typeof dTime === 'string') { _this.currentTime = _this.strToDateTime(dTime); } else if (_this.isValidDate(dTime)) { _this.currentTime = dTime; } else if (!dTime && !requireValidDate && options.allowBlank) { _this.currentTime = null; } else { _this.currentTime = _this.now(); } datetimepicker.trigger('xchange.xdsoft'); }; _this.empty = function () { _this.currentTime = null; }; _this.getCurrentTime = function (dTime) { return _this.currentTime; }; _this.nextMonth = function () { if (_this.currentTime === undefined || _this.currentTime === null) { _this.currentTime = _this.now(); } var month = _this.currentTime.getMonth() + 1, year; if (month === 12) { _this.currentTime.setFullYear(_this.currentTime.getFullYear() + 1); month = 0; } year = _this.currentTime.getFullYear(); _this.currentTime.setDate( Math.min( new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(), _this.currentTime.getDate() ) ); _this.currentTime.setMonth(month); if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) { options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input')); } if (year !== _this.currentTime.getFullYear() && $.isFunction(options.onChangeYear)) { options.onChangeYear.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input')); } datetimepicker.trigger('xchange.xdsoft'); return month; }; _this.prevMonth = function () { if (_this.currentTime === undefined || _this.currentTime === null) { _this.currentTime = _this.now(); } var month = _this.currentTime.getMonth() - 1; if (month === -1) { _this.currentTime.setFullYear(_this.currentTime.getFullYear() - 1); month = 11; } _this.currentTime.setDate( Math.min( new Date(_this.currentTime.getFullYear(), month + 1, 0).getDate(), _this.currentTime.getDate() ) ); _this.currentTime.setMonth(month); if (options.onChangeMonth && $.isFunction(options.onChangeMonth)) { options.onChangeMonth.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input')); } datetimepicker.trigger('xchange.xdsoft'); return month; }; _this.getWeekOfYear = function (datetime) { if (options.onGetWeekOfYear && $.isFunction(options.onGetWeekOfYear)) { var week = options.onGetWeekOfYear.call(datetimepicker, datetime); if (typeof week !== 'undefined') { return week; } } var onejan = new Date(datetime.getFullYear(), 0, 1); //First week of the year is th one with the first Thursday according to ISO8601 if(onejan.getDay()!=4) onejan.setMonth(0, 1 + ((4 - onejan.getDay()+ 7) % 7)); return Math.ceil((((datetime - onejan) / 86400000) + onejan.getDay() + 1) / 7); }; _this.strToDateTime = function (sDateTime) { var tmpDate = [], timeOffset, currentTime; if (sDateTime && sDateTime instanceof Date && _this.isValidDate(sDateTime)) { return sDateTime; } tmpDate = /^(\+|\-)(.*)$/.exec(sDateTime); if (tmpDate) { tmpDate[2] = dateHelper.parseDate(tmpDate[2], options.formatDate); } if (tmpDate && tmpDate[2]) { timeOffset = tmpDate[2].getTime() - (tmpDate[2].getTimezoneOffset()) * 60000; currentTime = new Date((_this.now(true)).getTime() + parseInt(tmpDate[1] + '1', 10) * timeOffset); } else { currentTime = sDateTime ? dateHelper.parseDate(sDateTime, options.format) : _this.now(); } if (!_this.isValidDate(currentTime)) { currentTime = _this.now(); } return currentTime; }; _this.strToDate = function (sDate) { if (sDate && sDate instanceof Date && _this.isValidDate(sDate)) { return sDate; } var currentTime = sDate ? dateHelper.parseDate(sDate, options.formatDate) : _this.now(true); if (!_this.isValidDate(currentTime)) { currentTime = _this.now(true); } return currentTime; }; _this.strtotime = function (sTime) { if (sTime && sTime instanceof Date && _this.isValidDate(sTime)) { return sTime; } var currentTime = sTime ? dateHelper.parseDate(sTime, options.formatTime) : _this.now(true); if (!_this.isValidDate(currentTime)) { currentTime = _this.now(true); } return currentTime; }; _this.str = function () { return dateHelper.formatDate(_this.currentTime, options.format); }; _this.currentTime = this.now(); }; _xdsoft_datetime = new XDSoft_datetime(); applyButton.on('touchend click', function (e) {//pathbrite e.preventDefault(); datetimepicker.data('changed', true); _xdsoft_datetime.setCurrentTime(getCurrentValue()); input.val(_xdsoft_datetime.str()); datetimepicker.trigger('close.xdsoft'); }); month_picker .find('.xdsoft_today_button') .on('touchend mousedown.xdsoft', function () { datetimepicker.data('changed', true); _xdsoft_datetime.setCurrentTime(0, true); datetimepicker.trigger('afterOpen.xdsoft'); }).on('dblclick.xdsoft', function () { var currentDate = _xdsoft_datetime.getCurrentTime(), minDate, maxDate; currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()); minDate = _xdsoft_datetime.strToDate(options.minDate); minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate()); if (currentDate < minDate) { return; } maxDate = _xdsoft_datetime.strToDate(options.maxDate); maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate()); if (currentDate > maxDate) { return; } input.val(_xdsoft_datetime.str()); input.trigger('change'); datetimepicker.trigger('close.xdsoft'); }); month_picker .find('.xdsoft_prev,.xdsoft_next') .on('touchend mousedown.xdsoft', function () { var $this = $(this), timer = 0, stop = false; (function arguments_callee1(v) { if ($this.hasClass(options.next)) { _xdsoft_datetime.nextMonth(); } else if ($this.hasClass(options.prev)) { _xdsoft_datetime.prevMonth(); } if (options.monthChangeSpinner) { if (!stop) { timer = setTimeout(arguments_callee1, v || 100); } } }(500)); $([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee2() { clearTimeout(timer); stop = true; $([document.body, window]).off('touchend mouseup.xdsoft', arguments_callee2); }); }); timepicker .find('.xdsoft_prev,.xdsoft_next') .on('touchend mousedown.xdsoft', function () { var $this = $(this), timer = 0, stop = false, period = 110; (function arguments_callee4(v) { var pheight = timeboxparent[0].clientHeight, height = timebox[0].offsetHeight, top = Math.abs(parseInt(timebox.css('marginTop'), 10)); if ($this.hasClass(options.next) && (height - pheight) - options.timeHeightInTimePicker >= top) { timebox.css('marginTop', '-' + (top + options.timeHeightInTimePicker) + 'px'); } else if ($this.hasClass(options.prev) && top - options.timeHeightInTimePicker >= 0) { timebox.css('marginTop', '-' + (top - options.timeHeightInTimePicker) + 'px'); } /** * Fixed bug: * When using css3 transition, it will cause a bug that you cannot scroll the timepicker list. * The reason is that the transition-duration time, if you set it to 0, all things fine, otherwise, this * would cause a bug when you use jquery.css method. * Let's say: * { transition: all .5s ease; } * jquery timebox.css('marginTop') will return the original value which is before you clicking the next/prev button, * meanwhile the timebox[0].style.marginTop will return the right value which is after you clicking the * next/prev button. * * What we should do: * Replace timebox.css('marginTop') with timebox[0].style.marginTop. */ timeboxparent.trigger('scroll_element.xdsoft_scroller', [Math.abs(parseInt(timebox[0].style.marginTop, 10) / (height - pheight))]); period = (period > 10) ? 10 : period - 10; if (!stop) { timer = setTimeout(arguments_callee4, v || period); } }(500)); $([document.body, window]).on('touchend mouseup.xdsoft', function arguments_callee5() { clearTimeout(timer); stop = true; $([document.body, window]) .off('touchend mouseup.xdsoft', arguments_callee5); }); }); xchangeTimer = 0; // base handler - generating a calendar and timepicker datetimepicker .on('xchange.xdsoft', function (event) { clearTimeout(xchangeTimer); xchangeTimer = setTimeout(function () { if (_xdsoft_datetime.currentTime === undefined || _xdsoft_datetime.currentTime === null) { //In case blanks are allowed, delay construction until we have a valid date if (options.allowBlank) return; _xdsoft_datetime.currentTime = _xdsoft_datetime.now(); } var table = '', start = new Date(_xdsoft_datetime.currentTime.getFullYear(), _xdsoft_datetime.currentTime.getMonth(), 1, 12, 0, 0), i = 0, j, today = _xdsoft_datetime.now(), maxDate = false, minDate = false, hDate, day, d, y, m, w, classes = [], customDateSettings, newRow = true, time = '', h = '', line_time, description; while (start.getDay() !== options.dayOfWeekStart) { start.setDate(start.getDate() - 1); } table += '<table><thead><tr>'; if (options.weeks) { table += '<th></th>'; } for (j = 0; j < 7; j += 1) { table += '<th>' + options.i18n[globalLocale].dayOfWeekShort[(j + options.dayOfWeekStart) % 7] + '</th>'; } table += '</tr></thead>'; table += '<tbody>'; if (options.maxDate !== false) { maxDate = _xdsoft_datetime.strToDate(options.maxDate); maxDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate(), 23, 59, 59, 999); } if (options.minDate !== false) { minDate = _xdsoft_datetime.strToDate(options.minDate); minDate = new Date(minDate.getFullYear(), minDate.getMonth(), minDate.getDate()); } while (i < _xdsoft_datetime.currentTime.countDaysInMonth() || start.getDay() !== options.dayOfWeekStart || _xdsoft_datetime.currentTime.getMonth() === start.getMonth()) { classes = []; i += 1; day = start.getDay(); d = start.getDate(); y = start.getFullYear(); m = start.getMonth(); w = _xdsoft_datetime.getWeekOfYear(start); description = ''; classes.push('xdsoft_date'); if (options.beforeShowDay && $.isFunction(options.beforeShowDay.call)) { customDateSettings = options.beforeShowDay.call(datetimepicker, start); } else { customDateSettings = null; } if(options.allowDateRe && Object.prototype.toString.call(options.allowDateRe) === "[object RegExp]"){ if(!options.allowDateRe.test(dateHelper.formatDate(start, options.formatDate))){ classes.push('xdsoft_disabled'); } } else if(options.allowDates && options.allowDates.length>0){ if(options.allowDates.indexOf(dateHelper.formatDate(start, options.formatDate)) === -1){ classes.push('xdsoft_disabled'); } } else if ((maxDate !== false && start > maxDate) || (minDate !== false && start < minDate) || (customDateSettings && customDateSettings[0] === false)) { classes.push('xdsoft_disabled'); } else if (options.disabledDates.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) { classes.push('xdsoft_disabled'); } else if (options.disabledWeekDays.indexOf(day) !== -1) { classes.push('xdsoft_disabled'); }else if (input.is('[readonly]')) { classes.push('xdsoft_disabled'); } if (customDateSettings && customDateSettings[1] !== "") { classes.push(customDateSettings[1]); } if (_xdsoft_datetime.currentTime.getMonth() !== m) { classes.push('xdsoft_other_month'); } if ((options.defaultSelect || datetimepicker.data('changed')) && dateHelper.formatDate(_xdsoft_datetime.currentTime, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) { classes.push('xdsoft_current'); } if (dateHelper.formatDate(today, options.formatDate) === dateHelper.formatDate(start, options.formatDate)) { classes.push('xdsoft_today'); } if (start.getDay() === 0 || start.getDay() === 6 || options.weekends.indexOf(dateHelper.formatDate(start, options.formatDate)) !== -1) { classes.push('xdsoft_weekend'); } if (options.highlightedDates[dateHelper.formatDate(start, options.formatDate)] !== undefined) { hDate = options.highlightedDates[dateHelper.formatDate(start, options.formatDate)]; classes.push(hDate.style === undefined ? 'xdsoft_highlighted_default' : hDate.style); description = hDate.desc === undefined ? '' : hDate.desc; } if (options.beforeShowDay && $.isFunction(options.beforeShowDay)) { classes.push(options.beforeShowDay(start)); } if (newRow) { table += '<tr>'; newRow = false; if (options.weeks) { table += '<th>' + w + '</th>'; } } table += '<td data-date="' + d + '" data-month="' + m + '" data-year="' + y + '"' + ' class="xdsoft_date xdsoft_day_of_week' + start.getDay() + ' ' + classes.join(' ') + '" title="' + description + '">' + '<div>' + d + '</div>' + '</td>'; if (start.getDay() === options.dayOfWeekStartPrev) { table += '</tr>'; newRow = true; } start.setDate(d + 1); } table += '</tbody></table>'; calendar.html(table); month_picker.find('.xdsoft_label span').eq(0).text(options.i18n[globalLocale].months[_xdsoft_datetime.currentTime.getMonth()]); month_picker.find('.xdsoft_label span').eq(1).text(_xdsoft_datetime.currentTime.getFullYear()); // generate timebox time = ''; h = ''; m = ''; line_time = function line_time(h, m) { var now = _xdsoft_datetime.now(), optionDateTime, current_time, isALlowTimesInit = options.allowTimes && $.isArray(options.allowTimes) && options.allowTimes.length; now.setHours(h); h = parseInt(now.getHours(), 10); now.setMinutes(m); m = parseInt(now.getMinutes(), 10); optionDateTime = new Date(_xdsoft_datetime.currentTime); optionDateTime.setHours(h); optionDateTime.setMinutes(m); classes = []; if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || (options.maxTime !== false && _xdsoft_datetime.strtotime(options.maxTime).getTime() < now.getTime()) || (options.minTime !== false && _xdsoft_datetime.strtotime(options.minTime).getTime() > now.getTime())) { classes.push('xdsoft_disabled'); } else if ((options.minDateTime !== false && options.minDateTime > optionDateTime) || ((options.disabledMinTime !== false && now.getTime() > _xdsoft_datetime.strtotime(options.disabledMinTime).getTime()) && (options.disabledMaxTime !== false && now.getTime() < _xdsoft_datetime.strtotime(options.disabledMaxTime).getTime()))) { classes.push('xdsoft_disabled'); } else if (input.is('[readonly]')) { classes.push('xdsoft_disabled'); } current_time = new Date(_xdsoft_datetime.currentTime); current_time.setHours(parseInt(_xdsoft_datetime.currentTime.getHours(), 10)); if (!isALlowTimesInit) { current_time.setMinutes(Math[options.roundTime](_xdsoft_datetime.currentTime.getMinutes() / options.step) * options.step); } if ((options.initTime || options.defaultSelect || datetimepicker.data('changed')) && current_time.getHours() === parseInt(h, 10) && ((!isALlowTimesInit && options.step > 59) || current_time.getMinutes() === parseInt(m, 10))) { if (options.defaultSelect || datetimepicker.data('changed')) { classes.push('xdsoft_current'); } else if (options.initTime) { classes.push('xdsoft_init_time'); } } if (parseInt(today.getHours(), 10) === parseInt(h, 10) && parseInt(today.getMinutes(), 10) === parseInt(m, 10)) { classes.push('xdsoft_today'); } time += '<div class="xdsoft_time ' + classes.join(' ') + '" data-hour="' + h + '" data-minute="' + m + '">' + dateHelper.formatDate(now, options.formatTime) + '</div>'; }; if (!options.allowTimes || !$.isArray(options.allowTimes) || !options.allowTimes.length) { for (i = 0, j = 0; i < (options.hours12 ? 12 : 24); i += 1) { for (j = 0; j < 60; j += options.step) { h = (i < 10 ? '0' : '') + i; m = (j < 10 ? '0' : '') + j; line_time(h, m); } } } else { for (i = 0; i < options.allowTimes.length; i += 1) { h = _xdsoft_datetime.strtotime(options.allowTimes[i]).getHours(); m = _xdsoft_datetime.strtotime(options.allowTimes[i]).getMinutes(); line_time(h, m); } } timebox.html(time); opt = ''; i = 0; for (i = parseInt(options.yearStart, 10) + options.yearOffset; i <= parseInt(options.yearEnd, 10) + options.yearOffset; i += 1) { opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getFullYear() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + i + '</div>'; } yearselect.children().eq(0) .html(opt); for (i = parseInt(options.monthStart, 10), opt = ''; i <= parseInt(options.monthEnd, 10); i += 1) { opt += '<div class="xdsoft_option ' + (_xdsoft_datetime.currentTime.getMonth() === i ? 'xdsoft_current' : '') + '" data-value="' + i + '">' + options.i18n[globalLocale].months[i] + '</div>'; } monthselect.children().eq(0).html(opt); $(datetimepicker) .trigger('generate.xdsoft'); }, 10); event.stopPropagation(); }) .on('afterOpen.xdsoft', function () { if (options.timepicker) { var classType, pheight, height, top; if (timebox.find('.xdsoft_current').length) { classType = '.xdsoft_current'; } else if (timebox.find('.xdsoft_init_time').length) { classType = '.xdsoft_init_time'; } if (classType) { pheight = timeboxparent[0].clientHeight; height = timebox[0].offsetHeight; top = timebox.find(classType).index() * options.timeHeightInTimePicker + 1; if ((height - pheight) < top) { top = height - pheight; } timeboxparent.trigger('scroll_element.xdsoft_scroller', [parseInt(top, 10) / (height - pheight)]); } else { timeboxparent.trigger('scroll_element.xdsoft_scroller', [0]); } } }); timerclick = 0; calendar .on('touchend click.xdsoft', 'td', function (xdevent) { xdevent.stopPropagation(); // Prevents closing of Pop-ups, Modals and Flyouts in Bootstrap timerclick += 1; var $this = $(this), currentTime = _xdsoft_datetime.currentTime; if (currentTime === undefined || currentTime === null) { _xdsoft_datetime.currentTime = _xdsoft_datetime.now(); currentTime = _xdsoft_datetime.currentTime; } if ($this.hasClass('xdsoft_disabled')) { return false; } currentTime.setDate(1); currentTime.setFullYear($this.data('year')); currentTime.setMonth($this.data('month')); currentTime.setDate($this.data('date')); datetimepicker.trigger('select.xdsoft', [currentTime]); input.val(_xdsoft_datetime.str()); if (options.onSelectDate && $.isFunction(options.onSelectDate)) { options.onSelectDate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent); } datetimepicker.data('changed', true); datetimepicker.trigger('xchange.xdsoft'); datetimepicker.trigger('changedatetime.xdsoft'); if ((timerclick > 1 || (options.closeOnDateSelect === true || (options.closeOnDateSelect === false && !options.timepicker))) && !options.inline) { datetimepicker.trigger('close.xdsoft'); } setTimeout(function () { timerclick = 0; }, 200); }); timebox .on('touchmove', 'div', function () { currentlyScrollingTimeDiv = true; }) .on('touchend click.xdsoft', 'div', function (xdevent) { xdevent.stopPropagation(); if (currentlyScrollingTimeDiv) { currentlyScrollingTimeDiv = false; return; } var $this = $(this), currentTime = _xdsoft_datetime.currentTime; if (currentTime === undefined || currentTime === null) { _xdsoft_datetime.currentTime = _xdsoft_datetime.now(); currentTime = _xdsoft_datetime.currentTime; } if ($this.hasClass('xdsoft_disabled')) { return false; } currentTime.setHours($this.data('hour')); currentTime.setMinutes($this.data('minute')); datetimepicker.trigger('select.xdsoft', [currentTime]); datetimepicker.data('input').val(_xdsoft_datetime.str()); if (options.onSelectTime && $.isFunction(options.onSelectTime)) { options.onSelectTime.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), xdevent); } datetimepicker.data('changed', true); datetimepicker.trigger('xchange.xdsoft'); datetimepicker.trigger('changedatetime.xdsoft'); if (options.inline !== true && options.closeOnTimeSelect === true) { datetimepicker.trigger('close.xdsoft'); } }); datepicker .on('mousewheel.xdsoft', function (event) { if (!options.scrollMonth) { return true; } if (event.deltaY < 0) { _xdsoft_datetime.nextMonth(); } else { _xdsoft_datetime.prevMonth(); } return false; }); input .on('mousewheel.xdsoft', function (event) { if (!options.scrollInput) { return true; } if (!options.datepicker && options.timepicker) { current_time_index = timebox.find('.xdsoft_current').length ? timebox.find('.xdsoft_current').eq(0).index() : 0; if (current_time_index + event.deltaY >= 0 && current_time_index + event.deltaY < timebox.children().length) { current_time_index += event.deltaY; } if (timebox.children().eq(current_time_index).length) { timebox.children().eq(current_time_index).trigger('mousedown'); } return false; } if (options.datepicker && !options.timepicker) { datepicker.trigger(event, [event.deltaY, event.deltaX, event.deltaY]); if (input.val) { input.val(_xdsoft_datetime.str()); } datetimepicker.trigger('changedatetime.xdsoft'); return false; } }); datetimepicker .on('changedatetime.xdsoft', function (event) { if (options.onChangeDateTime && $.isFunction(options.onChangeDateTime)) { var $input = datetimepicker.data('input'); options.onChangeDateTime.call(datetimepicker, _xdsoft_datetime.currentTime, $input, event); delete options.value; $input.trigger('change'); } }) .on('generate.xdsoft', function () { if (options.onGenerate && $.isFunction(options.onGenerate)) { options.onGenerate.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input')); } if (triggerAfterOpen) { datetimepicker.trigger('afterOpen.xdsoft'); triggerAfterOpen = false; } }) .on('click.xdsoft', function (xdevent) { xdevent.stopPropagation(); }); current_time_index = 0; /** * Runs the callback for each of the specified node's ancestors. * * Return FALSE from the callback to stop ascending. * * @param {DOMNode} node * @param {Function} callback * @returns {undefined} */ forEachAncestorOf = function (node, callback) { do { node = node.parentNode; if (callback(node) === false) { break; } } while (node.nodeName !== 'HTML'); }; /** * Sets the position of the picker. * * @returns {undefined} */ setPos = function () { var dateInputOffset, dateInputElem, verticalPosition, left, position, datetimepickerElem, dateInputHasFixedAncestor, $dateInput, windowWidth, verticalAnchorEdge, datetimepickerCss, windowHeight, windowScrollTop; $dateInput = datetimepicker.data('input'); dateInputOffset = $dateInput.offset(); dateInputElem = $dateInput[0]; verticalAnchorEdge = 'top'; verticalPosition = (dateInputOffset.top + dateInputElem.offsetHeight) - 1; left = dateInputOffset.left; position = "absolute"; windowWidth = $(window).width(); windowHeight = $(window).height(); windowScrollTop = $(window).scrollTop(); if ((document.documentElement.clientWidth - dateInputOffset.left) < datepicker.parent().outerWidth(true)) { var diff = datepicker.parent().outerWidth(true) - dateInputElem.offsetWidth; left = left - diff; } if ($dateInput.parent().css('direction') === 'rtl') { left -= (datetimepicker.outerWidth() - $dateInput.outerWidth()); } if (options.fixed) { verticalPosition -= windowScrollTop; left -= $(window).scrollLeft(); position = "fixed"; } else { dateInputHasFixedAncestor = false; forEachAncestorOf(dateInputElem, function (ancestorNode) { if (window.getComputedStyle(ancestorNode).getPropertyValue('position') === 'fixed') { dateInputHasFixedAncestor = true; return false; } }); if (dateInputHasFixedAncestor) { position = 'fixed'; //If the picker won't fit entirely within the viewport then display it above the date input. if (verticalPosition + datetimepicker.outerHeight() > windowHeight + windowScrollTop) { verticalAnchorEdge = 'bottom'; verticalPosition = (windowHeight + windowScrollTop) - dateInputOffset.top; } else { verticalPosition -= windowScrollTop; } } else { if (verticalPosition + dateInputElem.offsetHeight > windowHeight + windowScrollTop) { verticalPosition = dateInputOffset.top - dateInputElem.offsetHeight + 1; } } if (verticalPosition < 0) { verticalPosition = 0; } if (left + dateInputElem.offsetWidth > windowWidth) { left = windowWidth - dateInputElem.offsetWidth; } } datetimepickerElem = datetimepicker[0]; forEachAncestorOf(datetimepickerElem, function (ancestorNode) { var ancestorNodePosition; ancestorNodePosition = window.getComputedStyle(ancestorNode).getPropertyValue('position'); if (ancestorNodePosition === 'relative' && windowWidth >= ancestorNode.offsetWidth) { left = left - ((windowWidth - ancestorNode.offsetWidth) / 2); return false; } }); datetimepickerCss = { position: position, left: left, top: '', //Initialize to prevent previous values interfering with new ones. bottom: '' //Initialize to prevent previous values interfering with new ones. }; datetimepickerCss[verticalAnchorEdge] = verticalPosition; datetimepicker.css(datetimepickerCss); }; datetimepicker .on('open.xdsoft', function (event) { var onShow = true; if (options.onShow && $.isFunction(options.onShow)) { onShow = options.onShow.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event); } if (onShow !== false) { datetimepicker.show(); setPos(); $(window) .off('resize.xdsoft', setPos) .on('resize.xdsoft', setPos); if (options.closeOnWithoutClick) { $([document.body, window]).on('touchstart mousedown.xdsoft', function arguments_callee6() { datetimepicker.trigger('close.xdsoft'); $([document.body, window]).off('touchstart mousedown.xdsoft', arguments_callee6); }); } } }) .on('close.xdsoft', function (event) { var onClose = true; month_picker .find('.xdsoft_month,.xdsoft_year') .find('.xdsoft_select') .hide(); if (options.onClose && $.isFunction(options.onClose)) { onClose = options.onClose.call(datetimepicker, _xdsoft_datetime.currentTime, datetimepicker.data('input'), event); } if (onClose !== false && !options.opened && !options.inline) { datetimepicker.hide(); } event.stopPropagation(); }) .on('toggle.xdsoft', function () { if (datetimepicker.is(':visible')) { datetimepicker.trigger('close.xdsoft'); } else { datetimepicker.trigger('open.xdsoft'); } }) .data('input', input); timer = 0; datetimepicker.data('xdsoft_datetime', _xdsoft_datetime); datetimepicker.setOptions(options); function getCurrentValue() { var ct = false, time; if (options.startDate) { ct = _xdsoft_datetime.strToDate(options.startDate); } else { ct = options.value || ((input && input.val && input.val()) ? input.val() : ''); if (ct) { ct = _xdsoft_datetime.strToDateTime(ct); } else if (options.defaultDate) { ct = _xdsoft_datetime.strToDateTime(options.defaultDate); if (options.defaultTime) { time = _xdsoft_datetime.strtotime(options.defaultTime); ct.setHours(time.getHours()); ct.setMinutes(time.getMinutes()); } } } if (ct && _xdsoft_datetime.isValidDate(ct)) { datetimepicker.data('changed', true); } else { ct = ''; } return ct || 0; } function setMask(options) { var isValidValue = function (mask, value) { var reg = mask .replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, '\\$1') .replace(/_/g, '{digit+}') .replace(/([0-9]{1})/g, '{digit$1}') .replace(/\{digit([0-9]{1})\}/g, '[0-$1_]{1}') .replace(/\{digit[\+]\}/g, '[0-9_]{1}'); return (new RegExp(reg)).test(value); }, getCaretPos = function (input) { try { if (document.selection && document.selection.createRange) { var range = document.selection.createRange(); return range.getBookmark().charCodeAt(2) - 2; } if (input.setSelectionRange) { return input.selectionStart; } } catch (e) { return 0; } }, setCaretPos = function (node, pos) { node = (typeof node === "string" || node instanceof String) ? document.getElementById(node) : node; if (!node) { return false; } if (node.createTextRange) { var textRange = node.createTextRange(); textRange.collapse(true); textRange.moveEnd('character', pos); textRange.moveStart('character', pos); textRange.select(); return true; } if (node.setSelectionRange) { node.setSelectionRange(pos, pos); return true; } return false; }; if(options.mask) { input.off('keydown.xdsoft'); } if (options.mask === true) { if (typeof moment != 'undefined') { options.mask = options.format .replace(/Y{4}/g, '9999') .replace(/Y{2}/g, '99') .replace(/M{2}/g, '19') .replace(/D{2}/g, '39') .replace(/H{2}/g, '29') .replace(/m{2}/g, '59') .replace(/s{2}/g, '59'); } else { options.mask = options.format .replace(/Y/g, '9999') .replace(/F/g, '9999') .replace(/m/g, '19') .replace(/d/g, '39') .replace(/H/g, '29') .replace(/i/g, '59') .replace(/s/g, '59'); } } if ($.type(options.mask) === 'string') { if (!isValidValue(options.mask, input.val())) { input.val(options.mask.replace(/[0-9]/g, '_')); setCaretPos(input[0], 0); } input.on('keydown.xdsoft', function (event) { var val = this.value, key = event.which, pos, digit; if (((key >= KEY0 && key <= KEY9) || (key >= _KEY0 && key <= _KEY9)) || (key === BACKSPACE || key === DEL)) { pos = getCaretPos(this); digit = (key !== BACKSPACE && key !== DEL) ? String.fromCharCode((_KEY0 <= key && key <= _KEY9) ? key - KEY0 : key) : '_'; if ((key === BACKSPACE || key === DEL) && pos) { pos -= 1; digit = '_'; } while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) { pos += (key === BACKSPACE || key === DEL) ? -1 : 1; } val = val.substr(0, pos) + digit + val.substr(pos + 1); if ($.trim(val) === '') { val = options.mask.replace(/[0-9]/g, '_'); } else { if (pos === options.mask.length) { event.preventDefault(); return false; } } pos += (key === BACKSPACE || key === DEL) ? 0 : 1; while (/[^0-9_]/.test(options.mask.substr(pos, 1)) && pos < options.mask.length && pos > 0) { pos += (key === BACKSPACE || key === DEL) ? -1 : 1; } if (isValidValue(options.mask, val)) { this.value = val; setCaretPos(this, pos); } else if ($.trim(val) === '') { this.value = options.mask.replace(/[0-9]/g, '_'); } else { input.trigger('error_input.xdsoft'); } } else { if (([AKEY, CKEY, VKEY, ZKEY, YKEY].indexOf(key) !== -1 && ctrlDown) || [ESC, ARROWUP, ARROWDOWN, ARROWLEFT, ARROWRIGHT, F5, CTRLKEY, TAB, ENTER].indexOf(key) !== -1) { return true; } } event.preventDefault(); return false; }); } } _xdsoft_datetime.setCurrentTime(getCurrentValue()); input .data('xdsoft_datetimepicker', datetimepicker) .on('open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart', function () { if (input.is(':disabled') || (input.data('xdsoft_datetimepicker').is(':visible') && options.closeOnInputClick)) { return; } clearTimeout(timer); timer = setTimeout(function () { if (input.is(':disabled')) { return; } triggerAfterOpen = true; _xdsoft_datetime.setCurrentTime(getCurrentValue(), true); if(options.mask) { setMask(options); } datetimepicker.trigger('open.xdsoft'); }, 100); }) .on('keydown.xdsoft', function (event) { var elementSelector, key = event.which; if ([ENTER].indexOf(key) !== -1 && options.enterLikeTab) { elementSelector = $("input:visible,textarea:visible,button:visible,a:visible"); datetimepicker.trigger('close.xdsoft'); elementSelector.eq(elementSelector.index(this) + 1).focus(); return false; } if ([TAB].indexOf(key) !== -1) { datetimepicker.trigger('close.xdsoft'); return true; } }) .on('blur.xdsoft', function () { datetimepicker.trigger('close.xdsoft'); }); }; destroyDateTimePicker = function (input) { var datetimepicker = input.data('xdsoft_datetimepicker'); if (datetimepicker) { datetimepicker.data('xdsoft_datetime', null); datetimepicker.remove(); input .data('xdsoft_datetimepicker', null) .off('.xdsoft'); $(window).off('resize.xdsoft'); $([window, document.body]).off('mousedown.xdsoft touchstart'); if (input.unmousewheel) { input.unmousewheel(); } } }; $(document) .off('keydown.xdsoftctrl keyup.xdsoftctrl') .on('keydown.xdsoftctrl', function (e) { if (e.keyCode === CTRLKEY) { ctrlDown = true; } }) .on('keyup.xdsoftctrl', function (e) { if (e.keyCode === CTRLKEY) { ctrlDown = false; } }); this.each(function () { var datetimepicker = $(this).data('xdsoft_datetimepicker'), $input; if (datetimepicker) { if ($.type(opt) === 'string') { switch (opt) { case 'show': $(this).select().focus(); datetimepicker.trigger('open.xdsoft'); break; case 'hide': datetimepicker.trigger('close.xdsoft'); break; case 'toggle': datetimepicker.trigger('toggle.xdsoft'); break; case 'destroy': destroyDateTimePicker($(this)); break; case 'reset': this.value = this.defaultValue; if (!this.value || !datetimepicker.data('xdsoft_datetime').isValidDate(dateHelper.parseDate(this.value, options.format))) { datetimepicker.data('changed', false); } datetimepicker.data('xdsoft_datetime').setCurrentTime(this.value); break; case 'validate': $input = datetimepicker.data('input'); $input.trigger('blur.xdsoft'); break; default: if (datetimepicker[opt] && $.isFunction(datetimepicker[opt])) { result = datetimepicker[opt](opt2); } } } else { datetimepicker .setOptions(opt); } return 0; } if ($.type(opt) !== 'string') { if (!options.lazyInit || options.open || options.inline) { createDateTimePicker($(this)); } else { lazyInit($(this)); } } }); return result; }; $.fn.datetimepicker.defaults = default_options; function HighlightedDate(date, desc, style) { "use strict"; this.date = date; this.desc = desc; this.style = style; } })); /*! * jQuery Mousewheel 3.1.13 * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license */ (function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }(function ($) { var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; if ( $.event.fixHooks ) { for ( var i = toFix.length; i; ) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } var special = $.event.special.mousewheel = { version: '3.1.12', setup: function() { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = handler; } // Store the line height and page height for this particular element $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); }, teardown: function() { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = null; } // Clean up the data we added to the element $.removeData(this, 'mousewheel-line-height'); $.removeData(this, 'mousewheel-page-height'); }, getLineHeight: function(elem) { var $elem = $(elem), $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); if (!$parent.length) { $parent = $('.page__wrapper'); } return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16; }, getPageHeight: function(elem) { return $(elem).height(); }, settings: { adjustOldDeltas: true, // see shouldAdjustOldDeltas() below normalizeOffset: true // calls getBoundingClientRect for each event } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); }, unmousewheel: function(fn) { return this.unbind('mousewheel', fn); } }); function handler(event) { var orgEvent = event || window.event, args = slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, offsetX = 0, offsetY = 0; event = $.event.fix(orgEvent); event.type = 'mousewheel'; // Old school scrollwheel delta if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) if ( 'deltaY' in orgEvent ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( 'deltaX' in orgEvent ) { deltaX = orgEvent.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } // No change actually happened, no reason to go any further if ( deltaY === 0 && deltaX === 0 ) { return; } // Need to convert lines and pages to pixels if we aren't already in pixels // There are three delta modes: // * deltaMode 0 is by pixels, nothing to do // * deltaMode 1 is by lines // * deltaMode 2 is by pages if ( orgEvent.deltaMode === 1 ) { var lineHeight = $.data(this, 'mousewheel-line-height'); delta *= lineHeight; deltaY *= lineHeight; deltaX *= lineHeight; } else if ( orgEvent.deltaMode === 2 ) { var pageHeight = $.data(this, 'mousewheel-page-height'); delta *= pageHeight; deltaY *= pageHeight; deltaX *= pageHeight; } // Store lowest absolute delta to normalize the delta values absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { lowestDelta /= 40; } } // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { // Divide all the things by 40! delta /= 40; deltaX /= 40; deltaY /= 40; } // Get a whole, normalized value for the deltas delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); // Normalise offsetX and offsetY properties if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { var boundingRect = this.getBoundingClientRect(); offsetX = event.clientX - boundingRect.left; offsetY = event.clientY - boundingRect.top; } // Add information to the event object event.deltaX = deltaX; event.deltaY = deltaY; event.deltaFactor = lowestDelta; event.offsetX = offsetX; event.offsetY = offsetY; // Go ahead and set deltaMode to 0 since we converted to pixels // Although this is a little odd since we overwrite the deltaX/Y // properties with normalized deltas. event.deltaMode = 0; // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); // Clearout lowestDelta after sometime to better // handle multiple device types that give different // a different lowestDelta // Ex: trackpad = 3 and mouse wheel = 120 if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); return ($.event.dispatch || $.event.handle).apply(this, args); } function nullLowestDelta() { lowestDelta = null; } function shouldAdjustOldDeltas(orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas // by 40 to try and get a more usable deltaFactor. // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; } }));
logics-layout/flufoods
markup/static/js/separate-js/jquery.datetimepicker.full.js
JavaScript
mit
114,711
using UnityEngine; using System.Collections; public class TextOutline : MonoBehaviour { public float pixelSize = 1; public int cloneCount = 8; public Color outlineColor = Color.black; public bool resolutionDependant = false; public int doubleResolution = 1024; public bool squareAlign = false; public bool updateAttributes; private TextMesh textMesh; private TextMesh[] childMeshes; private MeshRenderer[] childMeshRenderers; private MeshRenderer meshRenderer; void Start() { textMesh = GetComponent<TextMesh>(); meshRenderer = GetComponent<MeshRenderer>(); if (cloneCount != 8) squareAlign = false; childMeshes = new TextMesh[cloneCount]; childMeshRenderers = new MeshRenderer[cloneCount]; for (int i = 0; i < cloneCount; i++) { GameObject outline = new GameObject("outline", typeof(TextMesh)); outline.transform.parent = transform; outline.transform.localScale = new Vector3(1, 1, 1); MeshRenderer otherMeshRenderer = outline.GetComponent<MeshRenderer>(); otherMeshRenderer.material = new Material(meshRenderer.material); otherMeshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; otherMeshRenderer.receiveShadows = false; otherMeshRenderer.sortingLayerID = meshRenderer.sortingLayerID; otherMeshRenderer.sortingLayerName = meshRenderer.sortingLayerName; otherMeshRenderer.sortingOrder = meshRenderer.sortingOrder; childMeshRenderers[i] = otherMeshRenderer; childMeshes[i] = otherMeshRenderer.GetComponent<TextMesh>(); updateAttributes = true; } } void LateUpdate() { Vector3 screenPoint = MainCameraSingleton.instance.WorldToScreenPoint(transform.position); outlineColor.a = textMesh.color.a * textMesh.color.a; for (int i = 0; i < childMeshes.Length; i++) { TextMesh other = childMeshes[i]; other.text = textMesh.text; if (updateAttributes) { other.color = outlineColor; other.alignment = textMesh.alignment; other.anchor = textMesh.anchor; other.characterSize = textMesh.characterSize; other.font = textMesh.font; other.fontSize = textMesh.fontSize; other.fontStyle = textMesh.fontStyle; other.richText = textMesh.richText; other.tabSize = textMesh.tabSize; other.lineSpacing = textMesh.lineSpacing; other.offsetZ = textMesh.offsetZ; other.gameObject.layer = gameObject.layer; } bool doublePixel = resolutionDependant && (Screen.width > doubleResolution || Screen.height > doubleResolution); Vector3 pixelOffset = GetOffset(i) * (doublePixel ? 2.0f * getFunctionalPixelSize() : getFunctionalPixelSize()); Vector3 worldPoint = MainCameraSingleton.instance.ScreenToWorldPoint(screenPoint + (pixelOffset * ((float)Screen.currentResolution.width / 1400f))); other.transform.position = worldPoint + new Vector3(0f, 0f, .001f); MeshRenderer otherMeshRenderer = childMeshRenderers[i]; otherMeshRenderer.sortingLayerID = meshRenderer.sortingLayerID; otherMeshRenderer.sortingLayerName = meshRenderer.sortingLayerName; } } float getFunctionalPixelSize() { return pixelSize * 5f / MainCameraSingleton.instance.orthographicSize; } Vector3 GetOffset(int i) { if (squareAlign) return MathHelper.getVector2FromAngle(360f * ((float)i / (float)cloneCount), i % 2 == 0 ? 1f : Mathf.Sqrt(2f)); else return MathHelper.getVector2FromAngle(360f * ((float)i / (float)cloneCount), 1f); } }
NitorInc/NitoriWare
Assets/Scripts/UI/TextOutline.cs
C#
mit
3,734
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InjectedPackage.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Deployment.Core { /// <summary> /// Model object to track an injected package into a deployment. /// </summary> public class InjectedPackage { /// <summary> /// Initializes a new instance of the <see cref="InjectedPackage"/> class. /// </summary> /// <param name="reason">Reason for injection.</param> /// <param name="packagedConfig">Packaged config to add.</param> public InjectedPackage(string reason, PackagedDeploymentConfiguration packagedConfig) { this.Reason = reason; this.PackagedConfig = packagedConfig; } /// <summary> /// Gets the reason for adding the package. /// </summary> public string Reason { get; private set; } /// <summary> /// Gets the packaged config to add to deployment. /// </summary> public PackagedDeploymentConfiguration PackagedConfig { get; private set; } } }
NaosProject/Naos.Deployment
Naos.Deployment.Core/DeploymentAdjustment/InjectedPackage.cs
C#
mit
1,367
require([ "maplib/MapDrawer", "gaslib/Point" ], function(MapDrawer, Point){ QUnit.test( "a basic test example", function( assert ) { var element = document.getElementById("map"); var drawer = new MapDrawer(element); drawer.init(); drawer.drawMarker( new Point(52.23, 21.06), {} ); assert.equal( "got here", "got here", "We expect to get here" ); }); });
jeffreyjw/experimentA
testorial/tests/A beginner/2 markers/1 drawing markers/script.js
JavaScript
mit
449
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { fillRule: "evenodd", d: "M19.28 16.34c-1.21-.89-1.82-1.34-1.82-1.34s.32-.59.96-1.78c.38-.59 1.22-.59 1.6 0l.81 1.26c.19.3.21.68.06 1l-.22.47c-.25.54-.91.72-1.39.39zm-14.56 0c-.48.33-1.13.15-1.39-.38l-.23-.47c-.15-.32-.13-.7.06-1l.81-1.26c.38-.59 1.22-.59 1.6 0 .65 1.18.97 1.77.97 1.77s-.61.45-1.82 1.34zm10.64-6.97c.09-.68.73-1.06 1.27-.75l1.59.9c.46.26.63.91.36 1.41L16.5 15h-1.8l.66-5.63zm-6.73 0L9.3 15H7.5l-2.09-4.08c-.27-.5-.1-1.15.36-1.41l1.59-.9c.53-.3 1.18.08 1.27.76zM13.8 15h-3.6l-.74-6.88c-.07-.59.35-1.12.88-1.12h3.3c.53 0 .94.53.88 1.12L13.8 15z" }), 'BakeryDining'); exports.default = _default;
oliviertassinari/material-ui
packages/mui-icons-material/lib/BakeryDining.js
JavaScript
mit
1,025
/* * Copyright (c) 2016-2017 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System.Collections.Generic; namespace Piranha.Areas.Manager.Models { /// <summary> /// A collection region. /// </summary> public class PageEditRegionCollection : PageEditRegionBase { /// <summary> /// Gets/sets the available fieldsets. /// </summary> public IList<PageEditFieldSet> FieldSets { get; set; } /// <summary> /// Default constructor. /// </summary> public PageEditRegionCollection() { FieldSets = new List<PageEditFieldSet>(); } /// <summary> /// Adds a field set to the region. /// </summary> /// <param name="fieldSet">The field set</param> public override void Add(PageEditFieldSet fieldSet) { FieldSets.Add(fieldSet); } } }
filipjansson/piranha.core
core/Piranha.Manager/Areas/Manager/Models/PageEditRegionCollection.cs
C#
mit
1,045
<?php // Require CrudKit application require "crudkit/crudkit.php"; use CrudKit\CrudKitApp; use CrudKit\Pages\SQLiteTablePage; // Create a new CrudKitApp object $app = new CrudKitApp (); $page = new SQLiteTablePage ("sqlite2", "fixtures/chinook.sqlite"); $page->setName("Customer Management") ->setTableName("Customer") ->setPrimaryColumn("CustomerId") ->addColumn("FirstName", "First Name") ->addColumn("LastName", "Last Name") ->addColumn("City", "City") ->addColumn("Country", "Country") ->addColumn("Email", "E-mail") ->setSummaryColumns(array("FirstName", "Country")); $app->addPage($page); $invoice = new SQLiteTablePage ("sqlite1", "fixtures/chinook.sqlite"); $invoice->setName("Invoice") ->setPrimaryColumnWithId("a0", "InvoiceId") ->setTableName("Invoice") ->addColumnWithId("a1", "BillingCity", "City") ->addColumnWithId("a2", "BillingCountry", "Country") ->addColumnWithId("a3", "Total", "Total") ->addColumnWithId("a4", "InvoiceDate", "Date", array( )) ->setSummaryColumns(["a1", "a2", "a3", "a4"]); $app->addPage($invoice); // Render the app. This will display the HTML $app->render (); ?>
najiji/crudkit
demo/sql_basic.php
PHP
mit
1,171
// Author(s) : Pierre Alliez #include <iostream> #include <CGAL/Simple_cartesian.h> #include <CGAL/AABB_tree.h> #include <CGAL/AABB_traits.h> #include <CGAL/Polyhedron_3.h> #include <CGAL/AABB_face_graph_triangle_primitive.h> typedef CGAL::Simple_cartesian<double> K; typedef K::FT FT; typedef K::Point_3 Point; typedef K::Segment_3 Segment; typedef CGAL::Polyhedron_3<K> Polyhedron; typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive; typedef CGAL::AABB_traits<K, Primitive> Traits; typedef CGAL::AABB_tree<Traits> Tree; typedef Tree::Point_and_primitive_id Point_and_primitive_id; int main() { Point p(1.0, 0.0, 0.0); Point q(0.0, 1.0, 0.0); Point r(0.0, 0.0, 1.0); Point s(0.0, 0.0, 0.0); Polyhedron polyhedron; polyhedron.make_tetrahedron(p, q, r, s); // constructs AABB tree and computes internal KD-tree // data structure to accelerate distance queries Tree tree(polyhedron.facets_begin(),polyhedron.facets_end(),polyhedron); tree.accelerate_distance_queries(); // query point Point query(0.0, 0.0, 3.0); // computes squared distance from query FT sqd = tree.squared_distance(query); std::cout << "squared distance: " << sqd << std::endl; // computes closest point Point closest = tree.closest_point(query); std::cout << "closest point: " << closest << std::endl; // computes closest point and primitive id Point_and_primitive_id pp = tree.closest_point_and_primitive(query); Point closest_point = pp.first; Polyhedron::Face_handle f = pp.second; // closest primitive id std::cout << "closest point: " << closest_point << std::endl; std::cout << "closest triangle: ( " << f->halfedge()->vertex()->point() << " , " << f->halfedge()->next()->vertex()->point() << " , " << f->halfedge()->next()->next()->vertex()->point() << " )" << std::endl; return EXIT_SUCCESS; }
alexandrustaetu/natural_editor
external/CGAL-4.4-beta1/examples/AABB_tree/AABB_polyhedron_facet_distance_example.cpp
C++
mit
1,958
import { messages, ruleName, } from ".." import rules from "../../../rules" import { testRule } from "../../../testUtils" const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "@import url(x.css)", }, { code: "a { color: pink; }", }, { code: "@media print { a { color: pink; } }", }, { code: "a {{ &:hover { color: pink; }}}", }, { code: "a {\n&:hover { color: pink; }}", } ], reject: [ { code: "a{ color: pink; }", message: messages.expectedBefore(), line: 1, column: 1, }, { code: "a { color: pink; }", message: messages.expectedBefore(), line: 1, column: 3, }, { code: "a\t{ color: pink; }", message: messages.expectedBefore(), line: 1, column: 2, }, { code: "a\n{ color: pink; }", message: messages.expectedBefore(), line: 1, column: 2, }, { code: "a\r\n{ color: pink; }", description: "CRLF", message: messages.expectedBefore(), line: 1, column: 2, }, { code: "@media print\n{ a { color: pink; } }", message: messages.expectedBefore(), line: 1, column: 13, }, { code: "@media print { a\n{ color: pink; } }", message: messages.expectedBefore(), line: 1, column: 17, } ], }) testRule(rule, { ruleName, config: [ "always", { ignoreAtRules: ["for"] } ], accept: [ { code: "a { color: pink; }", }, { code: "@for ...\n{ color: pink; }", }, { code: "@for ...\r\n{ color: pink; }", } ], reject: [{ code: "a{ color: pink; }", message: messages.expectedBefore(), line: 1, column: 1, }], }) testRule(rule, { ruleName, config: [ "always", { ignoreAtRules: "/fo/" } ], accept: [ { code: "a { color: pink; }", }, { code: "@for ...\n{ color: pink; }", }, { code: "@for ...\r\n{ color: pink; }", } ], reject: [{ code: "a{ color: pink; }", message: messages.expectedBefore(), line: 1, column: 1, }], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a{ color: pink; }", }, { code: "@media print{ a{ color: pink; } }", } ], reject: [ { code: "a { color: pink; }", message: messages.rejectedBefore(), line: 1, column: 2, }, { code: "a { color: pink; }", message: messages.rejectedBefore(), line: 1, column: 3, }, { code: "a\t{ color: pink; }", message: messages.rejectedBefore(), line: 1, column: 2, }, { code: "a\n{ color: pink; }", message: messages.rejectedBefore(), line: 1, column: 2, }, { code: "a\r\n{ color: pink; }", description: "CRLF", message: messages.rejectedBefore(), line: 1, column: 2, }, { code: "@media print { a{ color: pink; } }", message: messages.rejectedBefore(), line: 1, column: 13, }, { code: "@media print{ a { color: pink; } }", message: messages.rejectedBefore(), line: 1, column: 16, } ], }) testRule(rule, { ruleName, config: ["always-single-line"], accept: [ { code: "a { color: pink; }", }, { code: "@media print { a { color: pink; } }", }, { code: "a{ color:\npink; }", }, { code: "@media print { a{ color:\npink; } }", }, { code: "@media print{ a { color:\npink; } }", }, { code: "@media print{\na { color: pink; } }", } ], reject: [ { code: "a{ color: pink; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 1, }, { code: "a { color: pink; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 3, }, { code: "a\t{ color: pink; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 2, }, { code: "a\n{ color: pink; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 2, }, { code: "a\r\n{ color: pink; }", description: "CRLF", message: messages.expectedBeforeSingleLine(), line: 1, column: 2, }, { code: "@media print\n{ a { color: pink; } }", message: messages.expectedBeforeSingleLine(), line: 1, column: 13, }, { code: "@media print { a\n{ color: pink; } }", message: messages.expectedBeforeSingleLine(), line: 1, column: 17, } ], }) testRule(rule, { ruleName, config: ["never-single-line"], accept: [ { code: "a{ color: pink; }", }, { code: "@media print{ a{ color: pink; } }", }, { code: "a { color:\npink; }", }, { code: "a { color:\r\npink; }", description: "CRLF", }, { code: "@media print { a { color:\npink; } }", }, { code: "@media print{ a{ color:\npink; } }", }, { code: "@media print {\na{ color: pink; } }", }, { code: "@media print{\na{ color: pink; } }", }, { code: "@media print{\r\na{ color: pink; } }", description: "CRLF", } ], reject: [ { code: "a { color: pink; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 2, }, { code: "a { color: pink; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 3, }, { code: "a\t{ color: pink; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 2, }, { code: "a\n{ color: pink; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 2, }, { code: "a\r\n{ color: pink; }", description: "CRLF", message: messages.rejectedBeforeSingleLine(), line: 1, column: 2, }, { code: "@media print { a{ color: pink; } }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 13, }, { code: "@media print{ a { color: pink; } }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 16, } ], }) testRule(rule, { ruleName, config: ["always-multi-line"], accept: [ { code: "a { color: pink;\nbackground: orange; }", }, { code: "@media print {\na { color: pink;\nbackground: orange } }", }, { code: "@media print {\r\na { color: pink;\r\nbackground: orange } }", description: "CRLF", }, { code: "a { color: pink; }", }, { code: "@media print { a { color: pink; } }", }, { code: "a{ color: pink; }", }, { code: "a { color: pink; }", }, { code: "a\t{ color: pink; }", } ], reject: [ { code: "a{ color: pink;\nbackground: orange; }", message: messages.expectedBeforeMultiLine(), line: 1, column: 1, }, { code: "a { color: pink;\nbackground: orange; }", message: messages.expectedBeforeMultiLine(), line: 1, column: 3, }, { code: "a\t{ color: pink;\nbackground: orange; }", message: messages.expectedBeforeMultiLine(), line: 1, column: 2, }, { code: "a\n{ color: pink;\nbackground: orange; }", message: messages.expectedBeforeMultiLine(), line: 1, column: 2, }, { code: "a\r\n{ color: pink;\r\nbackground: orange; }", description: "CRLF", message: messages.expectedBeforeMultiLine(), line: 1, column: 2, }, { code: "@media print\n{\na { color: pink;\nbackground: orange; } }", message: messages.expectedBeforeMultiLine(), line: 1, column: 13, }, { code: "@media print { a\n{ color: pink;\nbackground: orange; } }", message: messages.expectedBeforeMultiLine(), line: 1, column: 17, } ], }) testRule(rule, { ruleName, config: ["never-multi-line"], accept: [ { code: "a{ color: pink;\nbackground: orange; }", }, { code: "@media print{\na{ color: pink;\nbackground: orange } }", }, { code: "@media print{\r\na{ color: pink;\r\nbackground: orange } }", description: "CRLF", }, { code: "a { color: pink; }", }, { code: "@media print { a { color: pink; } }", }, { code: "a{ color: pink; }", }, { code: "a { color: pink; }", }, { code: "a\t{ color: pink; }", } ], reject: [ { code: "a { color: pink;\nbackground: orange; }", message: messages.rejectedBeforeMultiLine(), line: 1, column: 2, }, { code: "a { color: pink;\nbackground: orange; }", message: messages.rejectedBeforeMultiLine(), line: 1, column: 3, }, { code: "a\t{ color: pink;\nbackground: orange; }", message: messages.rejectedBeforeMultiLine(), line: 1, column: 2, }, { code: "a\n{ color: pink;\nbackground: orange; }", message: messages.rejectedBeforeMultiLine(), line: 1, column: 2, }, { code: "@media print\n{\na{ color: pink;\nbackground: orange; } }", message: messages.rejectedBeforeMultiLine(), line: 1, column: 13, }, { code: "@media print{ a\n{ color: pink;\nbackground: orange; } }", message: messages.rejectedBeforeMultiLine(), line: 1, column: 16, }, { code: "@media print{ a\r\n{ color: pink;\r\nbackground: orange; } }", description: "CRLF", message: messages.rejectedBeforeMultiLine(), line: 1, column: 16, } ], })
gaidarenko/stylelint
src/rules/block-opening-brace-space-before/__tests__/index.js
JavaScript
mit
8,936
require 'spec_helper' describe WishItemsController do render_views it "redirect to login if no current_user" do get :index response.should redirect_to(login_url) end end describe WishItemsController do render_views before(:each) do activate_authlogic @cur_user = create(:user) login_as(@cur_user) @variant = create(:variant) @wish_item = create(:cart_item, :item_type_id => ItemType::WISH_LIST_ID, :user_id => @cur_user.id, :variant => @variant) end it "index action should render index template" do get :index response.should render_template(:index) end it "destroy action should render index template" do delete :destroy, :id => @wish_item.id, :variant_id => @variant.id expect(CartItem.find(@wish_item.id).active).to eq false response.should render_template(:index) end end
PrabhakarUndurthi/ror_ecommerce
spec/controllers/wish_items_controller_spec.rb
Ruby
mit
851
package com.vsked.test; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class TestMapCompareMap { public static void main(String[] args) { Map<String, String> m1=new TreeMap<String, String>(); Map<String, String> m2=new TreeMap<String, String>(); m1.put("a", "1"); m1.put("b", "2"); m1.put("c", "3"); m1.put("c", "ft"); m2.put("a", "1"); m2.put("b", "2"); m2.put("c", "3"); System.out.println("---------"+m1.get("c")); System.out.println(m1.size()); System.out.println(m2.size()); System.out.println(m1.keySet().size()); System.out.println(m2.keySet().size()); System.out.println(isSameMap(m1, m2)); } public static boolean isSameMap(Map<String, String> m1,Map<String, String> m2){ boolean flag=true; Iterator<Map.Entry<String, String>> it = m1.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String, String> e = it.next(); if((!m2.containsKey(e.getKey())) || (!m2.containsValue(e.getValue()))) return false; } return flag; } }
brucevsked/vskeddemolist
vskeddemos/projects/testdemo/src/com/vsked/test/TestMapCompareMap.java
Java
mit
1,095
<!DOCTYPE html> <html> <head> <meta name="renderer" content="webkit"> <meta name="force-rendering" content="webkit"> <meta http-equiv="X-UA-Compatible" content="chrome=1,IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>管理后台--框架</title> <?php $this->load->view('admin/admin_header'); ?> </head> <body> <div id="pagebody"> <div id="header"> <?php $this->load->view('admin/admin_top'); ?> </div> <section> <div class="body-width"> <!--for ie border--> <div class="body-content"> <div class="leftArea" id="leftArea" style="width:15%; min-width:220px;"> <?php $this->load->view('admin/admin_menu'); ?> </div> <div id="jmreport-page"> <div id="jmreport-page-title"> <div class="jmreport-pageTitle">编辑</div> </div> <div> <form action="<?php echo base_url('index.php/admin/framework/framework_edit'); ?>" method="post"> <table> <input type="hidden" name="id" value="<?php echo $framework_info['id']; ?>"> <tr> <td>名称:<input type="text" name="frameworkname" value="<?php echo $framework_info['displayname']; ?>" /></td> </tr> <tr> <td colspan=2> <input type="submit" /> </td> </tr> </table> </form> </div> </div> <div class="clear"></div> </div> <div id="app_sel_body" class="sel-body"> </div> <div id="go-top" style="position:fixed;display:none;" title="回到顶部"> <a href="#" onclick="javascript:window.scrollTo(0,0);return false;"> <img src="<?php echo base_url('static/img/go-up.png')?>" alt="回到顶部" /> </a> </div> </div> </section> <div id="footer"> <ul> <li class="copyright">Copyright 2014</li> <li>JM</li> <li><a href="../admin/index.aspx" target="_blank">管理端</a></li> </ul> </div> </div> </body> <script type="text/javascript"> $(function () { $(window).resize(function () { $('#go-top').css({ "top": ($(window).height() - $("#go-top").height()), "left": $(window).width() - $("#go-top").width() - 2 }); }); $(window).scroll(function () { if ($(window).scrollTop() > 50) { $('#go-top').show(); }else { $('#go-top').hide(); } }); }); </script> </html>
shadowinlife/biplatform
application/views/admin/framework_edit.php
PHP
mit
2,653
module DeviceDeactivatable autoload :Mapping, 'devise_deactivatable/mapping' module Controllers autoload :Helpers, 'devise_deactivatable/controllers/helpers' end end require 'devise' require 'devise_deactivatable/routes' require 'devise_deactivatable/rails' Devise.add_module :deactivatable, :controller => :deactivate, :model => 'devise_deactivatable/model', :route => { :deactivate => [ :create ] }
dreamwords/devise_deactivatable
lib/devise_deactivatable.rb
Ruby
mit
413
<?php App::uses('CrudBaseObject', 'Crud.Controller/Crud'); App::uses('Hash', 'Utility'); App::uses('Validation', 'Utility'); /** * Base Crud class * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE.txt */ abstract class CrudAction extends CrudBaseObject { /** * Constant representing a model-level action * * @var integer */ const SCOPE_MODEL = 0; /** * Constant representing a record-level action * * @var integer */ const SCOPE_RECORD = 1; /** * Startup method * * Called when the action is loaded * * @param CrudSubject $subject * @param array $defaults * @return void */ public function __construct(CrudSubject $subject, array $defaults = array()) { parent::__construct($subject, $defaults); $this->_settings['action'] = $subject->action; } /** * Handle callback * * Based on the requested controller action, * decide if we should handle the request or not. * * By returning false the handling is cancelled and the * execution flow continues * * @throws NotImplementedException if the action can't handle the request * @param CakeEvent $event * @return mixed */ public function handle(CrudSubject $subject) { if (!$this->config('enabled')) { return false; } $requestMethod = $this->_request()->method(); $method = '_' . strtolower($requestMethod); if (method_exists($this, $method)) { return call_user_func_array(array($this, $method), $subject->args); } if (method_exists($this, '_handle')) { return call_user_func_array(array($this, '_handle'), $subject->args); } throw new NotImplementedException(sprintf('Action %s does not implement a handler for HTTP verb %s', get_class($this), $requestMethod)); } /** * Disable the Crud action * * @return void */ public function disable() { $this->config('enabled', false); $Controller = $this->_controller(); $actionName = $this->config('action'); $pos = array_search($actionName, $Controller->methods); if ($pos !== false) { unset($Controller->methods[$pos]); } } /** * Enable the Crud action * * @return void */ public function enable() { $this->config('enabled', true); $Controller = $this->_controller(); $actionName = $this->config('action'); if (!in_array($actionName, $Controller->methods)) { $Controller->methods[] = $actionName; } } /** * Change the find() method * * If `$method` is NULL the current value is returned * else the `findMethod` is changed * * @param mixed $method * @return mixed */ public function findMethod($method = null) { if ($method === null) { return $this->config('findMethod'); } return $this->config('findMethod', $method); } /** * Change the save() method * * If `$method` is NULL the current value is returned * else the `saveMethod` is changed * * @param mixed $method * @return mixed */ public function saveMethod($method = null) { if ($method === null) { return $this->config('saveMethod'); } return $this->config('saveMethod', $method); } /** * Set or get the related models that should be found * for the action * * @param mixed $related Everything but `null` will change the configuration * @return mixed */ public function relatedModels($related = null) { if ($related === null) { return $this->config('relatedModels'); } return $this->config('relatedModels', $related, false); } /** * Change redirect configuration * * If both `$name` and `$config` is empty all redirection * rules will be returned. * * If `$name` is provided and `$config` is null, the named * redirection configuration is returned. * * If both `$name` and `$config` is provided, the configuration * is changed for the named rule. * * $config should contain the following keys: * - type : name of the reader * - key : the key to read inside the reader * - url : the URL to redirect to * * @param null|string $name Name of the redirection rule * @param null|array $config Redirection configuration * @return mixed */ public function redirectConfig($name = null, $config = null) { if ($name === null && $config === null) { return $this->config('redirect'); } $path = sprintf('redirect.%s', $name); if ($config === null) { return $this->config($path); } return $this->config($path, $config); } /** * return the config for a given message type * * @param string $type * @param array $replacements * @return array * @throws CakeException for a missing or undefined message type */ public function message($type, array $replacements = array()) { if (empty($type)) { throw new CakeException('Missing message type'); } $crud = $this->_crud(); $config = $this->config('messages.' . $type); if (empty($config)) { $config = $crud->config('messages.' . $type); if (empty($config)) { throw new CakeException(sprintf('Invalid message type "%s"', $type)); } } if (is_string($config)) { $config = array('text' => $config); } $config = Hash::merge(array( 'element' => 'default', 'params' => array('class' => 'message'), 'key' => 'flash', 'type' => $this->config('action') . '.' . $type, 'name' => $this->_getResourceName() ), $config); if (!isset($config['text'])) { throw new CakeException(sprintf('Invalid message config for "%s" no text key found', $type)); } $config['params']['original'] = ucfirst(str_replace('{name}', $config['name'], $config['text'])); $domain = $this->config('messages.domain'); if (!$domain) { $domain = $crud->config('messages.domain') ?: 'crud'; } $config['text'] = __d($domain, $config['params']['original']); $config['text'] = String::insert( $config['text'], $replacements + array('name' => $config['name']), array('before' => '{', 'after' => '}') ); $config['params']['class'] .= ' ' . $type; return $config; } /** * Change the saveOptions configuration * * This is the 2nd argument passed to saveAll() * * if `$config` is NULL the current config is returned * else the `saveOptions` is changed * * @param mixed $config * @return mixed */ public function saveOptions($config = null) { if (empty($config)) { return $this->config('saveOptions'); } return $this->config('saveOptions', $config); } /** * Change the view to be rendered * * If `$view` is NULL the current view is returned * else the `$view` is changed * * If no view is configured, it will use the action * name from the request object * * @param mixed $view * @return mixed */ public function view($view = null) { if (empty($view)) { return $this->config('view') ?: $this->_request()->action; } return $this->config('view', $view); } /** * List of implemented events * * @return array */ public function implementedEvents() { return array(); } /** * Get the model find method for a current controller action * * @param string $default The default find method in case it hasn't been mapped * @return string The find method used in ->_model->find($method) */ protected function _getFindMethod($default = null) { $findMethod = $this->findMethod(); if (!empty($findMethod)) { return $findMethod; } return $default; } /** * Wrapper for Session::setFlash * * @param string $type Message type * @return void */ public function setFlash($type) { $config = $this->message($type); $subject = $this->_trigger('setFlash', $config); if (!empty($subject->stopped)) { return; } $this->_session()->setFlash($subject->text, $subject->element, $subject->params, $subject->key); } /** * Automatically detect primary key data type for `_validateId()` * * Binary or string with length of 36 chars will be detected as UUID * If the primary key is a number, integer validation will be used * * If no reliable detection can be made, no validation will be made * * @param Model $model * @return string * @throws CakeException If unable to get model object */ public function detectPrimaryKeyFieldType(Model $model = null) { if (empty($model)) { $model = $this->_model(); if (empty($model)) { throw new CakeException('Missing model object, cant detect primary key field type'); } } $fInfo = $model->schema($model->primaryKey); if (empty($fInfo)) { return false; } if ($fInfo['length'] == 36 && ($fInfo['type'] === 'string' || $fInfo['type'] === 'binary')) { return 'uuid'; } if ($fInfo['type'] === 'integer') { return 'integer'; } return false; } /** * Return the human name of the model * * By default it uses Inflector::humanize, but can be changed * using the "name" configuration property * * @return string */ protected function _getResourceName() { if (empty($this->_settings['name'])) { $this->_settings['name'] = strtolower(Inflector::humanize(Inflector::underscore($this->_model()->name))); } return $this->_settings['name']; } /** * Is the passed ID valid ? * * By default we assume you want to validate an numeric string * like a normal incremental ids from MySQL * * Change the validateId settings key to "uuid" for UUID check instead * * @param mixed $id * @return boolean * @throws BadRequestException If id is invalid */ protected function _validateId($id) { $type = $this->config('validateId'); if ($type === null) { $type = $this->detectPrimaryKeyFieldType(); } if (!$type) { return true; } elseif ($type === 'uuid') { $valid = Validation::uuid($id); } else { $valid = is_numeric($id); } if ($valid) { return true; } $subject = $this->_trigger('invalidId', compact('id')); $message = $this->message('invalidId'); $exceptionClass = $message['class']; throw new $exceptionClass($message['text'], $message['code']); } /** * Called for all redirects inside CRUD * * @param CrudSubject $subject * @param string|array $url * @param integer $status * @param boolean $exit * @return void */ protected function _redirect(CrudSubject $subject, $url = null, $status = null, $exit = true) { $url = $this->_redirectUrl($url); $subject->url = $url; $subject->status = $status; $subject->exit = $exit; $subject = $this->_trigger('beforeRedirect', $subject); $controller = $this->_controller(); $controller->redirect($subject->url, $subject->status, $subject->exit); return $controller->response; } }
simkimsia/cake-with-crud
plugins/Crud/Controller/Crud/CrudAction.php
PHP
mit
10,382
# frozen_string_literal: true Capybara.register_driver :rack_test do |app| Capybara::RackTest::Driver.new(app) end Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app) end Capybara.register_driver :selenium_headless do |app| version = Capybara::Selenium::Driver.load_selenium options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options browser_options = ::Selenium::WebDriver::Firefox::Options.new.tap do |opts| opts.add_argument '-headless' end Capybara::Selenium::Driver.new(app, **{ :browser => :firefox, options_key => browser_options }) end Capybara.register_driver :selenium_chrome do |app| version = Capybara::Selenium::Driver.load_selenium options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options browser_options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts| # Workaround https://bugs.chromium.org/p/chromedriver/issues/detail?id=2650&q=load&sort=-id&colspec=ID%20Status%20Pri%20Owner%20Summary opts.add_argument('--disable-site-isolation-trials') end Capybara::Selenium::Driver.new(app, **{ :browser => :chrome, options_key => browser_options }) end Capybara.register_driver :selenium_chrome_headless do |app| version = Capybara::Selenium::Driver.load_selenium options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options browser_options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts| opts.add_argument('--headless') opts.add_argument('--disable-gpu') if Gem.win_platform? # Workaround https://bugs.chromium.org/p/chromedriver/issues/detail?id=2650&q=load&sort=-id&colspec=ID%20Status%20Pri%20Owner%20Summary opts.add_argument('--disable-site-isolation-trials') end Capybara::Selenium::Driver.new(app, **{ :browser => :chrome, options_key => browser_options }) end
teamcapybara/capybara
lib/capybara/registrations/drivers.rb
Ruby
mit
1,932
<!DOCTYPE html> <html lang="hu"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Fishing on Orfű</title> <link rel="icon" type="image/png" sizes="32x32" href="<?php echo get_template_directory_uri(); ?>/assets/img/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="<?php echo get_template_directory_uri(); ?>/assets/img/favicon-16x16.png"> <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/assets/css/style.css"> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <?php wp_head(); ?> </head> <body <?php body_class( $class ); ?>> <div class="page-container"> <header class="header"> <div class="trigger-wrapper"> <button class="nav-trigger">Menü</button> </div> <div class="inner-wrapper"> <nav role="navigation"> <!--<ul class="header__menu nostyle"> <li><a href="#">Friss</a></li> <li><a href="#">Program</a></li> <li><a href="#">Jegy</a></li> <li><a href="#">Info</a></li> <li><a href="#">Sajtó</a></li> <li><a href="#">Támogatók</a></li> </ul>--> <?php wp_nav_menu( array( 'theme_location' => 'header-menu', 'container_class' => 'header__menu' ) ); ?> </nav> <ul class="social nostyle"> <li><a href="https://www.facebook.com/fishingonorfu" class="icon i-fb" target="_blank">Facebook</a></li> <li><a href="http://instagram.com/fishingonorfu" class="icon i-ins" target="_blank">Instagram</a></li> <li><a href="https://twitter.com/fishingonorfu12" class="icon i-twt" target="_blank">Twitter</a></li> <li><a href="https://www.youtube.com/user/FishingOnOrfuFeszt" class="icon i-yt" target="_blank">YouTube</a></li> </ul> <a href="/" class="logo"> <img src="<?php echo get_template_directory_uri(); ?>/assets/img/fishing_logo.png" alt="Fishing on Orfű"> </a> </div> </header>
akosszasz/akosszasz.github.io
fishing2021/wp-content/themes/fishing/header.php
PHP
mit
2,147
'use strict'; /** * Module dependencies. */ var mapsPolicy = require('../policies/maps.server.policy'), maps = require('../controllers/maps.server.controller'); module.exports = function(app) { // Articles collection routes app.route('/api/maps').all(mapsPolicy.isAllowed) .get(maps.list) .post(maps.create); // Single map routes app.route('/api/maps/:mapId').all(mapsPolicy.isAllowed) .get(maps.read) .put(maps.update) .delete(maps.delete); // Finish by binding the map middleware app.param('mapId', maps.mapByID); };
mezae/pfpundergrads
modules/articles/server/routes/maps.server.routes.js
JavaScript
mit
592
<?php /* FOSUserBundle:Profile:edit_content.html.twig */ class __TwigTemplate_1d7755141c036cceb13974c4038fc4adbd4b136a6e899c7c3bf5cd8b840dc4f7 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 2 echo " <form action=\""; // line 3 echo $this->env->getExtension('routing')->getPath("fos_user_profile_edit"); echo "\" "; echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype'); echo " method=\"POST\" class=\"fos_user_profile_edit\"> "; // line 4 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget'); echo " <div> <input type=\"submit\" value=\""; // line 6 echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("profile.edit.submit", array(), "FOSUserBundle"), "html", null, true); echo "\" /> </div> </form> "; } public function getTemplateName() { return "FOSUserBundle:Profile:edit_content.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 33 => 6, 28 => 4, 22 => 3, 19 => 2,); } }
paskalov/dvdworld
app/cache/dev/twig/1d/77/55141c036cceb13974c4038fc4adbd4b136a6e899c7c3bf5cd8b840dc4f7.php
PHP
mit
1,627
/******************************************************************************************************* This file was auto generated with the tool "WebIDLParser" Content was generated from IDL file: http://trac.webkit.org/browser/trunk/Source/WebCore/html/HTMLParamElement.idl PLEASE DO *NOT* MODIFY THIS FILE! This file will be overridden next generation. If you need changes: - All classes marked as "partial". Use the custom.cs in the root folder, to extend the classes. - or regenerate the project with the newest IDL files. - or modifiy the WebIDLParser tool itself. ******************************************************************************************************** Copyright (C) 2014 Sebastian Loncar, Web: http://loncar.de Copyright (C) 2009 Apple Inc. All Rights Reserved. MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************************************/ using System; namespace SharpKit.Html { using SharpKit.JavaScript; using SharpKit.Html.fileapi; using SharpKit.Html.html.shadow; using SharpKit.Html.html.track; using SharpKit.Html.inspector; using SharpKit.Html.loader.appcache; using SharpKit.Html.battery; using SharpKit.Html.filesystem; using SharpKit.Html.gamepad; using SharpKit.Html.geolocation; using SharpKit.Html.indexeddb; using SharpKit.Html.intents; using SharpKit.Html.mediasource; using SharpKit.Html.mediastream; using SharpKit.Html.navigatorcontentutils; using SharpKit.Html.networkinfo; using SharpKit.Html.notifications; using SharpKit.Html.proximity; using SharpKit.Html.quota; using SharpKit.Html.speech; using SharpKit.Html.vibration; using SharpKit.Html.webaudio; using SharpKit.Html.webdatabase; using SharpKit.Html.plugins; using SharpKit.Html.storage; using SharpKit.Html.svg; using SharpKit.Html.workers; [JsType(JsMode.Prototype, Export = false, PropertiesAsFields = true, NativeCasts = true, Name = "HTMLParamElement")] public partial class HtmlParamElement : HtmlElement { [JsMethod(OmitParanthesis = true, OmitNewOperator = true, Name = "document.createElement('param')")] public HtmlParamElement() {} public JsString name {get; set; } public JsString type {get; set; } public JsString value {get; set; } public JsString valueType {get; set; } } }
SharpKit/SharpKit-SDK
Defs/Html/generated/html/HTMLParamElement.cs
C#
mit
3,327
# frozen_string_literal: true require 'shrine' require 'shrine/storage/file_system' require 'ckeditor/backend/shrine' # Choose your favorite image processor require 'image_processing/mini_magick' SHRINE_PICTURE_PROCESSOR = ImageProcessing::MiniMagick # require 'image_processing/vips' # SHRINE_PICTURE_PROCESSOR = ImageProcessing::Vips Shrine.storages = { cache: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/cache'), store: Shrine::Storage::FileSystem.new('public', prefix: 'system') } Shrine.plugin :determine_mime_type Shrine.plugin :mongoid Shrine.plugin :instrumentation Shrine.plugin :validation_helpers Shrine.plugin :processing Shrine.plugin :versions
galetahub/ckeditor
lib/generators/ckeditor/templates/base/shrine/initializer.rb
Ruby
mit
683
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundFieldAccess { public BoundFieldAccess( SyntaxNode syntax, BoundExpression receiver, FieldSymbol fieldSymbol, ConstantValue constantValueOpt, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, LookupResultKind.Viable, fieldSymbol.Type, hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression receiver, FieldSymbol fieldSymbol, ConstantValue constantValueOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: false, type: type, hasErrors: hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression receiver, FieldSymbol fieldSymbol, ConstantValue constantValueOpt, LookupResultKind resultKind, bool isDeclaration, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: isDeclaration, type: type, hasErrors: hasErrors) { } public BoundFieldAccess Update( BoundExpression receiver, FieldSymbol fieldSymbol, ConstantValue constantValueOpt, LookupResultKind resultKind, TypeSymbol typeSymbol) { return this.Update(receiver, fieldSymbol, constantValueOpt, resultKind, this.IsByValue, this.IsDeclaration, typeSymbol); } private static bool NeedsByValueFieldAccess(BoundExpression receiver, FieldSymbol fieldSymbol) { if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsValueType || (object)receiver == null) // receiver may be null in error cases { return false; } switch (receiver.Kind) { case BoundKind.FieldAccess: return ((BoundFieldAccess)receiver).IsByValue; case BoundKind.Local: var localSymbol = ((BoundLocal)receiver).LocalSymbol; return !(localSymbol.IsWritableVariable || localSymbol.IsRef); default: return false; } } } internal partial class BoundCall { #nullable enable public BoundCall( SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, resultKind, originalMethodsOpt: default, binderOpt, type, hasErrors) { } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, LookupResultKind resultKind, Binder? binderOpt, TypeSymbol type) => Update(receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, resultKind, this.OriginalMethodsOpt, binderOpt, type); #nullable restore public static BoundCall ErrorCall( SyntaxNode node, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, bool isDelegateCall, bool invokedAsExtensionMethod, ImmutableArray<MethodSymbol> originalMethods, LookupResultKind resultKind, Binder binder) { if (!originalMethods.IsEmpty) resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); Debug.Assert(arguments.IsDefaultOrEmpty || (object)receiverOpt != (object)arguments[0]); return new BoundCall( syntax: node, receiverOpt: binder.BindToTypeForErrorRecovery(receiverOpt), method: method, arguments: arguments.SelectAsArray((e, binder) => binder.BindToTypeForErrorRecovery(e), binder), argumentNamesOpt: namedArguments, argumentRefKindsOpt: refKinds, isDelegateCall: isDelegateCall, expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray<int>), resultKind: resultKind, originalMethodsOpt: originalMethods, binderOpt: binder, type: method.ReturnType, hasErrors: true); } public BoundCall Update(ImmutableArray<BoundExpression> arguments) { return this.Update(ReceiverOpt, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, ResultKind, OriginalMethodsOpt, BinderOpt, Type); } public BoundCall Update(BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, ResultKind, OriginalMethodsOpt, BinderOpt, Type); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method) { return Synthesized(syntax, receiverOpt, method, ImmutableArray<BoundExpression>.Empty); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method, BoundExpression arg0) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method, BoundExpression arg0, BoundExpression arg1) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0, arg1)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return new BoundCall(syntax, receiverOpt, method, arguments, argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: method.ParameterRefKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray<int>), resultKind: LookupResultKind.Viable, originalMethodsOpt: default, binderOpt: null, type: method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol ) { WasCompilerGenerated = true }; } } internal sealed partial class BoundObjectCreationExpression { public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, Binder binderOpt, params BoundExpression[] arguments) : this(syntax, constructor, ImmutableArray.Create<BoundExpression>(arguments), default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), null, null, binderOpt, constructor.ContainingType) { } public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, Binder binderOpt, ImmutableArray<BoundExpression> arguments) : this(syntax, constructor, arguments, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), null, null, binderOpt, constructor.ContainingType) { } } internal partial class BoundIndexerAccess { public static BoundIndexerAccess ErrorAccess( SyntaxNode node, BoundExpression receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, ImmutableArray<PropertySymbol> originalIndexers) { return new BoundIndexerAccess( node, receiverOpt, indexer, arguments, namedArguments, refKinds, expanded: false, argsToParamsOpt: default(ImmutableArray<int>), binderOpt: null, useSetterForDefaultArgumentGeneration: false, originalIndexers, type: indexer.Type, hasErrors: true); } #nullable enable public BoundIndexerAccess( SyntaxNode syntax, BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, Binder? binderOpt, bool useSetterForDefaultArgumentGeneration, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, binderOpt, useSetterForDefaultArgumentGeneration, originalIndexersOpt: default, type, hasErrors) { } public BoundIndexerAccess Update(BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, Binder? binderOpt, bool useSetterForDefaultArgumentGeneration, TypeSymbol type) => Update(receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, binderOpt, useSetterForDefaultArgumentGeneration, this.OriginalIndexersOpt, type); #nullable restore } internal sealed partial class BoundConversion { /// <remarks> /// This method is intended for passes other than the LocalRewriter. /// Use MakeConversion helper method in the LocalRewriter instead, /// it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion SynthesizedNonUserDefined(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type, ConstantValue constantValueOpt = null) { return new BoundConversion( syntax, operand, conversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: constantValueOpt, originalUserDefinedConversionsOpt: default, type: type) { WasCompilerGenerated = true }; } /// <remarks> /// NOTE: This method is intended for passes other than the LocalRewriter. /// NOTE: Use MakeConversion helper method in the LocalRewriter instead, /// NOTE: it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion Synthesized( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup conversionGroupOpt, ConstantValue constantValueOpt, TypeSymbol type, bool hasErrors = false) { return new BoundConversion( syntax, operand, conversion, @checked, explicitCastInCode: explicitCastInCode, conversionGroupOpt, constantValueOpt, type, hasErrors || !conversion.IsValid) { WasCompilerGenerated = true }; } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup conversionGroupOpt, ConstantValue constantValueOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operand, conversion, isBaseConversion: false, @checked: @checked, explicitCastInCode: explicitCastInCode, constantValueOpt: constantValueOpt, conversionGroupOpt, conversion.OriginalUserDefinedConversions, type: type, hasErrors: hasErrors || !conversion.IsValid) { } #nullable enable public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, originalUserDefinedConversionsOpt: default, type, hasErrors) { } public BoundConversion Update(BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type) => Update(operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, this.OriginalUserDefinedConversionsOpt, type); #nullable restore } internal sealed partial class BoundBinaryOperator { public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, ConstantValue constantValueOpt, MethodSymbol methodOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, constantValueOpt, methodOpt, resultKind, originalUserDefinedOperatorsOpt, left, right, type, hasErrors) { } #nullable enable public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, constantValueOpt, methodOpt, resultKind, originalUserDefinedOperatorsOpt: default, left, right, type, hasErrors) { } public BoundBinaryOperator Update(BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) => Update(operatorKind, constantValueOpt, methodOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, left, right, type); #nullable restore } internal sealed partial class BoundUserDefinedConditionalLogicalOperator { public BoundUserDefinedConditionalLogicalOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, logicalOperator, trueOperator, falseOperator, resultKind, originalUserDefinedOperatorsOpt, left, right, type, hasErrors) { Debug.Assert(operatorKind.IsUserDefined() && operatorKind.IsLogical()); } #nullable enable public BoundUserDefinedConditionalLogicalOperator Update(BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) => Update(operatorKind, logicalOperator, trueOperator, falseOperator, resultKind, this.OriginalUserDefinedOperatorsOpt, left, right, type); #nullable restore } internal sealed partial class BoundParameter { public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, bool hasErrors = false) : this(syntax, parameterSymbol, parameterSymbol.Type, hasErrors) { } public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol) : this(syntax, parameterSymbol, parameterSymbol.Type) { } } internal sealed partial class BoundTypeExpression { public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, BoundTypeExpression boundContainingTypeOpt, ImmutableArray<BoundExpression> boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, boundDimensionsOpt, typeWithAnnotations, typeWithAnnotations.Type, hasErrors) { Debug.Assert((object)typeWithAnnotations.Type != null, "Field 'type' cannot be null"); } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, BoundTypeExpression boundContainingTypeOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, ImmutableArray<BoundExpression>.Empty, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, aliasOpt, null, TypeWithAnnotations.Create(type), hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol aliasOpt, ImmutableArray<BoundExpression> dimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, dimensionsOpt, typeWithAnnotations, hasErrors) { } } internal sealed partial class BoundNamespaceExpression { public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, bool hasErrors = false) : this(syntax, namespaceSymbol, null, hasErrors) { } public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol) : this(syntax, namespaceSymbol, null) { } public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol) { return Update(namespaceSymbol, this.AliasOpt); } } internal sealed partial class BoundAssignmentOperator { public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool isRef = false, bool hasErrors = false) : this(syntax, left, right, isRef, type, hasErrors) { } } internal sealed partial class BoundBadExpression { public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childBoundNodes, TypeSymbol type) : this(syntax, resultKind, symbols, childBoundNodes, type, true) { Debug.Assert((object)type != null); } } internal partial class BoundStatementList { public static BoundStatementList Synthesized(SyntaxNode syntax, params BoundStatement[] statements) { return Synthesized(syntax, false, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, params BoundStatement[] statements) { return Synthesized(syntax, hasErrors, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return Synthesized(syntax, false, statements); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, ImmutableArray<BoundStatement> statements) { return new BoundStatementList(syntax, statements, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundReturnStatement { public static BoundReturnStatement Synthesized(SyntaxNode syntax, RefKind refKind, BoundExpression expression, bool hasErrors = false) { return new BoundReturnStatement(syntax, refKind, expression, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundYieldBreakStatement { public static BoundYieldBreakStatement Synthesized(SyntaxNode syntax, bool hasErrors = false) { return new BoundYieldBreakStatement(syntax, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundGotoStatement { public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors = false) : this(syntax, label, caseExpressionOpt: null, labelExpressionOpt: null, hasErrors: hasErrors) { } } internal partial class BoundBlock { public BoundBlock(SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements, bool hasErrors = false) : this(syntax, locals, ImmutableArray<LocalFunctionSymbol>.Empty, statements, hasErrors) { } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, BoundStatement statement) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, params BoundStatement[] statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements.AsImmutableOrNull()) { WasCompilerGenerated = true }; } } internal sealed partial class BoundDefaultExpression { public BoundDefaultExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors = false) : this(syntax, targetType: null, type?.GetDefaultValue(), type, hasErrors) { } public override ConstantValue ConstantValue => ConstantValueOpt; } internal partial class BoundTryStatement { public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray<BoundCatchBlock> catchBlocks, BoundBlock finallyBlockOpt, LabelSymbol finallyLabelOpt = null) : this(syntax, tryBlock, catchBlocks, finallyBlockOpt, finallyLabelOpt, preferFaultHandler: false, hasErrors: false) { } } internal partial class BoundAddressOfOperator { public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, isManaged: false, type, hasErrors) { } } internal partial class BoundDagTemp { public BoundDagTemp(SyntaxNode syntax, TypeSymbol type, BoundDagEvaluation source) : this(syntax, type, source, index: 0, hasErrors: false) { } public static BoundDagTemp ForOriginalInput(BoundExpression expr) => new BoundDagTemp(expr.Syntax, expr.Type, source: null); } #nullable enable internal partial class BoundCompoundAssignmentOperator { public BoundCompoundAssignmentOperator(SyntaxNode syntax, BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, @operator, left, right, leftConversion, finalConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundCompoundAssignmentOperator Update(BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type) => Update(@operator, left, right, leftConversion, finalConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundUnaryOperator { public BoundUnaryOperator( SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, constantValueOpt, methodOpt, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundUnaryOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, LookupResultKind resultKind, TypeSymbol type) => Update(operatorKind, operand, constantValueOpt, methodOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundIncrementOperator { public BoundIncrementOperator( CSharpSyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, methodOpt, operandConversion, resultConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundIncrementOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type) { return Update(operatorKind, operand, methodOpt, operandConversion, resultConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } } #nullable restore }
abock/roslyn
src/Compilers/CSharp/Portable/BoundTree/Constructors.cs
C#
mit
31,920
<?php class ExceptionInSetUpTest extends CIUnit_Framework_TestCase { public $setUp = FALSE; public $assertPreConditions = FALSE; public $assertPostConditions = FALSE; public $tearDown = FALSE; public $testSomething = FALSE; protected function setUp() { $this->setUp = TRUE; throw new Exception; } public function testSomething() { $this->testSomething = TRUE; } protected function tearDown() { $this->tearDown = TRUE; } }
joeminow/mytest
application/tests/_files/ExceptionInSetUpTest.php
PHP
mit
525
package org.hive2hive.core.model.versioned; import java.io.File; import java.security.KeyPair; import java.security.PublicKey; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.hive2hive.core.TimeToLiveStore; import org.hive2hive.core.model.FolderIndex; import org.hive2hive.core.model.Index; import org.hive2hive.core.model.PermissionType; import org.hive2hive.core.model.UserPermission; /** * File which contains all keys and meta information about the files of the owner. * * @author Nico, Seppi * */ public class UserProfile extends BaseVersionedNetworkContent { private static final long serialVersionUID = -8089242126512434561L; private final String userId; private final KeyPair encryptionKeys; private final FolderIndex root; public UserProfile(String userId, KeyPair encryptionKeys, KeyPair protectionKeys) { assert userId != null; this.userId = userId; this.encryptionKeys = encryptionKeys; // create the root node root = new FolderIndex(encryptionKeys); root.setProtectionKeys(protectionKeys); root.addUserPermissions(new UserPermission(userId, PermissionType.WRITE)); } public String getUserId() { return userId; } public KeyPair getEncryptionKeys() { return encryptionKeys; } public KeyPair getProtectionKeys() { return root.getProtectionKeys(); } public FolderIndex getRoot() { return root; } @Override public int getTimeToLive() { return TimeToLiveStore.getInstance().getUserProfile(); } @Override protected int getContentHash() { return userId.hashCode() + 21 * encryptionKeys.hashCode(); } public Index getFileById(PublicKey fileId) { return findById(root, fileId); } private Index findById(Index current, PublicKey fileId) { if (current.getFilePublicKey().equals(fileId)) { return current; } Index found = null; if (current instanceof FolderIndex) { FolderIndex folder = (FolderIndex) current; for (Index child : folder.getChildren()) { found = findById(child, fileId); if (found != null) { return found; } } } return found; } public Index getFileByPath(File file, File root) { // holds all files in-order File currentFile = new File(file.getAbsolutePath()); List<String> filePath = new ArrayList<String>(); while (!root.equals(currentFile) && currentFile != null) { filePath.add(currentFile.getName()); currentFile = currentFile.getParentFile(); } Collections.reverse(filePath); FolderIndex currentIndex = this.root; for (String fileName : filePath) { Index child = currentIndex.getChildByName(fileName); if (child == null) { return null; } else if (child instanceof FolderIndex) { currentIndex = (FolderIndex) child; } else if (child.getName().equals(file.getName())) { return child; } } return currentIndex; } }
gfneto/Hive2Hive
org.hive2hive.core/src/main/java/org/hive2hive/core/model/versioned/UserProfile.java
Java
mit
2,849
package crafttweaker.api.chat; import crafttweaker.annotations.ZenRegister; import stanhebben.zenscript.annotations.*; /** * Represents a chat message. Strings can be converted into chat messages, and * chat messages can be colored and concatenated. * * @author Stan Hebben */ @ZenClass("crafttweaker.chat.IChatMessage") @ZenRegister public interface IChatMessage { /** * Concatenates two chat messages. * * @param other other chat message * * @return concatenated chat message */ @ZenOperator(OperatorType.ADD) IChatMessage add(IChatMessage other); /** * Retrieves the internal object backing this object. Must be generated by * the implementing platform. * * @return internal object */ Object getInternal(); }
AllTheMods/CraftTweaker
CraftTweaker2-API/src/main/java/crafttweaker/api/chat/IChatMessage.java
Java
mit
804
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("CacheModelUnitTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("CacheModelUnitTest")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [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("bfda6f9d-3497-4e3e-8bf3-d5f2a05df918")] // 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")]
owolp/Telerik-Academy
Module-2/Design-Patterns/Materials/DI.NET/DIContainers/CacheModelUnitTest/Properties/AssemblyInfo.cs
C#
mit
1,430
/** * 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. */ package com.microsoft.azure.management.mediaservices.v2019_05_01_preview; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * Represents HTTPS job input. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@odata\\.type", defaultImpl = JobInputHttp.class) @JsonTypeName("#Microsoft.Media.JobInputHttp") public class JobInputHttp extends JobInputClip { /** * Base URI for HTTPS job input. It will be concatenated with provided file * names. If no base uri is given, then the provided file list is assumed * to be fully qualified uris. Maximum length of 4000 characters. */ @JsonProperty(value = "baseUri") private String baseUri; /** * Get base URI for HTTPS job input. It will be concatenated with provided file names. If no base uri is given, then the provided file list is assumed to be fully qualified uris. Maximum length of 4000 characters. * * @return the baseUri value */ public String baseUri() { return this.baseUri; } /** * Set base URI for HTTPS job input. It will be concatenated with provided file names. If no base uri is given, then the provided file list is assumed to be fully qualified uris. Maximum length of 4000 characters. * * @param baseUri the baseUri value to set * @return the JobInputHttp object itself. */ public JobInputHttp withBaseUri(String baseUri) { this.baseUri = baseUri; return this; } }
navalev/azure-sdk-for-java
sdk/mediaservices/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2019_05_01_preview/JobInputHttp.java
Java
mit
1,846
using System; using System.Text; using System.Collections; using System.Collections.Generic; namespace Com.Aspose.Tasks.Model { public class ResourceItems { public List<ResourceItem> List { get; set; } public Link link { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append("class ResourceItems {\n"); sb.Append(" List: ").Append(List).Append("\n"); sb.Append(" link: ").Append(link).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
asposetasks/Aspose_Tasks_Cloud
SDKs/Aspose.Tasks-Cloud-SDK-for-.NET/src/Com/Aspose/Tasks/Model/ResourceItems.cs
C#
mit
543
import path from 'path'; import webpack from 'webpack'; import config from '../config' let webpackConfig = { entry: { vendor: [path.join(__dirname, 'vendors/vendors.js')] }, output: { path: path.join(config.path_dist), filename: 'dll.[name].js', library: '[name]' }, plugins: [ new webpack.DefinePlugin(config.globals), new webpack.DllPlugin({ path: path.join(config.path_dist, '[name]-manifest.json'), name: '[name]', context: path.resolve(__dirname, '../app') }) ], resolve: { root: path.resolve(__dirname, '../app'), modulesDirectories: ['node_modules'] } }; if (process.env.NODE_ENV === 'production') { webpackConfig.plugins.push( new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { unused: true, dead_code: true } }) ) } const compiler = webpack(webpackConfig); compiler.run((err, stats) => { console.log(stats.toString({ chunks : false, chunkModules : false, colors : true })); });
voicebase/voicebase-end-user-experience
webpack/webpack.dll.js
JavaScript
mit
1,106
<?php namespace Dotenv\Store; use Dotenv\Exception\InvalidPathException; use Dotenv\Store\File\Reader; class FileStore implements StoreInterface { /** * The file paths. * * @var string[] */ protected $filePaths; /** * Should file loading short circuit? * * @var bool */ protected $shortCircuit; /** * Create a new file store instance. * * @param string[] $filePaths * @param bool $shortCircuit * * @return void */ public function __construct(array $filePaths, $shortCircuit) { $this->filePaths = $filePaths; $this->shortCircuit = $shortCircuit; } /** * Read the content of the environment file(s). * * @throws \Dotenv\Exception\InvalidPathException * * @return string */ public function read() { if ($this->filePaths === []) { throw new InvalidPathException('At least one environment file path must be provided.'); } $contents = Reader::read($this->filePaths, $this->shortCircuit); if (count($contents) > 0) { return implode("\n", $contents); } throw new InvalidPathException( sprintf('Unable to read any of the environment file(s) at [%s].', implode(', ', $this->filePaths)) ); } }
drakakisgeo/mailtester
vendor/vlucas/phpdotenv/src/Store/FileStore.php
PHP
mit
1,357
var fs = require('fs'); var _ = require('lodash'); var logger = require('winston'); function Lint() { /** * @type {string} */ this.file = null; /** * @type {string} */ this.pass = null; /** * @type {string} */ this.original = null; /** * @type {string[]} */ this.lines = null; /** * @param {string} file */ this.read = function (file) { this.file = file; this.original = fs.readFileSync(file, 'utf8'); this.original = this.original.replace(/\t/g, ' '); this.lines = this.original.replace(/[\r]/g, "").split("\n"); }; /** * */ this.clear = function () { this.file = null; this.original = null; this.lines = null; }; /** * @returns {boolean} */ this.isJs = function () { return !this.isTest() && _.endsWith(this.file.toLowerCase(), ".js"); }; /** * @returns {boolean} */ this.isTest = function () { return _.endsWith(this.file.toLowerCase(), ".spec.js") || _.endsWith(this.file.toLowerCase(), ".test.js"); }; /** * @returns {boolean} */ this.isHTML = function () { return _.endsWith(this.file.toLowerCase(), ".html"); }; /** * @param {Number} offset * @returns {{line:Number,column:Number}} */ this.getCoordsByOffset = function (offset) { var lines = this.original.substr(0, offset).split("\n"); return { line: lines.length, column: _.last(lines).length + 1, text: this.lines[lines.length - 1] } }; /** * Executes the callback for each line in the file. * * @param {function(string)} fn * @param {*=} thisArg */ this.each = function (fn, thisArg) { for (this.line = 0; this.line < this.lines.length; this.line++) { fn.call(thisArg || this, this.lines[this.line]); } }; /** * Executes the callback for each regexp match. * * @param {RegExp} regex * @param {function(Array)} fn * @param {*=} thisArg */ this.match = function (regex, fn, thisArg) { var match; while ((match = regex.exec(this.original)) != null) { // attach a convenient log method match.log = function (match, msg) { var coords = this.getCoordsByOffset(match.index); console.log(this.file + ':' + coords.line + ',' + coords.column); console.log(coords.text); console.log(Array(coords.column).join(' ') + '^'); console.log(msg); console.log(); }.bind(this, match); fn.call(thisArg, match); } }; } var LinkObj = new Lint(); logger.extend(LinkObj); module.exports = LinkObj;
thinkingmedia/nglint
src/lint.js
JavaScript
mit
2,873
package com.microsoft.bingads.adintelligence; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for guid simple type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;simpleType name="guid"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;pattern value="[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "guid", namespace = "http://schemas.microsoft.com/2003/10/Serialization/", propOrder = { "value" }) public class Guid { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } }
JeffRisberg/BING01
proxies/com/microsoft/bingads/adintelligence/Guid.java
Java
mit
1,325
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'adv_link', 'sq', { acccessKey: 'Sipas ID-së së Elementit', advanced: 'Të përparuara', advisoryContentType: 'Lloji i Përmbajtjes Këshillimore', advisoryTitle: 'Titull', anchor: { toolbar: 'Spirancë', menu: 'Redakto Spirancën', title: 'Anchor Properties', // MISSING name: 'Emri i Spirancës', errorName: 'Ju lutemi shkruani emrin e spirancës', remove: 'Largo Spirancën' }, anchorId: 'Sipas ID-së së Elementit', anchorName: 'Sipas Emrit të Spirancës', charset: 'Seti i Karaktereve të Burimeve të Nëdlidhura', cssClasses: 'Klasa stili CSS', emailAddress: 'Posta Elektronike', emailBody: 'Trupi i Porosisë', emailSubject: 'Titulli i Porosisë', id: 'Id', info: 'Informacione të Nyjes', langCode: 'Kod gjuhe', langDir: 'Drejtim teksti', langDirLTR: 'Nga e majta në të djathë (LTR)', langDirRTL: 'Nga e djathta në të majtë (RTL)', menu: 'Redakto Nyjen', name: 'Emër', noAnchors: '(Nuk ka asnjë spirancë në dokument)', noEmail: 'Ju lutemi shkruani postën elektronike', noUrl: 'Ju lutemi shkruani URL-në e nyjes', other: '<tjetër>', popupDependent: 'E Varur (Netscape)', popupFeatures: 'Karakteristikat e Dritares së Dialogut', popupFullScreen: 'Ekran i Plotë (IE)', popupLeft: 'Pozita Majtas', popupLocationBar: 'Shiriti i Lokacionit', popupMenuBar: 'Shiriti i Menysë', popupResizable: 'I ndryshueshëm', popupScrollBars: 'Shiritat zvarritës', popupStatusBar: 'Shiriti i Statutit', popupToolbar: 'Shiriti i Mejteve', popupTop: 'Top Pozita', rel: 'Marrëdhëniet', selectAnchor: 'Përzgjidh një Spirancë', styles: 'Stil', tabIndex: 'Indeksi i fletave', target: 'Objektivi', targetFrame: '<frame>', targetFrameName: 'Emri i Kornizës së Synuar', targetPopup: '<popup window>', targetPopupName: 'Emri i Dritares së Dialogut', title: 'Nyja', toAnchor: 'Lidhu me spirancën në tekst', toEmail: 'Posta Elektronike', toUrl: 'URL', toolbar: 'Nyja', type: 'Lloji i Nyjes', unlink: 'Largo Nyjen', upload: 'Ngarko' } );
theus77/ElasticMS
src/AppBundle/Resources/public/adv_link/lang/sq.js
JavaScript
mit
2,182
<?php if (!isset($_SERVER['REQUEST_TIME_FLOAT'])) { $_SERVER['REQUEST_TIME_FLOAT'] = microtime(true); } try { require_once __DIR__ . '/../bootstrap.php'; } catch (Exception $e) { // NO-OP } echo '<!--' . "\n"; echo 'processing duration: ' . round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000) . ' ms' . "\n"; echo 'peak memory usage: ' . memory_get_peak_usage(true) / 1024 / 1024 . ' MB' . "\n"; echo '-->' . "\n";
laposta/connect-googlecontacts
public/index.php
PHP
mit
443
#!/usr/bin/env node const http = require('http'); const config = require('../config'); const http_code = process.env.HEALTHCHECK_CODE || 200; const options = { host: 'localhost', port: process.env.IDM_PORT || config.port, timeout: 2000, method: 'GET', path: process.env.HEALTHCHECK_PATH || '/version' }; const request = http.request(options, (result) => { // eslint-disable-next-line no-console console.info(`Performed health check, result ${result.statusCode}`); if (result.statusCode === http_code) { process.exit(0); } else { process.exit(1); } }); request.on('error', (err) => { // eslint-disable-next-line no-console console.error(`An error occurred while performing health check, error: ${err}`); process.exit(1); }); request.end();
ging/fiware-idm
bin/healthcheck.js
JavaScript
mit
778
version https://git-lfs.github.com/spec/v1 oid sha256:3739b485ac39b157caa066b883e4d9d3f74c50beff0b86cd8a24ce407b179a23 size 93867
yogeshsaroya/new-cdnjs
ajax/libs/datatables/1.9.1/js/jquery.js
JavaScript
mit
130
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("1.PrintBoolean")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("1.PrintBoolean")] [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("1948594f-39bf-4ec7-a31b-f68492a8caf0")] // 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")]
jasssonpet/TelerikAcademy
Programming/4.HighQualityCode/3.NamingIdentifiers/1.PrintBoolean/Properties/AssemblyInfo.cs
C#
mit
1,404
#include "qss_nlfunction_step.h" void qss_nlfunction_step::init(double t,...) { //The 'parameters' variable contains the parameters transferred from the editor. va_list parameters; va_start(parameters,t); //To get a parameter: %Name% = va_arg(parameters,%Type%) //where: // %Name% is the parameter name // %Type% is the parameter type expre = va_arg(parameters,char*); n = (int)va_arg(parameters,double); purely_static=strcmp(va_arg(parameters,char*),"Purely static")==0; dQmin=getScilabVar(va_arg(parameters,char*)); dQrel=getScilabVar(va_arg(parameters,char*)); dt=1e-5; sigma=INF; for (int i=0;i<10;i++) { for (int j=0;j<n;j++) { u[j][i]=0; uaux[j][i]=0; }; y[i]=0; }; order=1; PRVar uvar0=new RVar ( "u0" , &uaux[0][0] ); PRVar uvar1=new RVar ( "u1" , &uaux[1][0] ); PRVar uvar2=new RVar ( "u2" , &uaux[2][0] ); PRVar uvar3=new RVar ( "u3" , &uaux[3][0] ); PRVar uvar4=new RVar ( "u4" , &uaux[4][0] ); PRVar uvar5=new RVar ( "u5" , &uaux[5][0] ); PRVar uvar6=new RVar ( "u6" , &uaux[6][0] ); PRVar uvar7=new RVar ( "u7" , &uaux[7][0] ); PRVar uvar8=new RVar ( "u8" , &uaux[8][0] ); PRVar uvar9=new RVar ( "u9" , &uaux[9][0] ); PRVar vartab[10]; vartab[0]=uvar0; vartab[1]=uvar1; vartab[2]=uvar2; vartab[3]=uvar3; vartab[4]=uvar4; vartab[5]=uvar5; vartab[6]=uvar6; vartab[7]=uvar7; vartab[8]=uvar8; vartab[9]=uvar9; pop=new ROperation ((char*)expre, n, (RVar**)vartab); } double qss_nlfunction_step::ta(double t) { return sigma; } void qss_nlfunction_step::dint(double t) { if (purely_static) { sigma=INF; return; } // Estimate advance time // First compute the next two coefficients y_n+1 and y_n+2 switch (order) { case 1: sigma=INF; return; case 2: { for (int i=0;i<n;i++) { advance_time(uaux[i],2*dt,1); }; f2dt=pop->Val(); // Evaluation of f(x+2dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-4*dt,1); }; f_2dt=pop->Val(); // Evaluation of f(x-2dt) y_n1=(fdt-2*f0+f_dt)/(dt*dt*2); y_n2=(f2dt-2*fdt+2*f_dt-f_2dt)/(dt*dt*dt*12); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; } break; case 3: { for (int i=0;i<n;i++) { advance_time(uaux[i],2*dt,2); }; f2dt=pop->Val(); // Evaluation of f(x+2dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-4*dt,2); }; f_2dt=pop->Val(); // Evaluation of f(x-2dt) y_n1=(f2dt-2*fdt+2*f_dt-f_2dt)/(dt*dt*dt*12); y_n2=(f2dt-4*fdt+6*f0-4*f_dt+f_2dt)/(dt*dt*dt*dt*24); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; } break; case 4: { for (int i=0;i<n;i++) { advance_time(uaux[i],2*dt,3); }; f2dt=pop->Val(); // Evaluation of f(x+2dt) for (int i=0;i<n;i++) { advance_time(uaux[i],dt,3); }; f3dt=pop->Val(); // Evaluation of f(x+3dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-5*dt,3); }; f_2dt=pop->Val(); // Evaluation of f(x-2dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-dt,3); }; f_3dt=pop->Val(); // Evaluation of f(x-3dt) y_n1=(f2dt-4*fdt+6*f0-4*f_dt+f_2dt)/(dt*dt*dt*dt*24); y_n2=(f3dt-4*f2dt+5*fdt-5*f_dt+4*f_2dt-f_3dt)/(dt*dt*dt*dt*dt*240); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; } break; } // Now estimate sigma tol=fabs(y[0])*dQrel; if (tol<dQmin) tol=dQmin; printLog("[t=%g] -2dt=%g -dt=%g f0=%g dt=%g 2dt=%g\n",t,f_2dt,f_dt,f0,fdt,f2dt); double eps=1e-20; if (fabs(y_n1)>eps) { sigma=.8* pow(fabs(tol/y_n1),1.0/order); printLog("[t=%g] With first coefficient sigma=%g y_n1=%g\n",t,sigma,y_n1); } if (fabs(y_n2)>eps) { printLog("[t=%g] With second coefficient sigma=%g y_n2=%g tol=%g\n",t,.8*pow(fabs(tol/y_n2),1.0/(order+1)),y_n2,tol); if (.8*pow(fabs(tol/y_n2),1.0/(order+1))<sigma) sigma=.8*pow(fabs(tol/y_n2),1.0/(order+1)); } for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; for (int i=0;i<n;i++) { advance_time(uaux[i],sigma,order); } double err=fabs(pop->Val()-evaluate_poly(y,sigma,order)); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; while (fabs(sigma)>eps && err>tol) { sigma*=.8*pow(fabs(tol/err),1.0/order); for (int i=0;i<n;i++) { advance_time(uaux[i],sigma,order); } err=fabs(pop->Val()-evaluate_poly(y,sigma,order)); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; printLog("[t=%g] With iteration sigma=%g\n",sigma); } if (fabs(sigma)<eps || err>tol) { sigma = 1e-10; for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; for (int i=0;i<n;i++) { advance_time(uaux[i],sigma,order); } unsigned iter=0,max_iter=100; while (fabs(pop->Val()-evaluate_poly(y,2*sigma,order))<tol && iter<max_iter) { sigma*=2; iter++; for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; for (int i=0;i<n;i++) { advance_time(uaux[i],2*sigma,order); } } printLog("Using a bisection step sigma=%g \n",sigma); } printLog("[t=%g] sigma=%g\n",t,sigma); } void qss_nlfunction_step::dext(Event x, double t) { //The input event is in the 'x' variable. //where: // 'x.value' is the value // 'x.port' is the port number double *xv; xv=(double*)(x.value); switch(order) { case 1: u[x.port][0]=xv[0]; if (xv[1]!=0){order=2;u[x.port][1]=xv[1];} if (xv[2]!=0){order=3;u[x.port][2]=xv[2];} if (xv[3]!=0){order=4;u[x.port][3]=xv[3];} break; case 2: u[x.port][0]=xv[0]; u[x.port][1]=xv[1]; for (int i=0;i<n;i++) { if (i!=x.port) { advance_time(u[i],e,1); }; }; if (xv[2]!=0){order=3;u[x.port][2]=xv[2];} if (xv[3]!=0){order=4;u[x.port][3]=xv[3];} break; case 3: u[x.port][0]=xv[0]; u[x.port][1]=xv[1]; u[x.port][2]=xv[2]; for (int i=0;i<n;i++) { if (i!=x.port) { advance_time(u[i],e,2); }; }; if (xv[3]!=0){order=4;u[x.port][3]=xv[3];} break; case 4: u[x.port][0]=xv[0]; u[x.port][1]=xv[1]; u[x.port][2]=xv[2]; u[x.port][3]=xv[3]; for (int i=0;i<n;i++) { if (i!=x.port) { advance_time(u[i],e,3); }; }; } sigma=0; if (e>1e-15){dt=e/100;} switch(order) { case 1: uaux[x.port][0]=u[x.port][0]; f[0]=pop->Val(); break; case 2: { for (int i=0;i<n;i++){ uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; f0=pop->Val(); for (int i=0;i<n;i++) { advance_time(uaux[i],dt,1); }; fdt=pop->Val(); for (int i=0;i<n;i++) { advance_time(uaux[i],-2*dt,1); }; f_dt=pop->Val(); f[0]=f0; f[1]=(fdt-f_dt)/(2*dt); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; } break; case 3: { for (int i=0;i<n;i++){ uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; uaux[i][2]=u[i][2]; }; f0=pop->Val(); for (int i=0;i<n;i++) { advance_time(uaux[i],dt,2); }; fdt=pop->Val(); for (int i=0;i<n;i++) { advance_time(uaux[i],-2*dt,2); }; f_dt=pop->Val(); f[0]=f0; f[1]=(fdt-f_dt)/2*dt; f[2]=(fdt-2*f0+f_dt)/(dt*dt*2); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; } break; case 4: { for (int i=0;i<n;i++){ uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; uaux[i][2]=u[i][2]; uaux[i][3]=u[i][3]; }; f0=pop->Val(); // Evaluation of f(t) for (int i=0;i<n;i++) { advance_time(uaux[i],dt,3); }; fdt=pop->Val(); // Evaluation of f(t+dt) for (int i=0;i<n;i++) { advance_time(uaux[i],dt,3); }; f2dt=pop->Val(); // Evaluation of f(t+2dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-3*dt,3); }; f_dt=pop->Val(); // Evaluation of f(t-dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-dt,3); }; f_2dt=pop->Val(); // Evaluation of f(t-2dt) f[0]=f0; f[1]=(fdt - f_dt)/2*dt; f[2]=(fdt-2*f0+f_dt)/(dt*dt*2); f[3]=(f2dt-2*fdt+2*f_dt-f_2dt)/(12*dt*dt*dt); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; } }; sigma=0; } Event qss_nlfunction_step::lambda(double t) { advance_time(y,sigma,order); for (int i=0;i<n;i++) { advance_time(u[i],sigma,order); }; if (e>1e-15){dt=e/100;} switch(order) { case 1: for (int i=0;i<n;i++) uaux[i][0]=u[i][0]; f0=pop->Val(); // Evaluation of f(t) f[0]=f0; break; case 2: { for (int i=0;i<n;i++){ uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; f0=pop->Val(); // Evaluation of f(t) for (int i=0;i<n;i++) { advance_time(uaux[i],dt,1); }; fdt=pop->Val(); // Evaluation of f(t+dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-2*dt,1); }; f_dt=pop->Val(); // Evaluation of f(t-dt) f[0]=f0; f[1]=(fdt-f_dt)/(2*dt); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; }; } break; case 3: { for (int i=0;i<n;i++){ uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; uaux[i][2]=u[i][2]; }; f0=pop->Val(); // Evaluation of f(t) for (int i=0;i<n;i++) { advance_time(uaux[i],dt,2); }; fdt=pop->Val(); // Evaluation of f(t+dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-2*dt,2); }; f_dt=pop->Val();// Evaluation of f(t-dt) f[0]=f0; f[1]=(fdt - f_dt)/(2*dt); f[2]=(fdt-2*f0+f_dt)/(2*dt*dt); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; uaux[i][2]=u[i][2]; }; } break; case 4: { for (int i=0;i<n;i++){ uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; uaux[i][2]=u[i][2]; uaux[i][3]=u[i][3]; }; f0=pop->Val(); // Evaluation of f(t) for (int i=0;i<n;i++) { advance_time(uaux[i],dt,3); }; fdt=pop->Val();// Evaluation of f(t+dt) for (int i=0;i<n;i++) { advance_time(uaux[i],dt,3); }; f2dt=pop->Val();// Evaluation of f(t+2dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-3*dt,3); }; f_dt=pop->Val();// Evaluation of f(t-dt) for (int i=0;i<n;i++) { advance_time(uaux[i],-dt,3); }; f_2dt=pop->Val();// Evaluation of f(t-2dt) f[0]=f0; f[1]=(fdt-f_dt)/(2*dt); f[2]=(fdt-2*f0+f_dt)/(dt*dt*2); f[3]=(f2dt-2*fdt+2*f_dt-f_2dt)/(dt*dt*dt*12); for (int i=0;i<n;i++){ // Take back the changes uaux[i][0]=u[i][0]; uaux[i][1]=u[i][1]; uaux[i][2]=u[i][2]; uaux[i][3]=u[i][3]; }; } }; if (fabs(f[0]-y[0])>tol && sigma) printLog("[t=%g] Diff=%g (tol=%g)\n",t,f[0]-y[0],tol); for (int i=0;i<order;i++) { y[i]=f[i]; }; return Event(y,0); } void qss_nlfunction_step::exit() { }
andyLaurito92/haikunet
debug/atomics/qss/qss_nlfunction_step.cpp
C++
mit
10,326
/** * @license Angular UI Gridster v0.4.1 * (c) 2010-2014. https://github.com/JimLiu/angular-ui-gridster * License: MIT */ (function () { 'use strict'; angular.module('ui.gridster', []) .constant('uiGridsterConfig', { widget_margins: [10, 10], widget_base_dimensions: [100, 100], widget_selector: '.ui-gridster-item', resize: { enabled: false } }); })(); (function() { 'use strict'; angular.module('ui.gridster') .controller('GridsterController', ['$scope', '$element', '$attrs', function($scope, $element, $attrs) { this.scope = $scope; this.element = $element; $scope.$dragEnabled = true; $scope.$modelValue = null; var gridster = null; $scope.init = function(element, options) { gridster = element.gridster(options).data('gridster'); return gridster; }; this.addItem = function(element, sizeX, sizeY, col, row) { if (gridster) { return gridster.add_widget(element, sizeX, sizeY, col, row); } return null; }; this.removeItem = function(element) { if (gridster) { gridster.remove_widget(element, function() { $scope.$apply(); }); } }; this.resizeItem = function(widget, sizeX, sizeY) { if (gridster && widget) { gridster.resize_widget(widget, sizeX, sizeY); } }; $scope.serializeToJson = function() { var s = gridster.serialize(); return JSON.stringify(s); }; $scope.applyChanges = function() { var items = gridster.serialize(); angular.forEach(items, function(item, index) { var widget = $scope.$modelValue[index]; widget.sizeX = item.size_x; widget.sizeY = item.size_y; widget.row = item.row; widget.col = item.col; }); }; } ]); })(); (function() { 'use strict'; angular.module('ui.gridster') .directive('uiGridster', ['uiGridsterConfig', '$timeout', function(uiGridsterConfig, $timeout) { return { restrict: 'A', scope: true, controller: 'GridsterController', require: 'ngModel', link: function(scope, element, attrs, ngModel) { var options = { draggable: {}, resize: {} }; var gridster; options = angular.extend(options, uiGridsterConfig); function combineCallbacks(first,second){ if(second && (typeof second === 'function')) { return function(e, ui) { first(e, ui); second(e, ui); }; } return first; } options.draggable.stop = function(event, ui) { scope.$apply(); }; options.resize.stop = function(event, ui, $widget) { scope.$apply(); }; if (ngModel) { ngModel.$render = function() { if (!ngModel.$modelValue || !angular.isArray(ngModel.$modelValue)) { scope.$modelValue = []; } scope.$modelValue = ngModel.$modelValue; }; } attrs.$observe('uiGridster', function(val) { var gval = scope.$eval(val); if((typeof gval) != 'undefined') { if (gval.draggable) { if (gval.draggable.stop) { gval.draggable.stop = combineCallbacks(options.draggable.stop, gval.draggable.stop); } else { gval.draggable.stop = options.resize.stop; } } if (gval.resize) { if (gval.resize.stop) { gval.resize.stop = combineCallbacks(options.resize.stop, gval.resize.stop); } else { gval.resize.stop = options.resize.stop; } } angular.extend(options, gval); } gridster = scope.init(element, options); }); scope.$watch(function() { return scope.$eval(attrs.gridsterDragEnabled); }, function(val) { if((typeof val) == "boolean") { scope.$dragEnabled = val; if (!gridster) { return; } if (val) { gridster.enable(); } else { gridster.disable(); } } }); } }; } ]); })(); (function() { 'use strict'; angular.module('ui.gridster') .directive('uiGridsterItem', ['$compile', function($compile) { return { restrict: 'A', require: '^uiGridster', link: function(scope, element, attrs, controller) { var gridsterItem = null; var widget = element; element.addClass('ui-gridster-item'); scope.gridsterItem = null; attrs.$observe('uiGridsterItem', function(val) { var ival = scope.$eval(val); if((typeof ival) == 'object') { gridsterItem = ival; scope.gridsterItem = gridsterItem; var placeHolder = $('<li></li>'); element.replaceWith(placeHolder); var widget = controller.addItem(element, gridsterItem.sizeX, gridsterItem.sizeY, gridsterItem.col, gridsterItem.row); $compile(widget.contents())(scope); placeHolder.replaceWith(widget); widget.bind('$destroy', function() { controller.removeItem(widget); }); scope.$watch(function() { return widget.attr('data-col'); }, function(val) { gridsterItem.col = parseInt(val); }); scope.$watch(function() { return widget.attr('data-row'); }, function(val) { gridsterItem.row = parseInt(val); }); scope.$watch(function() { return widget.attr('data-sizex'); }, function(val) { gridsterItem.sizeX = parseInt(val); }); scope.$watch(function() { return widget.attr('data-sizey'); }, function(val) { gridsterItem.sizeY = parseInt(val); }); } }); scope.$watchCollection('[gridsterItem.sizeX, gridsterItem.sizeY]', function(newValues) { if (newValues[0] && newValues[1]) { controller.resizeItem(widget, newValues[0], newValues[1]); } }); } }; } ]); })();
JimLiu/angular-ui-gridster
dist/angular-ui-gridster.js
JavaScript
mit
7,041
namespace Photos { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class Photographer { private Photographer() { this.Albums = new HashSet<Album>(); } public Photographer(string userName, string password, string email) : this() { this.UserName = userName; this.Password = password; this.Email = email; } public int Id { get; set; } [Required] [MinLength(3)] [MaxLength(25)] public string UserName { get; set; } [Required] [MinLength(8)] [MaxLength(16)] public string Password { get; set; } [Required] [StringLength(50)] public string Email { get; set; } public DateTime? RegisterDate { get; set; } public DateTime? BirthDate { get; set; } public virtual ICollection<Album> Albums { get; set; } } }
RAstardzhiev/Software-University-SoftUni
Databases Advanced - Entity Framework 6/EF Relations/Photos/Photographer.cs
C#
mit
1,014
export const TaskRequestStepType = { FileTask: "FileTask", EncodedTask: "EncodedTask" } export interface ITaskStepProperties { type: string; } export interface EncodedTaskStep extends ITaskStepProperties { values: Value[]; contextPath: string; contextAccessToken: string; encodedTaskContent: string; encodedValuesContent: string; } export interface IFileTaskStep extends ITaskStepProperties { contextPath: string; contextAccessToken: string; taskFilePath: string; valuesFilePath: string; } export class Value { name: string; value: string; isSecret: boolean; } export class TaskStep { build? : string; push?: string[]; } export class TaskJson { version: string; steps: TaskStep[]; } export interface IOverrideTaskStepProperties { arguments: string[]; values: Value[]; contextPath: string; } export interface ITaskRunRequest { type: "TaskRunRequest"; taskId: string; taskName: string; overrideTaskStepProperties: IOverrideTaskStepProperties } export interface IPlatformProperties { architecture: string; os: string; variant: string; } export interface IBaseImageTrigger { status: string; baseImageTriggerType: string; name: string; updateTriggerEndpoint: string; updateTriggerPayloadType: string; } export interface ITrigger { baseImageTrigger: IBaseImageTrigger; } export interface IAgentConfiguration { cpu: string; } export interface IAcrTaskRequestBodyProperties { platform: IPlatformProperties; step: ITaskStepProperties; agentConfiguration?: IAgentConfiguration; trigger?: ITrigger; } export interface IAcrTaskRequestBody { location: string; identity: {}; tags: { [key: string] : string }; properties: IAcrTaskRequestBodyProperties; } export class OutputImage { registry: string; repository: string; tag: string; digest: string; }
Microsoft/vso-agent-tasks
Tasks/ACRTaskV0/models/acrtaskrequestbody.ts
TypeScript
mit
1,800
from django.core.exceptions import ImproperlyConfigured from django.db.models import get_model class TimePeriodMixin(object): '''Will add the currently active time period to the template context or False if no active time period. Configuration: `time_period_model`: The model class that implements TimePeriodBase. `time_period_queryset`: If not set TimePeriod.current is used In Django 1.5 and above: If the app that implements `TimePeriod` is the same as the one the current request is on and that app's urls has `app_name` configured in `urls.py` model can be automatically found. I.e.: url(r'^test/', include('test_app.urls', namespace='test', app_name='test_app')), Raises: ImproperlyConfigured: If no model has been defined ''' _model = None time_period_model = None time_period_queryset = None def get_time_period_model(self): if self._model: return self._model model = self.time_period_model if model is None: if hasattr(self.request, 'resolver_match'): model = get_model(self.request.resolver_match.app_name, 'TimePeriod') if not model: raise ImproperlyConfigured( '`time_period_model` is not set for TimePeriod.' ) self._model = model return model def get_time_period_queryset(self): if self.time_period_queryset is None: model = self.get_time_period_model() return model.current else: return self.time_period_queryset def get_time_period(self): model = self.get_time_period_model() queryset = self.get_time_period_queryset() try: return queryset.get() except model.DoesNotExist: return False def get_context_data(self, **kwargs): context = super(TimePeriodMixin, self).get_context_data(**kwargs) context['time_period'] = self.get_time_period() return context
Mercy-Nekesa/sokoapp
sokoapp/contests/views.py
Python
mit
2,091
/** * Created by Liza on 21.07.2015. */ var pixi = require("pixi.js") var Point = pixi.Point; var Tracker = require('../core').Tracker; function Train(way, resources) { pixi.Container.call(this); this.carSize = 90/2;//way.segments[0].rails.scale.x; this.offset = 2; this.wheels = []; this.way = way; this.maxVelocity = 100; this.velocity = 0; this.traction = 2; this.traveled = 0; this.traveledTime = 0; this.resources = resources; this.wagon = []; var w = 192; for (var i=0;i<32;i++) { this.wagon.push(new pixi.Texture(resources['wagon'].texture, new pixi.Rectangle((i&7) * w, (i>>3) * w, w, w))); } this.loco = []; for (var i=0;i<32;i++) { this.loco.push(new pixi.Texture(resources['loco'].texture, new pixi.Rectangle((i&7) * w, (i>>3) * w, w, w))); } } Train.prototype = Object.create(pixi.Container.prototype); Train.prototype.constructor = Train; module.exports = Train; Train.prototype.init = function(carCount, options, listener) { carCount = carCount || 1; var way = this.way; for (var i=0;i<carCount; i++) { var p = (this.carSize + this.offset) * i + this.carSize / 2; this.wheels.push(new Tracker(p - this.carSize / 2, way.segments[0])); this.wheels.push(new Tracker(p + this.carSize / 2, way.segments[0])); } this.cars = []; for (var i=0;i<carCount; i++) { var spr = new pixi.Sprite((i==0 || i==carCount-1)? this.loco[0]: this.wagon[0]); spr.anchor.x = spr.anchor.y = 0.5; spr.position.y = -10; this.cars.push(spr); } this.listener = listener; this.update(0, options); } Train.prototype.sync = function() { var rail = this.wheels[0].rail; var pos = this.wheels[0].pos; for (var i=0;i<this.cars.length; i++) { var p = (this.carSize + this.offset) * i + this.carSize / 2; this.wheels[i*2].rail = rail; this.wheels[i*2].pos = pos + p - this.carSize/2; this.wheels[i*2+1].rail = rail; this.wheels[i*2+1].pos = pos + p + this.carSize/2; } } Train.prototype.frontWheel = function() { return this.wheels[this.wheels.length-1]; } Train.prototype.backWheel = function() { return this.wheels[0]; } Train.prototype.update = function (dt, options) { this.sync(); this.maxVelocity = (options.trainMaxSpeed - options.trainStartSpeed ) * Math.min(1, this.traveled / options.trainDistanceBeforeMaxSpeed) + options.trainStartSpeed; this.way.level.randomWay = this.maxVelocity >= options.trainRandomWaySpeed; this.traveled += dt * this.velocity; this.traveledTime += dt; for (var i = 0; i<this.cars.length;i++) { var car = this.cars[i]; var back = this.wheels[i*2], front = this.wheels[i*2+1]; front.move(dt * this.velocity); back.move(dt * this.velocity); var p1 = front.getPos(); var p2 = back.getPos(); car.position.x = (p1.x+p2.x)/2; car.position.y = (p1.y+p2.y)/2 - 6; if (Math.abs(p2.x-p1.x) + Math.abs(p2.y- p1.y) > 1e-5) { var ang = Math.atan2(p2.y - p1.y, p2.x - p1.x); var ang2 = Math.round(ang / (Math.PI / 16)); ang -= ang2 * (Math.PI/16); var ang3 = (ang2 + 72)%32; var t = (i==0 || i== this.cars.length-1)?this.loco:this.wagon; if (i >= this.cars.length/2) car.texture = t[ang3]; else car.texture = t[(ang3+16)%32]; car.rotation = ang; } } var p = this.coord = this.frontWheel().pos + this.frontWheel().rail.coord; var obstacles = this.way.obstacles; var acc = this.maxVelocity / this.traction; var vel = this.velocity; var newVel = Math.min(this.maxVelocity, vel + acc * dt); var w = this.backWheel(); var b = w.pos + w.rail.coord; var near = 0, nearDist = 10000; for (var i=0;i<obstacles.length;i++){ var obst = obstacles[i]; if (obst.state<2) { var c = obst.coord - p - 10; if (c < nearDist) { near = obst; nearDist = c; } if (c <= vel*vel / 2 / acc && (obst.state==0 || c <= vel * obst.timeLeft)) { newVel = Math.max(0, Math.min(vel - acc * dt, newVel)); } if (c <= options.showTipDistance && obst.state == 0 && !obst.shown) { this.listener && this.listener.onshow(obst); obst.shown = true; } } //TODO: move it into RUNNER code if (obst.state == 3 && obst.coord + this.carSize *3/5 < b) { obst.state = 4; } if (!obst.shown && obst.state == 5) { this.listener && this.listener.onshow(obst); obst.shown = true; } if (obst.state == 4 || obst.state==5) { obst.coord = b; w.rail.pointAt(w.pos, obst.position); if (obst.state == 5 && obst.spr && obst.spr.dieIn < 1e-3) { this.listener && this.listener.onend(obst); } } } this.velocity = newVel; if (newVel < 1e-3 && nearDist < 20) { this.listener && this.listener.onend(near); } };
szhigunov/railways
src/game/Train.js
JavaScript
mit
5,243
/* * Swampfile.js * * This file is a Swamp configurations file generated automatically * * Copyright (c) 2014 Udi Talias * Licensed under the MIT license. * https://github.com/uditalias/swamp/blob/master/LICENSE */ module.exports = function(swamp) { swamp.config({ params : { base_path:process.cwd() }, options: { silence: false, monitor: { cpu: true, memory: true }, dashboard: { hostname: 'localhost', port: 2121, autoLaunch: true } }, environments: [ { name: "development", PORT: 8080 }, { name: "production", PORT: 80 } ], services: [ { name: "test-app1", description: "test app 1", path: "<%= params.base_path %>", command: "python", args: ["python-app.py"], options: { autorun: true, defaultEnv: 'development', restartOnChange: false, runForever: true, maxRetries: -1 }, environments: [ { name: "development", PORT: 9999 }, ] }, ] }); }
uditalias/swamp
test/bats/valid/Swampfile.js
JavaScript
mit
1,578
var signalExit = require('signal-exit') var spawn = require('child_process').spawn var crossSpawn = require('cross-spawn-async') var fs = require('fs') var which = require('which') function needsCrossSpawn (exe) { if (process.platform !== 'win32') { return false } try { exe = which.sync(exe) } catch (er) { // failure to find the file? cmd probably needed. return true } if (/\.(com|cmd|bat)$/i.test(exe)) { // need cmd.exe to run command and batch files return true } var buffer = new Buffer(150) try { var fd = fs.openSync(exe, 'r') fs.readSync(fd, buffer, 0, 150, 0) } catch (e) { // If it's not an actual file, probably it needs cmd.exe. // also, would be unsafe to test arbitrary memory on next line! return true } return /\#\!(.+)/i.test(buffer.toString().trim()) } module.exports = function (program, args, cb) { var arrayIndex = arguments.length if (typeof args === 'function') { cb = args args = undefined } else { cb = Array.prototype.slice.call(arguments).filter(function (arg, i) { if (typeof arg === 'function') { arrayIndex = i return true } })[0] } cb = cb || function (done) { return done() } if (Array.isArray(program)) { args = program.slice(1) program = program[0] } else if (!Array.isArray(args)) { args = [].slice.call(arguments, 1, arrayIndex) } var spawnfn = needsCrossSpawn(program) ? crossSpawn : spawn var child = spawnfn(program, args, { stdio: 'inherit' }) var childExited = false signalExit(function (code, signal) { child.kill(signal || 'SIGHUP') }) child.on('close', function (code, signal) { // Allow the callback to inspect the child’s exit code and/or modify it. process.exitCode = signal ? 128 + signal : code cb(function () { childExited = true if (signal) { // If there is nothing else keeping the event loop alive, // then there's a race between a graceful exit and getting // the signal to this process. Put this timeout here to // make sure we're still alive to get the signal, and thus // exit with the intended signal code. setTimeout(function () {}, 200) process.kill(process.pid, signal) } else { // Equivalent to process.exit() on Node.js >= 0.11.8 process.exit(process.exitCode) } }) }) return child }
Goldtean/addition-goldtean
node_modules/foreground-child/index.js
JavaScript
mit
2,445
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.CodeAnalysis.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(IPreviewFactoryService)), Shared] internal class PreviewFactoryService : ForegroundThreadAffinitizedObject, IPreviewFactoryService { private const double DefaultZoomLevel = 0.75; private readonly ITextViewRoleSet _previewRoleSet; private readonly ITextBufferFactoryService _textBufferFactoryService; private readonly IContentTypeRegistryService _contentTypeRegistryService; private readonly IProjectionBufferFactoryService _projectionBufferFactoryService; private readonly IEditorOptionsFactoryService _editorOptionsFactoryService; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IDifferenceBufferFactoryService _differenceBufferService; private readonly IWpfDifferenceViewerFactoryService _differenceViewerService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewFactoryService( IThreadingContext threadingContext, ITextBufferFactoryService textBufferFactoryService, IContentTypeRegistryService contentTypeRegistryService, IProjectionBufferFactoryService projectionBufferFactoryService, ITextEditorFactoryService textEditorFactoryService, IEditorOptionsFactoryService editorOptionsFactoryService, ITextDifferencingSelectorService differenceSelectorService, IDifferenceBufferFactoryService differenceBufferService, IWpfDifferenceViewerFactoryService differenceViewerService) : base(threadingContext) { Contract.ThrowIfFalse(ThreadingContext.HasMainThread); _textBufferFactoryService = textBufferFactoryService; _contentTypeRegistryService = contentTypeRegistryService; _projectionBufferFactoryService = projectionBufferFactoryService; _editorOptionsFactoryService = editorOptionsFactoryService; _differenceSelectorService = differenceSelectorService; _differenceBufferService = differenceBufferService; _differenceViewerService = differenceViewerService; _previewRoleSet = textEditorFactoryService.CreateTextViewRoleSet( TextViewRoles.PreviewRole, PredefinedTextViewRoles.Analyzable); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken) { return GetSolutionPreviews(oldSolution, newSolution, DefaultZoomLevel, cancellationToken); } public SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: The order in which previews are added to the below list is significant. // Preview for a changed document is preferred over preview for changed references and so on. var previewItems = new List<SolutionPreviewItem>(); SolutionChangeSummary changeSummary = null; if (newSolution != null) { var solutionChanges = newSolution.GetChanges(oldSolution); var ignoreUnchangeableDocuments = oldSolution.Workspace.IgnoreUnchangeableDocumentsWhenApplyingChanges; foreach (var projectChanges in solutionChanges.GetProjectChanges()) { cancellationToken.ThrowIfCancellationRequested(); var projectId = projectChanges.ProjectId; var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // Exclude changes to unchangeable documents if they will be ignored when applied to workspace. foreach (var documentId in projectChanges.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true, ignoreUnchangeableDocuments)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateChangedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateAddedDocumentPreviewViewAsync(newSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c => CreateRemovedDocumentPreviewViewAsync(oldSolution.GetDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetChangedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateChangedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateAddedAdditionalDocumentPreviewViewAsync(newSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedAdditionalDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c => CreateRemovedAdditionalDocumentPreviewViewAsync(oldSolution.GetAdditionalDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetChangedAnalyzerConfigDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateChangedAnalyzerConfigDocumentPreviewViewAsync(oldSolution.GetAnalyzerConfigDocument(documentId), newSolution.GetAnalyzerConfigDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetAddedAnalyzerConfigDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(documentId.ProjectId, documentId, c => CreateAddedAnalyzerConfigDocumentPreviewViewAsync(newSolution.GetAnalyzerConfigDocument(documentId), zoomLevel, c))); } foreach (var documentId in projectChanges.GetRemovedAnalyzerConfigDocuments()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, documentId, c => CreateRemovedAnalyzerConfigDocumentPreviewViewAsync(oldSolution.GetAnalyzerConfigDocument(documentId), zoomLevel, c))); } foreach (var metadataReference in projectChanges.GetAddedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_reference_0_to_1, metadataReference.Display, oldProject.Name))); } foreach (var metadataReference in projectChanges.GetRemovedMetadataReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_reference_0_from_1, metadataReference.Display, oldProject.Name))); } foreach (var projectReference in projectChanges.GetAddedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_reference_0_to_1, newSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var projectReference in projectChanges.GetRemovedProjectReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_reference_0_from_1, oldSolution.GetProject(projectReference.ProjectId).Name, oldProject.Name))); } foreach (var analyzer in projectChanges.GetAddedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Adding_analyzer_reference_0_to_1, analyzer.Display, oldProject.Name))); } foreach (var analyzer in projectChanges.GetRemovedAnalyzerReferences()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(oldProject.Id, null, string.Format(EditorFeaturesResources.Removing_analyzer_reference_0_from_1, analyzer.Display, oldProject.Name))); } } foreach (var project in solutionChanges.GetAddedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.Adding_project_0, project.Name))); } foreach (var project in solutionChanges.GetRemovedProjects()) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(project.Id, null, string.Format(EditorFeaturesResources.Removing_project_0, project.Name))); } foreach (var projectChanges in solutionChanges.GetProjectChanges().Where(ProjectReferencesChanged)) { cancellationToken.ThrowIfCancellationRequested(); previewItems.Add(new SolutionPreviewItem(projectChanges.OldProject.Id, null, string.Format(EditorFeaturesResources.Changing_project_references_for_0, projectChanges.OldProject.Name))); } changeSummary = new SolutionChangeSummary(oldSolution, newSolution, solutionChanges); } return new SolutionPreviewResult(ThreadingContext, previewItems, changeSummary); } private bool ProjectReferencesChanged(ProjectChanges projectChanges) { var oldProjectReferences = projectChanges.OldProject.ProjectReferences.ToDictionary(r => r.ProjectId); var newProjectReferences = projectChanges.NewProject.ProjectReferences.ToDictionary(r => r.ProjectId); // These are the set of project reference that remained in the project. We don't care // about project references that were added or removed. Those will already be reported. var preservedProjectIds = oldProjectReferences.Keys.Intersect(newProjectReferences.Keys); foreach (var projectId in preservedProjectIds) { var oldProjectReference = oldProjectReferences[projectId]; var newProjectReference = newProjectReferences[projectId]; if (!oldProjectReference.Equals(newProjectReference)) { return true; } } return false; } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateAddedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateAddedDocumentPreviewViewCoreAsync(ITextBuffer newBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.Adding_0_to_1_with_content_colon, document.Name, document.Project.Name); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); var span = new SnapshotSpan(newBuffer.CurrentSnapshot, Span.FromBounds(0, newBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(null, workspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } private Task<object> CreateAddedTextDocumentPreviewViewAsync( TextDocument document, double zoomLevel, Func<TextDocument, CancellationToken, ITextBuffer> createBuffer, Action<Workspace, DocumentId> openTextDocument, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var newBuffer = createBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var rightWorkspace = new PreviewWorkspace( document.Project.Solution.WithTextDocumentText(document.Id, newBuffer.AsTextContainer().CurrentText)); openTextDocument(rightWorkspace, document.Id); return CreateAddedDocumentPreviewViewCoreAsync(newBuffer, rightWorkspace, document, zoomLevel, cancellationToken); } public Task<object> CreateAddedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { return CreateAddedTextDocumentPreviewViewAsync( document, zoomLevel, createBuffer: (textDocument, cancellationToken) => CreateNewBuffer((Document)textDocument, cancellationToken), openTextDocument: (workspace, documentId) => workspace.OpenDocument(documentId), cancellationToken); } public Task<object> CreateAddedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { return CreateAddedTextDocumentPreviewViewAsync( document, zoomLevel, createBuffer: CreateNewPlainTextBuffer, openTextDocument: (workspace, documentId) => workspace.OpenAdditionalDocument(documentId), cancellationToken); } public Task<object> CreateAddedAnalyzerConfigDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { return CreateAddedTextDocumentPreviewViewAsync( document, zoomLevel, createBuffer: CreateNewPlainTextBuffer, openTextDocument: (workspace, documentId) => workspace.OpenAnalyzerConfigDocument(documentId), cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, CancellationToken cancellationToken) { return CreateRemovedDocumentPreviewViewAsync(document, DefaultZoomLevel, cancellationToken); } private Task<object> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var firstLine = string.Format(EditorFeaturesResources.Removing_0_from_1_with_content_colon, document.Name, document.Project.Name); var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List<object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); return CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } private Task<object> CreateRemovedTextDocumentPreviewViewAsync( TextDocument document, double zoomLevel, Func<TextDocument, CancellationToken, ITextBuffer> createBuffer, Func<Solution, DocumentId, Solution> removeTextDocument, Func<Solution, DocumentId, string, SourceText, Solution> addTextDocument, Action<Workspace, DocumentId> openTextDocument, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and possibly open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = createBuffer(document, cancellationToken); // Create PreviewWorkspace around the buffer to be displayed in the diff preview // so that all IDE services (colorizer, squiggles etc.) light up in this buffer. var leftDocumentId = DocumentId.CreateNewId(document.Project.Id); var solutionWithRemovedDocument = removeTextDocument(document.Project.Solution, document.Id); var leftSolution = addTextDocument(solutionWithRemovedDocument, leftDocumentId, document.Name, oldBuffer.AsTextContainer().CurrentText); var leftDocument = leftSolution.GetTextDocument(leftDocumentId); var leftWorkspace = new PreviewWorkspace(leftSolution); openTextDocument(leftWorkspace, leftDocument.Id); return CreateRemovedDocumentPreviewViewCoreAsync(oldBuffer, leftWorkspace, leftDocument, zoomLevel, cancellationToken); } public Task<object> CreateRemovedDocumentPreviewViewAsync(Document document, double zoomLevel, CancellationToken cancellationToken) { return CreateRemovedTextDocumentPreviewViewAsync( document, zoomLevel, createBuffer: (textDocument, cancellationToken) => CreateNewBuffer((Document)textDocument, cancellationToken), removeTextDocument: (solution, documentId) => solution.RemoveDocument(documentId), addTextDocument: (solution, documentId, name, text) => solution.AddDocument(documentId, name, text), openTextDocument: (workspace, documentId) => workspace.OpenDocument(documentId), cancellationToken); } public Task<object> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { return CreateRemovedTextDocumentPreviewViewAsync( document, zoomLevel, createBuffer: CreateNewPlainTextBuffer, removeTextDocument: (solution, documentId) => solution.RemoveAdditionalDocument(documentId), addTextDocument: (solution, documentId, name, text) => solution.AddAdditionalDocument(documentId, name, text), openTextDocument: (workspace, documentId) => workspace.OpenAdditionalDocument(documentId), cancellationToken); } public Task<object> CreateRemovedAnalyzerConfigDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { return CreateRemovedTextDocumentPreviewViewAsync( document, zoomLevel, createBuffer: CreateNewPlainTextBuffer, removeTextDocument: (solution, documentId) => solution.RemoveAnalyzerConfigDocument(documentId), addTextDocument: (solution, documentId, name, text) => solution.AddAnalyzerConfigDocument(documentId, name, text), openTextDocument: (workspace, documentId) => workspace.OpenAnalyzerConfigDocument(documentId), cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { return CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, DefaultZoomLevel, cancellationToken); } public Task<object> CreateChangedDocumentPreviewViewAsync(Document oldDocument, Document newDocument, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. // We also need to show the spans that are in conflict. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); var description = default(string); var allSpans = default(NormalizedSpanCollection); if (newDocument.SupportsSyntaxTree) { var newRoot = newDocument.GetSyntaxRootSynchronously(cancellationToken); var conflictNodes = newRoot.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind); var conflictSpans = conflictNodes.Select(n => n.Span.ToSpan()).ToList(); var conflictDescriptions = conflictNodes.SelectMany(n => n.GetAnnotations(ConflictAnnotation.Kind)) .Select(a => $"❌ {ConflictAnnotation.GetDescription(a)}") .Distinct(); var warningNodes = newRoot.GetAnnotatedNodesAndTokens(WarningAnnotation.Kind); var warningSpans = warningNodes.Select(n => n.Span.ToSpan()).ToList(); var warningDescriptions = warningNodes.SelectMany(n => n.GetAnnotations(WarningAnnotation.Kind)) .Select(a => $"⚠ {WarningAnnotation.GetDescription(a)}") .Distinct(); var suppressDiagnosticsNodes = newRoot.GetAnnotatedNodesAndTokens(SuppressDiagnosticsAnnotation.Kind); var suppressDiagnosticsSpans = suppressDiagnosticsNodes.Select(n => n.Span.ToSpan()).ToList(); AttachAnnotationsToBuffer(newBuffer, conflictSpans, warningSpans, suppressDiagnosticsSpans); description = conflictSpans.Count == 0 && warningSpans.Count == 0 ? null : string.Join(Environment.NewLine, conflictDescriptions.Concat(warningDescriptions)); allSpans = new NormalizedSpanCollection(conflictSpans.Concat(warningSpans).Concat(changedSpans)); } else { allSpans = new NormalizedSpanCollection(changedSpans); } var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, allSpans, cancellationToken); if (!originalLineSpans.Any()) { // This means that we have no differences (likely because of conflicts). // In such cases, use the same spans for the left (old) buffer as the right (new) buffer. originalLineSpans = changedLineSpans; } // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocument = oldDocument.Project .RemoveDocument(oldDocument.Id) .AddDocument(oldDocument.Name, oldBuffer.AsTextContainer().CurrentText, oldDocument.Folders, oldDocument.FilePath); var leftWorkspace = new PreviewWorkspace(leftDocument.Project.Solution); leftWorkspace.OpenDocument(leftDocument.Id); var rightWorkspace = new PreviewWorkspace( newDocument.WithText(newBuffer.AsTextContainer().CurrentText).Project.Solution); rightWorkspace.OpenDocument(newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkspace, zoomLevel, cancellationToken); } // NOTE: We are only sharing this code between additional documents and analyzer config documents, // which are essentially plain text documents. Regular source documents need special handling // and hence have a different implementation. private Task<object> CreateChangedAdditionalOrAnalyzerConfigDocumentPreviewViewAsync( TextDocument oldDocument, TextDocument newDocument, double zoomLevel, Func<Solution, DocumentId, Solution> removeTextDocument, Func<Solution, DocumentId, string, SourceText, Solution> addTextDocument, Func<Solution, DocumentId, SourceText, PreservationMode, Solution> withDocumentText, Action<Workspace, DocumentId> openTextDocument, CancellationToken cancellationToken) { Debug.Assert(oldDocument.Kind == TextDocumentKind.AdditionalDocument || oldDocument.Kind == TextDocumentKind.AnalyzerConfigDocument); cancellationToken.ThrowIfCancellationRequested(); // Note: We don't use the original buffer that is associated with oldDocument // (and currently open in the editor) for oldBuffer below. This is because oldBuffer // will be used inside a projection buffer inside our inline diff preview below // and platform's implementation currently has a bug where projection buffers // are being leaked. This leak means that if we use the original buffer that is // currently visible in the editor here, the projection buffer span calculation // would be triggered every time user changes some code in this buffer (even though // the diff view would long have been dismissed by the time user edits the code) // resulting in crashes. Instead we create a new buffer from the same content. // TODO: We could use ITextBufferCloneService instead here to clone the original buffer. var oldBuffer = CreateNewPlainTextBuffer(oldDocument, cancellationToken); var newBuffer = CreateNewPlainTextBuffer(newDocument, cancellationToken); // Convert the diffs to be line based. // Compute the diffs between the old text and the new. var diffResult = ComputeEditDifferences(oldDocument, newDocument, cancellationToken); // Need to show the spans in the right that are different. var originalSpans = GetOriginalSpans(diffResult, cancellationToken); var changedSpans = GetChangedSpans(diffResult, cancellationToken); string description = null; var originalLineSpans = CreateLineSpans(oldBuffer.CurrentSnapshot, originalSpans, cancellationToken); var changedLineSpans = CreateLineSpans(newBuffer.CurrentSnapshot, changedSpans, cancellationToken); // TODO: Why aren't we attaching conflict / warning annotations here like we do for regular documents above? // Create PreviewWorkspaces around the buffers to be displayed on the left and right // so that all IDE services (colorizer, squiggles etc.) light up in these buffers. var leftDocumentId = DocumentId.CreateNewId(oldDocument.Project.Id); var solutionWithRemovedDocument = removeTextDocument(oldDocument.Project.Solution, oldDocument.Id); var leftSolution = addTextDocument(solutionWithRemovedDocument, leftDocumentId, oldDocument.Name, oldBuffer.AsTextContainer().CurrentText); var leftWorkspace = new PreviewWorkspace(leftSolution); openTextDocument(leftWorkspace, leftDocumentId); var rightWorkSpace = new PreviewWorkspace( withDocumentText(oldDocument.Project.Solution, oldDocument.Id, newBuffer.AsTextContainer().CurrentText, PreservationMode.PreserveValue)); openTextDocument(rightWorkSpace, newDocument.Id); return CreateChangedDocumentViewAsync( oldBuffer, newBuffer, description, originalLineSpans, changedLineSpans, leftWorkspace, rightWorkSpace, zoomLevel, cancellationToken); } public Task<object> CreateChangedAdditionalDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken) { return CreateChangedAdditionalOrAnalyzerConfigDocumentPreviewViewAsync( oldDocument, newDocument, zoomLevel, removeTextDocument: (solution, documentId) => solution.RemoveAdditionalDocument(documentId), addTextDocument: (solution, documentId, name, text) => solution.AddAdditionalDocument(documentId, name, text), withDocumentText: (solution, documentId, newText, mode) => solution.WithAdditionalDocumentText(documentId, newText, mode), openTextDocument: (workspace, documentId) => workspace.OpenAdditionalDocument(documentId), cancellationToken); } public Task<object> CreateChangedAnalyzerConfigDocumentPreviewViewAsync(TextDocument oldDocument, TextDocument newDocument, double zoomLevel, CancellationToken cancellationToken) { return CreateChangedAdditionalOrAnalyzerConfigDocumentPreviewViewAsync( oldDocument, newDocument, zoomLevel, removeTextDocument: (solution, documentId) => solution.RemoveAnalyzerConfigDocument(documentId), addTextDocument: (solution, documentId, name, text) => solution.AddAnalyzerConfigDocument(documentId, name, text), withDocumentText: (solution, documentId, newText, mode) => solution.WithAnalyzerConfigDocumentText(documentId, newText, mode), openTextDocument: (workspace, documentId) => workspace.OpenAnalyzerConfigDocument(documentId), cancellationToken); } private Task<object> CreateChangedDocumentViewAsync(ITextBuffer oldBuffer, ITextBuffer newBuffer, string description, List<LineSpan> originalSpans, List<LineSpan> changedSpans, PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!(originalSpans.Any() && changedSpans.Any())) { // Both line spans must be non-empty. Otherwise, below projection buffer factory API call will throw. // So if either is empty (signaling that there are no changes to preview in the document), then we bail out. // This can happen in cases where the user has already applied the fix and light bulb has already been dismissed, // but platform hasn't cancelled the preview operation yet. Since the light bulb has already been dismissed at // this point, the preview that we return will never be displayed to the user. So returning null here is harmless. return SpecializedTasks.Null<object>(); } var originalBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, oldBuffer.CurrentSnapshot, "...", description, originalSpans.ToArray()); var changedBuffer = _projectionBufferFactoryService.CreateProjectionBufferWithoutIndentation( _contentTypeRegistryService, _editorOptionsFactoryService.GlobalOptions, newBuffer.CurrentSnapshot, "...", description, changedSpans.ToArray()); return CreateNewDifferenceViewerAsync(leftWorkspace, rightWorkspace, originalBuffer, changedBuffer, zoomLevel, cancellationToken); } private static void AttachAnnotationsToBuffer( ITextBuffer newBuffer, IEnumerable<Span> conflictSpans, IEnumerable<Span> warningSpans, IEnumerable<Span> suppressDiagnosticsSpans) { // Attach the spans to the buffer. newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.ConflictSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, conflictSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.WarningSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, warningSpans)); newBuffer.Properties.AddProperty(PredefinedPreviewTaggerKeys.SuppressDiagnosticsSpansKey, new NormalizedSnapshotSpanCollection(newBuffer.CurrentSnapshot, suppressDiagnosticsSpans)); } private ITextBuffer CreateNewBuffer(Document document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // is it okay to create buffer from threads other than UI thread? var contentTypeService = document.GetLanguageService<IContentTypeLanguageService>(); var contentType = contentTypeService.GetDefaultContentType(); return _textBufferFactoryService.CreateTextBuffer( document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private ITextBuffer CreateNewPlainTextBuffer(TextDocument document, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var contentType = _textBufferFactoryService.TextContentType; return _textBufferFactoryService.CreateTextBuffer( document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString(), contentType); } private async Task<object> CreateNewDifferenceViewerAsync( PreviewWorkspace leftWorkspace, PreviewWorkspace rightWorkspace, IProjectionBuffer originalBuffer, IProjectionBuffer changedBuffer, double zoomLevel, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // leftWorkspace can be null if the change is adding a document. // rightWorkspace can be null if the change is removing a document. // However both leftWorkspace and rightWorkspace can't be null at the same time. Contract.ThrowIfTrue((leftWorkspace == null) && (rightWorkspace == null)); var diffBuffer = _differenceBufferService.CreateDifferenceBuffer( originalBuffer, changedBuffer, new StringDifferenceOptions(), disableEditing: true); var diffViewer = _differenceViewerService.CreateDifferenceView(diffBuffer, _previewRoleSet); diffViewer.Closed += (s, e) => { // Workaround Editor bug. The editor has an issue where they sometimes crash when // trying to apply changes to projection buffer. So, when the user actually invokes // a SuggestedAction we may then edit a text buffer, which the editor will then // try to propagate through the projections we have here over that buffer. To ensure // that that doesn't happen, we clear out the projections first so that this crash // won't happen. originalBuffer.DeleteSpans(0, originalBuffer.CurrentSnapshot.SpanCount); changedBuffer.DeleteSpans(0, changedBuffer.CurrentSnapshot.SpanCount); leftWorkspace?.Dispose(); leftWorkspace = null; rightWorkspace?.Dispose(); rightWorkspace = null; }; const string DiffOverviewMarginName = "deltadifferenceViewerOverview"; if (leftWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.RightViewOnly; diffViewer.RightView.ZoomLevel *= zoomLevel; diffViewer.RightHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else if (rightWorkspace == null) { diffViewer.ViewMode = DifferenceViewMode.LeftViewOnly; diffViewer.LeftView.ZoomLevel *= zoomLevel; diffViewer.LeftHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } else { diffViewer.ViewMode = DifferenceViewMode.Inline; diffViewer.InlineView.ZoomLevel *= zoomLevel; diffViewer.InlineHost.GetTextViewMargin(DiffOverviewMarginName).VisualElement.Visibility = Visibility.Collapsed; } // Disable focus / tab stop for the diff viewer. diffViewer.RightView.VisualElement.Focusable = false; diffViewer.LeftView.VisualElement.Focusable = false; diffViewer.InlineView.VisualElement.Focusable = false; // This code path must be invoked on UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. await diffViewer.SizeToFitAsync(ThreadingContext).ConfigureAwait(true); leftWorkspace?.EnableDiagnostic(); rightWorkspace?.EnableDiagnostic(); return new DifferenceViewerPreview(diffViewer); } private List<LineSpan> CreateLineSpans(ITextSnapshot textSnapshot, NormalizedSpanCollection allSpans, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var result = new List<LineSpan>(); foreach (var span in allSpans) { cancellationToken.ThrowIfCancellationRequested(); var lineSpan = GetLineSpan(textSnapshot, span); MergeLineSpans(result, lineSpan); } return result; } // Find the lines that surround the span of the difference. Try to expand the span to // include both the previous and next lines so that we can show more context to the // user. private LineSpan GetLineSpan( ITextSnapshot snapshot, Span span) { var startLine = snapshot.GetLineNumberFromPosition(span.Start); var endLine = snapshot.GetLineNumberFromPosition(span.End); if (startLine > 0) { startLine--; } if (endLine < snapshot.LineCount) { endLine++; } return LineSpan.FromBounds(startLine, endLine); } // Adds a line span to the spans we've been collecting. If the line span overlaps or // abuts a previous span then the two are merged. private static void MergeLineSpans(List<LineSpan> lineSpans, LineSpan nextLineSpan) { if (lineSpans.Count > 0) { var lastLineSpan = lineSpans.Last(); // We merge them if there's no more than one line between the two. Otherwise // we'd show "..." between two spans where we could just show the actual code. if (nextLineSpan.Start >= lastLineSpan.Start && nextLineSpan.Start <= (lastLineSpan.End + 1)) { nextLineSpan = LineSpan.FromBounds(lastLineSpan.Start, nextLineSpan.End); lineSpans.RemoveAt(lineSpans.Count - 1); } } lineSpans.Add(nextLineSpan); } private IHierarchicalDifferenceCollection ComputeEditDifferences(TextDocument oldDocument, TextDocument newDocument, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Get the text that's actually in the editor. var oldText = oldDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var newText = newDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); // Defer to the editor to figure out what changes the client made. var diffService = _differenceSelectorService.GetTextDifferencingService( oldDocument.Project.LanguageServices.GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService ??= _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(oldText.ToString(), newText.ToString(), new StringDifferenceOptions() { DifferenceType = StringDifferenceTypes.Word | StringDifferenceTypes.Line, }); } private NormalizedSpanCollection GetOriginalSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } private NormalizedSpanCollection GetChangedSpans(IHierarchicalDifferenceCollection diffResult, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var lineSpans = new List<Span>(); foreach (var difference in diffResult) { cancellationToken.ThrowIfCancellationRequested(); var mappedSpan = diffResult.RightDecomposition.GetSpanInOriginal(difference.Right); lineSpans.Add(mappedSpan); } return new NormalizedSpanCollection(lineSpans); } } }
abock/roslyn
src/EditorFeatures/Core.Wpf/Preview/PreviewFactoryService.cs
C#
mit
48,130
# -*- coding: utf-8 -*- import sys from influxdb import chunked_json if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestChunkJson(unittest.TestCase): @classmethod def setUpClass(cls): super(TestChunkJson, cls).setUpClass() def test_load(self): """ Tests reading a sequence of JSON values from a string """ example_response = \ '{"results": [{"series": [{"measurement": "sdfsdfsdf", ' \ '"columns": ["time", "value"], "values": ' \ '[["2009-11-10T23:00:00Z", 0.64]]}]}, {"series": ' \ '[{"measurement": "cpu_load_short", "columns": ["time", "value"],'\ '"values": [["2009-11-10T23:00:00Z", 0.64]]}]}]}' res = list(chunked_json.loads(example_response)) # import ipdb; ipdb.set_trace() # self.assertTrue(res) self.assertListEqual( [ { 'results': [ {'series': [{ 'values': [['2009-11-10T23:00:00Z', 0.64]], 'measurement': 'sdfsdfsdf', 'columns': ['time', 'value']}]}, {'series': [{ 'values': [['2009-11-10T23:00:00Z', 0.64]], 'measurement': 'cpu_load_short', 'columns': ['time', 'value']}]} ] } ], res )
georgijd/influxdb-python
influxdb/tests/chunked_json_test.py
Python
mit
1,565
//----------------------------------------------------------------------- // <copyright file="SerializationRoot.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.Serialization { [Serializable()] public class SerializationRoot : BusinessBase<SerializationRoot> { public static PropertyInfo<string> DataProperty = RegisterProperty<string>(c => c.Data, RelationshipTypes.PrivateField); private string _data = DataProperty.DefaultValue; public string Data { get { return GetProperty(DataProperty, _data); } set { SetProperty(DataProperty, ref _data, value); } } protected override void OnDeserialized(System.Runtime.Serialization.StreamingContext context) { base.OnDeserialized(context); Csla.ApplicationContext.GlobalContext.Add("Deserialized", true); Console.WriteLine("OnDeserialized"); } } }
BrettJaner/csla
Source/Csla.test/Serialization/SerializationRoot.cs
C#
mit
1,152
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define({ "_widgetLabel": "Анализ стоимости", "unableToFetchInfoErrMessage": "Невозможно вызвать информацию слоя сервиса геометрии/настроенного", "invalidCostingGeometryLayer": "Невозможно получить 'esriFieldTypeGlobalID' в слое геометрии расчета стоимости.", "projectLayerNotFound": "Невозможно найти настроенный слой проекта на карте.", "costingGeometryLayerNotFound": "Невозможно найти настроенный слой геометрии расчета стоимости на карте.", "projectMultiplierTableNotFound": "Невозможно найти настроенную таблицу множителя добавочной стоимости проекта на карте.", "projectAssetTableNotFound": "Невозможно найти настроенную таблицу объектов проекта на карте.", "createLoadProject": { "createProjectPaneTitle": "Создать проект", "loadProjectPaneTitle": "Загрузить проект", "projectNamePlaceHolder": "Название проекта", "projectDescPlaceHolder": "Описание проекта", "selectProject": "Выбрать проект", "viewInMapLabel": "Просмотреть на карте", "loadLabel": "Загрузить", "createLabel": "Создать", "deleteProjectConfirmationMsg": "Вы уверены, что хотите удалить проект?", "noAssetsToViewOnMap": "В выбранном проекте нет объектов для показа на карте.", "projectDeletedMsg": "Проект успешно удален.", "errorInCreatingProject": "Ошибка создания проекта.", "errorProjectNotFound": "Проект не найден.", "errorInLoadingProject": "Проверьте, что выбран корректный проект.", "errorProjectNotSelected": "Выбрать проект в ниспадающем списке", "errorDuplicateProjectName": "Имя проекта уже существует.", "errorFetchingPointLabel": "Ошибка при получении подписи точки. Повторите попытку еще раз", "errorAddingPointLabel": "Ошибка при добавлении подписи точки. Повторите попытку еще раз" }, "statisticsSettings": { "tabTitle": "Настройки статистики", "addStatisticsLabel": "Добавить статистику", "addNewStatisticsText": "Добавить новую статистику", "deleteStatisticsText": "Удалить статистику", "moveStatisticsUpText": "Переместить статистику вверх", "moveStatisticsDownText": "Переместить статистику вниз", "layerNameTitle": "Слой", "statisticsTypeTitle": "Тип", "fieldNameTitle": "Поле", "statisticsTitle": "Подпись", "actionLabelTitle": "Действия", "selectDeselectAllTitle": "Выбрать все", "layerCheckbox": "Отметка слоя" }, "statisticsType": { "countLabel": "Количество", "averageLabel": "Среднее арифметическое", "maxLabel": "Максимум", "minLabel": "Минимум", "summationLabel": "Суммирование", "areaLabel": "Площадь", "lengthLabel": "Длина" }, "costingInfo": { "noEditableLayersAvailable": "Слои, которые должны быть отмечена как редактируемые на вкладке настроек слоя" }, "workBench": { "refresh": "Обновить", "noAssetAddedMsg": "Нет добавленный объектов", "units": "единицы измерения", "assetDetailsTitle": "Информация об элементе объекта", "costEquationTitle": "Уравнение стоимости", "newCostEquationTitle": "Новое уравнение", "defaultCostEquationTitle": "Уравнение по умолчанию", "geographyTitle": "География", "scenarioTitle": "Сценарий", "costingInfoHintText": "<div>Подсказка: Используйте следующие ключевые слова</div><ul><li><b>{TOTALCOUNT}</b>: Использует общее число объектов одного типа в географии</li> <li><b>{MEASURE}</b>: Использует длину для линейных объектов и площадь для полигональных</li><li><b>{TOTALMEASURE}</b>: Использует общую длину для линейных объектов и общую площадь для полигональных объектов одинакового типа в географии</li></ul> Можно использовать функции, например:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Отредактируйте уравнение стоимости, как необходимо для проекта.", "zoomToAsset": "Приблизить к объекту", "deleteAsset": "Удалить объект", "closeDialog": "Закрыть диалог", "objectIdColTitle": "Object Id", "costColTitle": "Стоимость", "errorInvalidCostEquation": "Недопустимое уравнение стоимости.", "errorInSavingAssetDetails": "Невозможно сохранить информацию об объекте.", "featureModeText": "Режим объекта", "sketchToolTitle": "Скетч", "selectToolTitle": "Выбрать", "downloadCSVBtnTitle": "Экспорт отчета" }, "assetDetails": { "inGeography": " в ${geography} ", "withScenario": " в ${scenario}", "totalCostTitle": "Общая стоимость", "additionalCostLabel": "Описание", "additionalCostValue": "Значение", "additionalCostNetValue": "Общее значение" }, "projectOverview": { "assetItemsTitle": "Элементы объекта", "assetStatisticsTitle": "Статистика объекта", "projectSummaryTitle": "Краткая информация проекта", "projectName": "Имя проекта: ${name}", "totalCostLabel": "Общая стоимость проекта (*):", "grossCostLabel": "Валовая стоимость проекта (*):", "roundingLabel": "* Округление до '${selectedRoundingOption}'", "unableToSaveProjectBoundary": "Невозможно сохранить границы проекта в слое проекта.", "unableToSaveProjectCost": "Невозможно сохранить стоимости в слое проекта.", "roundCostValues": { "twoDecimalPoint": "Два десятичных знака", "nearestWholeNumber": "Ближайшее целое число", "nearestTen": "Ближайшие десять", "nearestHundred": "Ближайшие сто", "nearestThousand": "Ближайшие тысяча", "nearestTenThousands": "Ближайшие десять тысяч" } }, "projectAttribute": { "projectAttributeText": "Атрибут проекта", "projectAttributeTitle": "Редактировать атрибуты проекта" }, "costEscalation": { "costEscalationLabel": "Добавить добавочную стоимость", "valueHeader": "Значение", "addCostEscalationText": "Добавить добавочную стоимость", "deleteCostEscalationText": "Удалить выбранную добавочную стоимость", "moveCostEscalationUpText": "Переместить вверх выбранную добавочную стоимость", "moveCostEscalationDownText": "Переместить вниз выбранную добавочную стоимость", "invalidEntry": "Одна или несколько записей некорректны.", "errorInSavingCostEscalation": "Невозможно сохранить информацию о добавочной стоимости." }, "scenarioSelection": { "popupTitle": "Выбрать сценарий для объекта", "regionLabel": "География", "scenarioLabel": "Сценарий", "noneText": "Нет", "copyFeatureMsg": "Хотите копировать выбранные объекты?" }, "detailStatistics": { "detailStatisticsLabel": "Подробности статистики", "noDetailStatisticAvailable": "Статистика объекта не добавлена" }, "copyFeatures": { "title": "Копировать объекты", "createFeatures": "Создать объекты", "createSingleFeature": "Создать 1 объект множественной геометрии", "noFeaturesSelectedMessage": "Отсутствуют выбранные объекты", "selectFeatureToCopyMessage": "Выберите объект для копирования." }, "updateCostEquationPanel": { "updateProjectCostTabLabel": "Обновить уравнения проекта", "updateProjectCostSelectProjectTitle": "Выбрать все проекты", "updateButtonTextForm": "Обновление", "updateProjectCostSuccess": "Уравнения стоимости обновлены для выбранных проектов", "updateProjectCostError": "Невозможно обновить уравнение стоимости для выбранных проектов", "updateProjectNoProject": "Проекты не найдены" } });
tmcgee/cmv-wab-widgets
wab/2.15/widgets/CostAnalysis/nls/ru/strings.js
JavaScript
mit
10,806
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2016, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** @file Implementation of the STL importer class */ #ifndef ASSIMP_BUILD_NO_STL_IMPORTER // internal headers #include "STLLoader.h" #include "ParsingUtils.h" #include "fast_atof.h" #include <memory> #include <assimp/IOSystem.hpp> #include <assimp/scene.h> #include <assimp/DefaultLogger.hpp> using namespace Assimp; namespace { static const aiImporterDesc desc = { "Stereolithography (STL) Importer", "", "", "", aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour, 0, 0, 0, 0, "stl" }; // A valid binary STL buffer should consist of the following elements, in order: // 1) 80 byte header // 2) 4 byte face count // 3) 50 bytes per face static bool IsBinarySTL(const char* buffer, unsigned int fileSize) { if( fileSize < 84 ) { return false; } const uint32_t faceCount = *reinterpret_cast<const uint32_t*>(buffer + 80); const uint32_t expectedBinaryFileSize = faceCount * 50 + 84; return expectedBinaryFileSize == fileSize; } // An ascii STL buffer will begin with "solid NAME", where NAME is optional. // Note: The "solid NAME" check is necessary, but not sufficient, to determine // if the buffer is ASCII; a binary header could also begin with "solid NAME". static bool IsAsciiSTL(const char* buffer, unsigned int fileSize) { if (IsBinarySTL(buffer, fileSize)) return false; const char* bufferEnd = buffer + fileSize; if (!SkipSpaces(&buffer)) return false; if (buffer + 5 >= bufferEnd) return false; bool isASCII( strncmp( buffer, "solid", 5 ) == 0 ); if( isASCII ) { // A lot of importers are write solid even if the file is binary. So we have to check for ASCII-characters. if( fileSize >= 500 ) { isASCII = true; for( unsigned int i = 0; i < 500; i++ ) { if( buffer[ i ] > 127 ) { isASCII = false; break; } } } } return isASCII; } } // namespace // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer STLImporter::STLImporter() : mBuffer(), fileSize(), pScene() {} // ------------------------------------------------------------------------------------------------ // Destructor, private as well STLImporter::~STLImporter() {} // ------------------------------------------------------------------------------------------------ // Returns whether the class can handle the format of the given file. bool STLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const { const std::string extension = GetExtension(pFile); if( extension == "stl" ) { return true; } else if (!extension.length() || checkSig) { if( !pIOHandler ) { return true; } const char* tokens[] = {"STL","solid"}; return SearchFileHeaderForToken(pIOHandler,pFile,tokens,2); } return false; } // ------------------------------------------------------------------------------------------------ const aiImporterDesc* STLImporter::GetInfo () const { return &desc; } void addFacesToMesh(aiMesh* pMesh) { pMesh->mFaces = new aiFace[pMesh->mNumFaces]; for (unsigned int i = 0, p = 0; i < pMesh->mNumFaces;++i) { aiFace& face = pMesh->mFaces[i]; face.mIndices = new unsigned int[face.mNumIndices = 3]; for (unsigned int o = 0; o < 3;++o,++p) { face.mIndices[o] = p; } } } // ------------------------------------------------------------------------------------------------ // Imports the given file into the given scene structure. void STLImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) { std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb")); // Check whether we can read from the file if( file.get() == NULL) { throw DeadlyImportError( "Failed to open STL file " + pFile + "."); } fileSize = (unsigned int)file->FileSize(); // allocate storage and copy the contents of the file to a memory buffer // (terminate it with zero) std::vector<char> mBuffer2; TextFileToBuffer(file.get(),mBuffer2); this->pScene = pScene; this->mBuffer = &mBuffer2[0]; // the default vertex color is light gray. clrColorDefault.r = clrColorDefault.g = clrColorDefault.b = clrColorDefault.a = 0.6; // allocate a single node pScene->mRootNode = new aiNode(); bool bMatClr = false; if (IsBinarySTL(mBuffer, fileSize)) { bMatClr = LoadBinaryFile(); } else if (IsAsciiSTL(mBuffer, fileSize)) { LoadASCIIFile(); } else { throw DeadlyImportError( "Failed to determine STL storage representation for " + pFile + "."); } // add all created meshes to the single node pScene->mRootNode->mNumMeshes = pScene->mNumMeshes; pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes]; for (unsigned int i = 0; i < pScene->mNumMeshes; i++) pScene->mRootNode->mMeshes[i] = i; // create a single default material, using a light gray diffuse color for consistency with // other geometric types (e.g., PLY). aiMaterial* pcMat = new aiMaterial(); aiString s; s.Set(AI_DEFAULT_MATERIAL_NAME); pcMat->AddProperty(&s, AI_MATKEY_NAME); aiColor4D clrDiffuse(0.6,0.6,0.6,1.0); if (bMatClr) { clrDiffuse = clrColorDefault; } pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE); pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR); clrDiffuse = aiColor4D(0.05,0.05,0.05,1.0); pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT); pScene->mNumMaterials = 1; pScene->mMaterials = new aiMaterial*[1]; pScene->mMaterials[0] = pcMat; } // ------------------------------------------------------------------------------------------------ // Read an ASCII STL file void STLImporter::LoadASCIIFile() { std::vector<aiMesh*> meshes; const char* sz = mBuffer; const char* bufferEnd = mBuffer + fileSize; std::vector<aiVector3D> positionBuffer; std::vector<aiVector3D> normalBuffer; // try to guess how many vertices we could have // assume we'll need 160 bytes for each face size_t sizeEstimate = std::max(1u, fileSize / 160u ) * 3; positionBuffer.reserve(sizeEstimate); normalBuffer.reserve(sizeEstimate); while (IsAsciiSTL(sz, bufferEnd - sz)) { aiMesh* pMesh = new aiMesh(); pMesh->mMaterialIndex = 0; meshes.push_back(pMesh); SkipSpaces(&sz); ai_assert(!IsLineEnd(sz)); sz += 5; // skip the "solid" SkipSpaces(&sz); const char* szMe = sz; while (!::IsSpaceOrNewLine(*sz)) { sz++; } size_t temp; // setup the name of the node if ((temp = (size_t)(sz-szMe))) { if (temp >= MAXLEN) { throw DeadlyImportError( "STL: Node name too long" ); } pScene->mRootNode->mName.length = temp; memcpy(pScene->mRootNode->mName.data,szMe,temp); pScene->mRootNode->mName.data[temp] = '\0'; } else pScene->mRootNode->mName.Set("<STL_ASCII>"); unsigned int faceVertexCounter = 0; for ( ;; ) { // go to the next token if(!SkipSpacesAndLineEnd(&sz)) { // seems we're finished although there was no end marker DefaultLogger::get()->warn("STL: unexpected EOF. \'endsolid\' keyword was expected"); break; } // facet normal -0.13 -0.13 -0.98 if (!strncmp(sz,"facet",5) && IsSpaceOrNewLine(*(sz+5)) && *(sz + 5) != '\0') { if (faceVertexCounter != 3) { DefaultLogger::get()->warn("STL: A new facet begins but the old is not yet complete"); } faceVertexCounter = 0; normalBuffer.push_back(aiVector3D()); aiVector3D* vn = &normalBuffer.back(); sz += 6; SkipSpaces(&sz); if (strncmp(sz,"normal",6)) { DefaultLogger::get()->warn("STL: a facet normal vector was expected but not found"); } else { if (sz[6] == '\0') { throw DeadlyImportError("STL: unexpected EOF while parsing facet"); } sz += 7; SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x ); SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y ); SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z ); normalBuffer.push_back(*vn); normalBuffer.push_back(*vn); } } // vertex 1.50000 1.50000 0.00000 else if (!strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6))) { if (faceVertexCounter >= 3) { DefaultLogger::get()->error("STL: a facet with more than 3 vertices has been found"); ++sz; } else { if (sz[6] == '\0') { throw DeadlyImportError("STL: unexpected EOF while parsing facet"); } sz += 7; SkipSpaces(&sz); positionBuffer.push_back(aiVector3D()); aiVector3D* vn = &positionBuffer.back(); sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x ); SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y ); SkipSpaces(&sz); sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z ); faceVertexCounter++; } } else if (!::strncmp(sz,"endsolid",8)) { do { ++sz; } while (!::IsLineEnd(*sz)); SkipSpacesAndLineEnd(&sz); // finished! break; } // else skip the whole identifier else { do { ++sz; } while (!::IsSpaceOrNewLine(*sz)); } } if (positionBuffer.empty()) { pMesh->mNumFaces = 0; throw DeadlyImportError("STL: ASCII file is empty or invalid; no data loaded"); } if (positionBuffer.size() % 3 != 0) { pMesh->mNumFaces = 0; throw DeadlyImportError("STL: Invalid number of vertices"); } if (normalBuffer.size() != positionBuffer.size()) { pMesh->mNumFaces = 0; throw DeadlyImportError("Normal buffer size does not match position buffer size"); } pMesh->mNumFaces = positionBuffer.size() / 3; pMesh->mNumVertices = positionBuffer.size(); pMesh->mVertices = new aiVector3D[pMesh->mNumVertices]; memcpy(pMesh->mVertices, &positionBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D)); positionBuffer.clear(); pMesh->mNormals = new aiVector3D[pMesh->mNumVertices]; memcpy(pMesh->mNormals, &normalBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D)); normalBuffer.clear(); // now copy faces addFacesToMesh(pMesh); } // now add the loaded meshes pScene->mNumMeshes = (unsigned int)meshes.size(); pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]; for (size_t i = 0; i < meshes.size(); i++) { pScene->mMeshes[i] = meshes[i]; } } // ------------------------------------------------------------------------------------------------ // Read a binary STL file bool STLImporter::LoadBinaryFile() { // allocate one mesh pScene->mNumMeshes = 1; pScene->mMeshes = new aiMesh*[1]; aiMesh* pMesh = pScene->mMeshes[0] = new aiMesh(); pMesh->mMaterialIndex = 0; // skip the first 80 bytes if (fileSize < 84) { throw DeadlyImportError("STL: file is too small for the header"); } bool bIsMaterialise = false; // search for an occurrence of "COLOR=" in the header const unsigned char* sz2 = (const unsigned char*)mBuffer; const unsigned char* const szEnd = sz2+80; while (sz2 < szEnd) { if ('C' == *sz2++ && 'O' == *sz2++ && 'L' == *sz2++ && 'O' == *sz2++ && 'R' == *sz2++ && '=' == *sz2++) { // read the default vertex color for facets bIsMaterialise = true; DefaultLogger::get()->info("STL: Taking code path for Materialise files"); clrColorDefault.r = (*sz2++) / 255.0; clrColorDefault.g = (*sz2++) / 255.0; clrColorDefault.b = (*sz2++) / 255.0; clrColorDefault.a = (*sz2++) / 255.0; break; } } const unsigned char* sz = (const unsigned char*)mBuffer + 80; // now read the number of facets pScene->mRootNode->mName.Set("<STL_BINARY>"); pMesh->mNumFaces = *((uint32_t*)sz); sz += 4; if (fileSize < 84 + pMesh->mNumFaces*50) { throw DeadlyImportError("STL: file is too small to hold all facets"); } if (!pMesh->mNumFaces) { throw DeadlyImportError("STL: file is empty. There are no facets defined"); } pMesh->mNumVertices = pMesh->mNumFaces*3; aiVector3D* vp,*vn; vp = pMesh->mVertices = new aiVector3D[pMesh->mNumVertices]; vn = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices]; for (unsigned int i = 0; i < pMesh->mNumFaces;++i) { // NOTE: Blender sometimes writes empty normals ... this is not // our fault ... the RemoveInvalidData helper step should fix that *vn = *((aiVector3D*)sz); sz += sizeof(aiVector3D); *(vn+1) = *vn; *(vn+2) = *vn; vn += 3; *vp++ = *((aiVector3D*)sz); sz += sizeof(aiVector3D); *vp++ = *((aiVector3D*)sz); sz += sizeof(aiVector3D); *vp++ = *((aiVector3D*)sz); sz += sizeof(aiVector3D); uint16_t color = *((uint16_t*)sz); sz += 2; if (color & (1 << 15)) { // seems we need to take the color if (!pMesh->mColors[0]) { pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices]; for (unsigned int i = 0; i <pMesh->mNumVertices;++i) *pMesh->mColors[0]++ = this->clrColorDefault; pMesh->mColors[0] -= pMesh->mNumVertices; DefaultLogger::get()->info("STL: Mesh has vertex colors"); } aiColor4D* clr = &pMesh->mColors[0][i*3]; clr->a = 1.0; if (bIsMaterialise) // this is reversed { clr->r = (color & 0x31u) / 31.0; clr->g = ((color & (0x31u<<5))>>5u) / 31.0; clr->b = ((color & (0x31u<<10))>>10u) / 31.0; } else { clr->b = (color & 0x31u) / 31.0; clr->g = ((color & (0x31u<<5))>>5u) / 31.0; clr->r = ((color & (0x31u<<10))>>10u) / 31.0; } // assign the color to all vertices of the face *(clr+1) = *clr; *(clr+2) = *clr; } } // now copy faces addFacesToMesh(pMesh); if (bIsMaterialise && !pMesh->mColors[0]) { // use the color as diffuse material color return true; } return false; } #endif // !! ASSIMP_BUILD_NO_STL_IMPORTER
Polynominal/Lucy3D
Dependencies/assimp/code/STLLoader.cpp
C++
mit
17,739
import template from './_ngmodule_.html'; export let =ngmodule=Component = { template, selector: '_ngmodule_', // add ng1 directive definition directiveSelector: () => console.log('=ngmodule=', '-> change this'), controllerAs: '$ctrl', scope: { }, bindToController: true, replace: true, restrict: 'E', controller: class =ngmodule=Ctrl { /* @ngInject */ constructor () { // Object.assign(this, ...arguments); } } };
orizens/echoes
config/templates/_ngmodule_/_ngmodule_.component.js
JavaScript
mit
439
require 'rubygems' require 'test/unit' require 'fileutils' require 'active_record' require 'logger' # ------------------------------------------------------ # Setup AR environment # ------------------------------------------------------ # Define connection info ActiveRecord::Base.configurations = { "test" => { :adapter => 'sqlite3', :database => ':memory:' } } ActiveRecord::Base.establish_connection("test") # Setup logger tmp = File.expand_path('../../tmp', __FILE__) FileUtils.mkdir_p(tmp) ActiveRecord::Base.logger = Logger.new("#{tmp}/debug.log") # ------------------------------------------------------ # Inject audit-trascer # and setup test schema # and define models used in tests # ------------------------------------------------------ require "ar-audit-tracer" require "resources/schema.rb" require "resources/models.rb"
verticonaut/ar-audit-tracer
test/helper.rb
Ruby
mit
858
from nose.tools import raises from tests.test_stack import TestConfig, app_from_config from tg.util import no_warn from tg.configuration import config from tg.configuration import milestones from tg.decorators import Decoration, decode_params import tg import json def make_app(): base_config = TestConfig(folder = 'rendering', values = {'use_sqlalchemy': False, 'use_legacy_renderer': False, # this is specific to mako # to make sure inheritance works 'use_dotted_templatenames': False, 'use_toscawidgets': False, 'use_toscawidgets2': False } ) return app_from_config(base_config) class TestTGController(object): def setup(self): self.app = make_app() def test_simple_jsonification(self): resp = self.app.get('/j/json') expected = {"a": "hello world", "b": True} assert expected == resp.json_body def test_multi_dispatch_json(self): resp = self.app.get('/j/xml_or_json', headers={'accept':'application/json'}) assert '''"status": "missing"''' in resp assert '''"name": "John Carter"''' in resp assert '''"title": "officer"''' in resp def test_json_with_object(self): resp = self.app.get('/j/json_with_object') assert '''"Json": "Rocks"''' in str(resp.body) @no_warn def test_json_with_bad_object(self): try: resp = self.app.get('/j/json_with_bad_object') assert False except Exception as e: assert "is not JSON serializable" in str(e), str(e) def test_multiple_engines(self): default_renderer = config['default_renderer'] resp = self.app.get('/multiple_engines') assert default_renderer in resp, resp def test_decode_params_json(self): params = {'name': 'Name', 'surname': 'Surname'} resp = self.app.post_json('/echo_json', params) assert resp.json_body == params @raises(ValueError) def test_decode_params_notjson(self): @decode_params('xml') def _fakefunc(): pass class TestExposeInheritance(object): def setup(self): self.app = make_app() def test_inherited_expose_template(self): resp1 = self.app.get('/sub1/index') resp2 = self.app.get('/sub2/index') assert resp1.body == resp2.body def test_inherited_expose_override(self): resp1 = self.app.get('/sub1/index_override') resp2 = self.app.get('/sub2/index_override') assert resp1.body != resp2.body def test_inherited_expose_hooks(self): resp1 = self.app.get('/sub1/data') assert ('"v"' in resp1 and '"parent_value"' in resp1) resp2 = self.app.get('/sub2/data') assert ('"v"' in resp2 and '"parent_value"' in resp2 and '"child_value"' in resp2) class TestExposeLazyInheritance(object): def test_lazy_inheritance(self): milestones.renderers_ready._reset() class BaseController(tg.TGController): @tg.expose('template.html') def func(self): pass class SubController(BaseController): @tg.expose(inherit=True) def func(self): pass milestones.renderers_ready.reach() deco = Decoration.get_decoration(SubController.func) assert len(deco.engines) == 1, deco.engines assert deco.engines['text/html'][1] == 'template.html', deco.engines def test_lazy_inheritance_with_template(self): milestones.renderers_ready._reset() class BaseController(tg.TGController): @tg.expose('template.html') def func(self): pass class SubController(BaseController): @tg.expose('new_template.html', inherit=True) def func(self): pass milestones.renderers_ready.reach() deco = Decoration.get_decoration(SubController.func) assert len(deco.engines) == 1, deco.engines assert deco.engines['text/html'][1] == 'new_template.html', deco.engines def test_lazy_inheritance_with_nested_template(self): milestones.renderers_ready._reset() class BaseController(tg.TGController): @tg.expose('template.html') @tg.expose('template.html', content_type='text/plain') def func(self): pass class SubController(BaseController): @tg.expose('new_template.html', inherit=True) @tg.expose('new_template.html', content_type='text/plain') def func(self): pass class SubSubController(SubController): @tg.expose('new2_template.html', inherit=True) def func(self): pass milestones.renderers_ready.reach() deco = Decoration.get_decoration(SubSubController.func) assert len(deco.engines) == 2, deco.engines assert deco.engines['text/html'][1] == 'new2_template.html', deco.engines assert deco.engines['text/plain'][1] == 'new_template.html', deco.engines def test_lazy_inheritance_with_3nested_template(self): milestones.renderers_ready._reset() class BaseController(tg.TGController): @tg.expose('template.html') @tg.expose('template.html', content_type='text/plain') @tg.expose('template.html', content_type='text/javascript') def func(self): pass class SubController(BaseController): @tg.expose('new_template.html', inherit=True) @tg.expose('new_template.html', content_type='text/plain') @tg.expose('new_template.html', content_type='text/javascript') def func(self): pass class SubSubController(SubController): @tg.expose('new2_template.html', inherit=True) @tg.expose('new2_template.html', content_type='text/javascript') def func(self): pass class SubSubSubController(SubSubController): @tg.expose('new3_template.html', inherit=True) def func(self): pass milestones.renderers_ready.reach() deco = Decoration.get_decoration(SubSubSubController.func) assert len(deco.engines) == 3, deco.engines assert deco.engines['text/html'][1] == 'new3_template.html', deco.engines assert deco.engines['text/plain'][1] == 'new_template.html', deco.engines assert deco.engines['text/javascript'][1] == 'new2_template.html', deco.engines
lucius-feng/tg2
tests/test_stack/rendering/test_decorators.py
Python
mit
6,861