code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package opentipbot.persistence.model; /** * @author Gilles Cadignan */ public enum OpenTipBotCommandStatus { NEW,PENDING,PROCESSED,ERROR; }
gill3s/opentipbot
opentipbot-persistence/src/main/java/opentipbot/persistence/model/OpenTipBotCommandStatus.java
Java
mit
147
import traverse from "../../../traversal"; import object from "../../../helpers/object"; import * as util from "../../../util"; import * as t from "../../../types"; import values from "lodash/object/values"; import extend from "lodash/object/extend"; function isLet(node, parent) { if (!t.isVariableDeclaration(node)) return false; if (node._let) return true; if (node.kind !== "let") return false; // https://github.com/babel/babel/issues/255 if (isLetInitable(node, parent)) { for (var i = 0; i < node.declarations.length; i++) { var declar = node.declarations[i]; declar.init ||= t.identifier("undefined"); } } node._let = true; node.kind = "var"; return true; } function isLetInitable(node, parent) { return !t.isFor(parent) || !t.isFor(parent, { left: node }); } function isVar(node, parent) { return t.isVariableDeclaration(node, { kind: "var" }) && !isLet(node, parent); } function standardizeLets(declars) { for (var i = 0; i < declars.length; i++) { delete declars[i]._let; } } export function check(node) { return t.isVariableDeclaration(node) && (node.kind === "let" || node.kind === "const"); } export function VariableDeclaration(node, parent, scope, file) { if (!isLet(node, parent)) return; if (isLetInitable(node) && file.transformers["es6.blockScopingTDZ"].canRun()) { var nodes = [node]; for (var i = 0; i < node.declarations.length; i++) { var decl = node.declarations[i]; if (decl.init) { var assign = t.assignmentExpression("=", decl.id, decl.init); assign._ignoreBlockScopingTDZ = true; nodes.push(t.expressionStatement(assign)); } decl.init = file.addHelper("temporal-undefined"); } node._blockHoist = 2; return nodes; } } export function Loop(node, parent, scope, file) { var init = node.left || node.init; if (isLet(init, node)) { t.ensureBlock(node); node.body._letDeclarators = [init]; } var blockScoping = new BlockScoping(this, node.body, parent, scope, file); return blockScoping.run(); } export function BlockStatement(block, parent, scope, file) { if (!t.isLoop(parent)) { var blockScoping = new BlockScoping(null, block, parent, scope, file); blockScoping.run(); } } export { BlockStatement as Program }; function replace(node, parent, scope, remaps) { if (!t.isReferencedIdentifier(node, parent)) return; var remap = remaps[node.name]; if (!remap) return; var ownBinding = scope.getBindingIdentifier(node.name); if (ownBinding === remap.binding) { node.name = remap.uid; } else { // scope already has it's own binding that doesn't // match the one we have a stored replacement for if (this) this.skip(); } } var replaceVisitor = { enter: replace }; function traverseReplace(node, parent, scope, remaps) { replace(node, parent, scope, remaps); scope.traverse(node, replaceVisitor, remaps); } var letReferenceBlockVisitor = { enter(node, parent, scope, state) { if (this.isFunction()) { scope.traverse(node, letReferenceFunctionVisitor, state); return this.skip(); } } }; var letReferenceFunctionVisitor = { enter(node, parent, scope, state) { // not a direct reference if (!this.isReferencedIdentifier()) return; // this scope has a variable with the same name so it couldn't belong // to our let scope if (scope.hasOwnBinding(node.name)) return; // not a part of our scope if (!state.letReferences[node.name]) return; state.closurify = true; } }; var hoistVarDeclarationsVisitor = { enter(node, parent, scope, self) { if (this.isForStatement()) { if (isVar(node.init, node)) { node.init = t.sequenceExpression(self.pushDeclar(node.init)); } } else if (this.isFor()) { if (isVar(node.left, node)) { node.left = node.left.declarations[0].id; } } else if (isVar(node, parent)) { return self.pushDeclar(node).map(t.expressionStatement); } else if (this.isFunction()) { return this.skip(); } } }; var loopLabelVisitor = { enter(node, parent, scope, state) { if (this.isLabeledStatement()) { state.innerLabels.push(node.label.name); } } }; var loopNodeTo = function (node) { if (t.isBreakStatement(node)) { return "break"; } else if (t.isContinueStatement(node)) { return "continue"; } }; var loopVisitor = { enter(node, parent, scope, state) { var replace; if (this.isLoop()) { state.ignoreLabeless = true; scope.traverse(node, loopVisitor, state); state.ignoreLabeless = false; } if (this.isFunction() || this.isLoop()) { return this.skip(); } var loopText = loopNodeTo(node); if (loopText) { if (node.label) { // we shouldn't be transforming this because it exists somewhere inside if (state.innerLabels.indexOf(node.label.name) >= 0) { return; } loopText = `${loopText}|${node.label.name}`; } else { // we shouldn't be transforming these statements because // they don't refer to the actual loop we're scopifying if (state.ignoreLabeless) return; // break statements mean something different in this context if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return; } state.hasBreakContinue = true; state.map[loopText] = node; replace = t.literal(loopText); } if (this.isReturnStatement()) { state.hasReturn = true; replace = t.objectExpression([ t.property("init", t.identifier("v"), node.argument || t.identifier("undefined")) ]); } if (replace) { replace = t.returnStatement(replace); return t.inherits(replace, node); } } }; class BlockScoping { /** * Description */ constructor(loopPath?: TraversalPath, block: Object, parent: Object, scope: Scope, file: File) { this.parent = parent; this.scope = scope; this.block = block; this.file = file; this.outsideLetReferences = object(); this.hasLetReferences = false; this.letReferences = block._letReferences = object(); this.body = []; if (loopPath) { this.loopParent = loopPath.parent; this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label; this.loop = loopPath.node; } } /** * Start the ball rolling. */ run() { var block = this.block; if (block._letDone) return; block._letDone = true; var needsClosure = this.getLetReferences(); // this is a block within a `Function/Program` so we can safely leave it be if (t.isFunction(this.parent) || t.isProgram(this.block)) return; // we can skip everything if (!this.hasLetReferences) return; if (needsClosure) { this.wrapClosure(); } else { this.remap(); } if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) { return t.labeledStatement(this.loopLabel, this.loop); } } /** * Description */ remap() { var hasRemaps = false; var letRefs = this.letReferences; var scope = this.scope; // alright, so since we aren't wrapping this block in a closure // we have to check if any of our let variables collide with // those in upper scopes and then if they do, generate a uid // for them and replace all references with it var remaps = object(); for (var key in letRefs) { // just an Identifier node we collected in `getLetReferences` // this is the defining identifier of a declaration var ref = letRefs[key]; if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { var uid = scope.generateUidIdentifier(ref.name).name; ref.name = uid; hasRemaps = true; remaps[key] = remaps[uid] = { binding: ref, uid: uid }; } } if (!hasRemaps) return; // var loop = this.loop; if (loop) { traverseReplace(loop.right, loop, scope, remaps); traverseReplace(loop.test, loop, scope, remaps); traverseReplace(loop.update, loop, scope, remaps); } scope.traverse(this.block, replaceVisitor, remaps); } /** * Description */ wrapClosure() { var block = this.block; var outsideRefs = this.outsideLetReferences; // remap loop heads with colliding variables if (this.loop) { for (var name in outsideRefs) { var id = outsideRefs[name]; if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) { delete outsideRefs[id.name]; delete this.letReferences[id.name]; this.scope.rename(id.name); this.letReferences[id.name] = id; outsideRefs[id.name] = id; } } } // if we're inside of a for loop then we search to see if there are any // `break`s, `continue`s, `return`s etc this.has = this.checkLoop(); // hoist var references to retain scope this.hoistVarDeclarations(); // turn outsideLetReferences into an array var params = values(outsideRefs); // build the closure that we're going to wrap the block with var fn = t.functionExpression(null, params, t.blockStatement(block.body)); fn._aliasFunction = true; // replace the current block body with the one we're going to build block.body = this.body; // build a call and a unique id that we can assign the return value to var call = t.callExpression(fn, params); var ret = this.scope.generateUidIdentifier("ret"); // handle generators var hasYield = traverse.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); if (hasYield) { fn.generator = true; call = t.yieldExpression(call, true); } // handlers async functions var hasAsync = traverse.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); if (hasAsync) { fn.async = true; call = t.awaitExpression(call, true); } this.build(ret, call); } /** * Description */ getLetReferences() { var block = this.block; var declarators = block._letDeclarators || []; var declar; // for (var i = 0; i < declarators.length; i++) { declar = declarators[i]; extend(this.outsideLetReferences, t.getBindingIdentifiers(declar)); } // if (block.body) { for (i = 0; i < block.body.length; i++) { declar = block.body[i]; if (isLet(declar, block)) { declarators = declarators.concat(declar.declarations); } } } // for (i = 0; i < declarators.length; i++) { declar = declarators[i]; var keys = t.getBindingIdentifiers(declar); extend(this.letReferences, keys); this.hasLetReferences = true; } // no let references so we can just quit if (!this.hasLetReferences) return; // set let references to plain var references standardizeLets(declarators); var state = { letReferences: this.letReferences, closurify: false }; // traverse through this block, stopping on functions and checking if they // contain any local let references this.scope.traverse(this.block, letReferenceBlockVisitor, state); return state.closurify; } /** * If we're inside of a loop then traverse it and check if it has one of * the following node types `ReturnStatement`, `BreakStatement`, * `ContinueStatement` and replace it with a return value that we can track * later on. * * @returns {Object} */ checkLoop() { var state = { hasBreakContinue: false, ignoreLabeless: false, innerLabels: [], hasReturn: false, isLoop: !!this.loop, map: {} }; this.scope.traverse(this.block, loopLabelVisitor, state); this.scope.traverse(this.block, loopVisitor, state); return state; } /** * Hoist all var declarations in this block to before it so they retain scope * once we wrap everything in a closure. */ hoistVarDeclarations() { traverse(this.block, hoistVarDeclarationsVisitor, this.scope, this); } /** * Turn a `VariableDeclaration` into an array of `AssignmentExpressions` with * their declarations hoisted to before the closure wrapper. */ pushDeclar(node: { type: "VariableDeclaration" }): Array<Object> { this.body.push(t.variableDeclaration(node.kind, node.declarations.map(function (declar) { return t.variableDeclarator(declar.id); }))); var replace = []; for (var i = 0; i < node.declarations.length; i++) { var declar = node.declarations[i]; if (!declar.init) continue; var expr = t.assignmentExpression("=", declar.id, declar.init); replace.push(t.inherits(expr, declar)); } return replace; } /** * Push the closure to the body. */ build(ret: { type: "Identifier" }, call: { type: "CallExpression" }) { var has = this.has; if (has.hasReturn || has.hasBreakContinue) { this.buildHas(ret, call); } else { this.body.push(t.expressionStatement(call)); } } /** * Description */ buildHas(ret: { type: "Identifier" }, call: { type: "CallExpression" }) { var body = this.body; body.push(t.variableDeclaration("var", [ t.variableDeclarator(ret, call) ])); var loop = this.loop; var retCheck; var has = this.has; var cases = []; if (has.hasReturn) { // typeof ret === "object" retCheck = util.template("let-scoping-return", { RETURN: ret }); } if (has.hasBreakContinue) { for (var key in has.map) { cases.push(t.switchCase(t.literal(key), [has.map[key]])); } if (has.hasReturn) { cases.push(t.switchCase(null, [retCheck])); } if (cases.length === 1) { var single = cases[0]; body.push(this.file.attachAuxiliaryComment(t.ifStatement( t.binaryExpression("===", ret, single.test), single.consequent[0] ))); } else { // #998 for (var i = 0; i < cases.length; i++) { var caseConsequent = cases[i].consequent[0]; if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) { caseConsequent.label = this.loopLabel ||= this.file.scope.generateUidIdentifier("loop"); } } body.push(this.file.attachAuxiliaryComment(t.switchStatement(ret, cases))); } } else { if (has.hasReturn) { body.push(this.file.attachAuxiliaryComment(retCheck)); } } } }
rwjblue/babel
src/babel/transformation/transformers/es6/block-scoping.js
JavaScript
mit
14,712
#pragma once #include "engine/core/types.h" namespace sandbox { void ecs_init_physics_clean(void); void ecs_update_physics_clean(r32 dt); }
Feacur/CustomEngineStudy
sandbox/src/game/physics_clean.h
C
mit
143
// // NSMutableString+MSOSDKAdditions.h // Pods // // Created by John Setting on 4/6/17. // // #import <Foundation/Foundation.h> @interface NSMutableString (MSOSDKAdditions) - (nullable NSMutableString *)mso_string_escape; - (nullable NSMutableString *)mso_string_unescape; @end
logicielInc/MSOSDK
MSOSDK/Extensions/NSMutableString+MSOSDKAdditions.h
C
mit
286
<?php /* * This file is part of the Shared Kernel library. * * Copyright (c) 2016-present LIN3S <info@lin3s.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace LIN3S\SharedKernel\Domain\Model\Email; /** * @author Beñat Espiña <benatespina@gmail.com> */ class Email { private $email; private $domain; private $localPart; public function __construct($anEmail) { if (!filter_var($anEmail, FILTER_VALIDATE_EMAIL)) { throw new EmailInvalidException(); } $this->email = $anEmail; $this->localPart = implode(explode('@', $this->email, -1), '@'); $this->domain = str_replace($this->localPart . '@', '', $this->email); } public function email() { return $this->email; } public function localPart() { return $this->localPart; } public function domain() { return $this->domain; } public function equals(self $anEmail) { return mb_strtolower((string) $this) === mb_strtolower((string) $anEmail); } public function __toString() { return (string) $this->email; } }
LIN3S/SharedKernel
src/LIN3S/SharedKernel/Domain/Model/Email/Email.php
PHP
mit
1,266
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class VirtualRouterPeeringsOperations(object): """VirtualRouterPeeringsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_09_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def _delete_initial( self, resource_group_name, # type: str virtual_router_name, # type: str peering_name, # type: str **kwargs # type: Any ): # type: (...) -> None cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualRouterName': self._serialize.url("virtual_router_name", virtual_router_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}'} # type: ignore def begin_delete( self, resource_group_name, # type: str virtual_router_name, # type: str peering_name, # type: str **kwargs # type: Any ): # type: (...) -> LROPoller[None] """Deletes the specified peering from a Virtual Router. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_router_name: The name of the Virtual Router. :type virtual_router_name: str :param peering_name: The name of the peering. :type peering_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._delete_initial( resource_group_name=resource_group_name, virtual_router_name=virtual_router_name, peering_name=peering_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualRouterName': self._serialize.url("virtual_router_name", virtual_router_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}'} # type: ignore def get( self, resource_group_name, # type: str virtual_router_name, # type: str peering_name, # type: str **kwargs # type: Any ): # type: (...) -> "_models.VirtualRouterPeering" """Gets the specified Virtual Router Peering. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_router_name: The name of the Virtual Router. :type virtual_router_name: str :param peering_name: The name of the Virtual Router Peering. :type peering_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: VirtualRouterPeering, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_09_01.models.VirtualRouterPeering :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualRouterPeering"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualRouterName': self._serialize.url("virtual_router_name", virtual_router_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('VirtualRouterPeering', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}'} # type: ignore def _create_or_update_initial( self, resource_group_name, # type: str virtual_router_name, # type: str peering_name, # type: str parameters, # type: "_models.VirtualRouterPeering" **kwargs # type: Any ): # type: (...) -> "_models.VirtualRouterPeering" cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualRouterPeering"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualRouterName': self._serialize.url("virtual_router_name", virtual_router_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'VirtualRouterPeering') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VirtualRouterPeering', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VirtualRouterPeering', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}'} # type: ignore def begin_create_or_update( self, resource_group_name, # type: str virtual_router_name, # type: str peering_name, # type: str parameters, # type: "_models.VirtualRouterPeering" **kwargs # type: Any ): # type: (...) -> LROPoller["_models.VirtualRouterPeering"] """Creates or updates the specified Virtual Router Peering. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_router_name: The name of the Virtual Router. :type virtual_router_name: str :param peering_name: The name of the Virtual Router Peering. :type peering_name: str :param parameters: Parameters supplied to the create or update Virtual Router Peering operation. :type parameters: ~azure.mgmt.network.v2019_09_01.models.VirtualRouterPeering :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either VirtualRouterPeering or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.network.v2019_09_01.models.VirtualRouterPeering] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualRouterPeering"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, virtual_router_name=virtual_router_name, peering_name=peering_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VirtualRouterPeering', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualRouterName': self._serialize.url("virtual_router_name", virtual_router_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = ARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings/{peeringName}'} # type: ignore def list( self, resource_group_name, # type: str virtual_router_name, # type: str **kwargs # type: Any ): # type: (...) -> Iterable["_models.VirtualRouterPeeringListResult"] """Lists all Virtual Router Peerings in a Virtual Router resource. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_router_name: The name of the Virtual Router. :type virtual_router_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either VirtualRouterPeeringListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2019_09_01.models.VirtualRouterPeeringListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualRouterPeeringListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualRouterName': self._serialize.url("virtual_router_name", virtual_router_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('VirtualRouterPeeringListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize.failsafe_deserialize(_models.Error, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualRouters/{virtualRouterName}/peerings'} # type: ignore
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_09_01/operations/_virtual_router_peerings_operations.py
Python
mit
22,524
--- layout: post author: 166yuan titile: 自适应设计与响应式设计 category: 前端 tag: 响应式 --- ###自适应与响应式 首先,两者是不同的东西,不要混为一谈。 ```自适应网页设计```是指自动识别屏幕宽度、并做出相应调整的网页设计。 ```响应式网页设计```是```自适应网页设计```的子集。```响应式网页设计```指的是页面的布局(流动网格、灵活的图像及媒介查询)。总体目标就是去解决设备多样化问题。 响应式布局等于流动网格布局,而```自适应布局```等于使用固定分割点来进行布局。 当固定宽度与流动宽度结合起来时,```自适应布局```就是一种响应式设计,而不仅仅是它的一种替代方法。​ ###响应式布局: 外链式的响应式: <link rel="stylesheet" media="screen and (max-width: 400px)" href="mini.css" /> Device Width:若浏览设备的可视范围最大为480px,则下方的CSS描述就会立即被套用:(注:移动手机目前常见最大宽度为480px,如iPhone or Android Phone) @media screen and (max-device-width:480px){ .class { background:#000; } } 针对iphone4 的设定 <link rel= "stylesheet" media= "only screen and (-webkit-min-device-pixel-ratio: 2)" type= "text/css" href= "iphone4.css" /> 针对iPad的Portrait Mode(直立)与Landscape Mode(横躺)两种浏览模式给予不同的css设定档: <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css"> <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css"> 2.viewport使用 <meta name="viewport" content="width=device-width, initial-scale=1.0"> viewport编译过程会转化成如下的语义: @viewport { width: device-width; initial-scale: 1.0 } 如果希望在不同device使用不同缩放大小,就必须使用javascript,检测UA(User agent),动态设定viewport,如下: viewport = document.querySelector("meta[name=viewport]"); viewport.setAttribute('content', 'width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;'); 3.不使用绝对宽度 而最好使用百分比宽度width:20%;或者with:auto; 4.字体不要用px限定,用em 附录:px pt em rem区别: px是pixel,像素,是屏幕上显示数据的最基本的点,在HTML中,默认的单位就是px; pt是point,是印刷行业常用单位,等于1/72英寸。 em才是真正的“相对单位”(百分比嘛,当然是相对),而px和pt都是绝对单位(都有固定值)。所以,一般移动终端布局用em比较合适。 rem是css3的出现,同时引进新的单位,而rem是相对于根元素<html>,这样就意味着,我们只需要在根元素确定一个参考值,在根元素中设置多大的字体,这完全可以根据您自己的需要。 5.Skill 5 流动布局(fluid grid) 流动布局的含义是各个位置都是浮动的,不是固定不变的 .main { float: right; width: 70%; } .leftBar { float: left; width: 25%; } float的好处是,如果宽度太小,放不下两个元素,后面的元素会自动滚动到前面元素的下方,不会在水平方向overflow(溢出),避免了水平滚动条的出现。 流动布局实例 ![流动1](http://7xiwi7.com1.z0.glb.clouddn.com/float.png) ![流动2](http://7xiwi7.com1.z0.glb.clouddn.com/floatall.png) 6.图片等比缩放 img{ max-width: 100%; }
166yuan/166yuan.github.io
_posts/2015-04-20-响应式页面布局.md
Markdown
mit
3,546
// // VersionName.h // // Created by Alex Bonine 07/19/2012 // #import <Cordova/CDVPlugin.h> @interface VersionName : CDVPlugin - (void) getVersionName:(CDVInvokedUrlCommand*)command; @end
alexbonine/version-name
src/ios/VersionName.h
C
mit
196
package services import ( "github.com/stretchr/testify/assert" "testing" ) func ReadJsonConfFileServiceTest(t *testing.T) { confFilename := "../testdata/fixtures/system.json" f, _ := ReadJsonConfFileService(confFilename) if len(f.Files) < 1 { t.Fatal("no Files found in " + confFilename) } var actual string = "" for i := 0; i < len(f.Files); i++ { actual = f.Files[i].Pattern break } expected := "installed.*" assert.Equal(t, expected, actual, "unexpected config pattern") }
pce/doctorlog
services/services_test.go
GO
mit
501
using SharpKit.JavaScript; using UnityEngine; using System.Collections; using System.Collections.Generic; // test System.Collections.Generic.List public class ListTest : MonoBehaviour { // Use this for initialization void Start () { } float elapsed = 0; void Update() { elapsed += Time.deltaTime; if (elapsed > 1f) { elapsed = 0f; List<int> lst = new List<int>(); lst.Add(6); lst.Add(95); foreach (var v in lst) { Debug.Log(v); } int vFind = lst.Find((val) => (val == 6)); Debug.Log("vFind = " + vFind); // var lstS = lst.ConvertAll<string>((v) => "s: " + v); // foreach (var v in lstS) // { // Debug.Log(v); // } // Debug.Log(lstS[0]); // Debug.Log(lstS[1]); } } }
linkabox/PureJSB
Assets/Scripts/JsbUnitTest/Samples/ListTest.cs
C#
mit
933
/* working */ *, *:after, *:before { box-sizing: border-box; } * {margin:0;padding:0;border: 0 none; position: relative;} :root { --sinSerif: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; --Nhexa: 4; --gap: 2vw; --size: calc(calc(100vw / var(--Nhexa)) - var(--gap)); } @media only screen and (min-width: 1100px) { :root { --Nhexa: 6; } } @media only screen and (max-width: 600px) { :root { --Nhexa: 2; } } section { /* margin: calc(var(--size) * .5) auto 0; */ margin-left:8%; margin-top:6%; width: calc(var(--size) * calc(var(--Nhexa) - .5)); display: grid; grid-template-columns: repeat(var(--Nhexa), 1fr); grid-gap: var(--gap); } article { background: cadetblue; width: var(--size); height: calc(var(--size) / 1.1111111); clip-path: url(#hexagono); clip-path: polygon(25% 0, 75% 0, 100% 50%, 75% 100%, 25% 100%, 0 50%); margin-right: calc(var(--size) / 2); color: #fff; overflow: hidden; } article:nth-child(2n) { margin: calc(var(--size) * -.5) calc(var(--size) * -.25) 0 calc(var(--size) * -.75); } #hex1 { background-image: url("Hex_imgs/ALLEN VALLEY_OVP_Hex (2).jpg"); } article::before { content: ''; float: left; width: 25%; height: 100%; clip-path: polygon(0% 0%, 100% 0%, 0% 50%, 100% 100%, 0% 100%); shape-outside: polygon(0% 0%, 100% 0%, 0% 50%, 100% 100%, 0% 100%); } article::after { content: ''; float: right; width: 25%; height: 100%; clip-path: polygon(75% 0%, 100% 0%, 100% 100%, 100% 0%); shape-outside: polygon(75% 0%, 100% 0%, 100% 100%, 100% 0%); } .hex_img { width: var(--size); height: var(--size); position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); transform-origin: 0% 50%; transition: .75s; clip-path: url(#hexagono); clip-path: inherit; z-index: 10; } article:hover { -webkit-transform:scale(1.2); transform:scale(1.2); -webkit-transition: all 0.7s ease; transition: all 0.7s ease; } figure { display: flex; flex-direction: column; flex-wrap: nowrap; justify-content: center; max-width: 50%; height: 100%; font-size: calc(9 / var(--Nhexa) * 1vw); line-height: 1; color: #fff; transition: .75s .05s; hyphens: auto; text-align: center; }
philipagardner/IRIS_Site
css/Hex_Grid2.css
CSS
mit
2,436
<!-- todolist_cms Created by keleko34, the main list for the todo app -->
keleko34/Konnekt
components/todolist/cms/todolist.html
HTML
mit
74
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * HP * * This model handles clinic management. It operates the following tables: * - HP, * - users * * @author Visions */ class Manage_hp extends CI_Model { private $table_name = 'mc_hp_info'; // HP entry private $countries_table_name = 'mc_countries'; private $users_table_name = 'mc_users'; private $table_notifications = 'mc_notifications'; private $table_hp_clinics = 'mc_hp_clinic_relation'; private $table_clinic_access = 'mc_clinic_access'; private $table_clinic_admin = 'mc_clinic_admin'; function __construct() { parent::__construct(); $ci =& get_instance(); $this->table_name = $ci->config->item('db_table_prefix', 'tank_auth').$this->table_name; $this->countries_table_name = $ci->config->item('db_table_prefix', 'tank_auth').$this->countries_table_name; $this->users_table_name = $ci->config->item('db_table_prefix', 'tank_auth').$this->users_table_name; $this->table_notifications = $ci->config->item('db_table_prefix', 'tank_auth').$this->table_notifications; $this->table_hp_clinics = $ci->config->item('db_table_prefix', 'tank_auth').$this->table_hp_clinics; $this->table_clinic_access = $ci->config->item('db_table_prefix', 'tank_auth').$this->table_clinic_access; $this->table_clinic_admin = $ci->config->item('db_table_prefix', 'tank_auth').$this->table_clinic_admin; } public function getHpList(){ $return= array(); $this->db->select("*"); $this->db->from($this->table_name .' as clist'); $this->db->join($this->users_table_name .' as users', 'users.id = clist.user_id','left'); $this->db->order_by('clist.hp_id',"DESC"); $query = $this->db->get(); if($query->num_rows()>0){ $return=$query->result(); } return $return; } public function getClinicDetail($clinic_location_id = ''){ $return= array(); $this->db->select("clist.*,clist_setting.abn_number,clist_setting.website_url,clist_setting.clinic_logo"); $this->db->from($this->clinic_table_name .' as clist'); $this->db->join($this->clinic_setting .' as clist_setting', 'clist.clinic_id = clist_setting.clinic_id','left'); $where = "(clist.location_id='".$clinic_location_id."')"; $this->db->where($where); $query = $this->db->get(); if($query->num_rows()>0){ $return=$query->row(); } return $return; } public function create_clinic($formFields) { $clinicNos = implode('::',$formFields['clinic_telephone_no']); $FaxNos = implode('::',$formFields['clinic_fax_number']); $EmailAdd = implode('::',$formFields['clinic_admin_email']); $RoomAdd = implode('::',$formFields['clinic_room']); $ipAddress = $this->mc_constants->remote_ip(); $role = $clinic = $clinicInfo = $relation = $is_suburb = $suburb_id = $city_id = ''; if($formFields['country']=='AU') { $country = 'Australia'; $returnSuburb = $this->getAusSuburbid($formFields['clinic_suburb'], $formFields['clinic_state'], $formFields['clinic_postcode']); $returnState = $this->getSurburbState($formFields['clinic_state']); $suburb_id = $returnSuburb[0]['suburb_id']; $state = $returnState['state_name']; $is_suburb = '1'; $city = ''; } else { $city_id = $formFields['clinic_city']; $cityData = $this->getCityInfo($city_id); $city = $cityData['city_name']; $state = $cityData['state_name']; $country = $cityData['country_name']; } $clinicInfo['clinic_name'] = $formFields['clinic_name']; $clinicInfo['clinic_contact_email_address'] = $EmailAdd; $clinicInfo['street_address'] = $formFields['clinic_street_address']; $clinicInfo['street_address_2'] = $formFields['clinic_street_address_line2']; $clinicInfo['is_suburb'] = $is_suburb; $clinicInfo['suburb_id'] = $suburb_id; $clinicInfo['city_id'] = $city_id; $clinicInfo['city'] = $city; $clinicInfo['status'] = $formFields['clinic_status']; $clinicInfo['suburb'] = $formFields['clinic_suburb']; $clinicInfo['state'] = $state; $clinicInfo['country'] = $country; $clinicInfo['postcode'] = $formFields['clinic_postcode']; $clinicInfo['clinic_room'] = $RoomAdd; $clinicInfo['telephone'] = $clinicNos; $clinicInfo['fax_number'] = $FaxNos; $clinicInfo['created_ip'] = $ipAddress; $clinicInfo['created_date'] = @date('Y-m-d H:i:s'); $clinicInfo['created_by'] = ''; $clinicInfo['code'] = $city."".$formFields['clinic_postcode']."".rand(5, 9999); $relation['created_ip'] = $ipAddress; $relation['created_date'] = @date('Y-m-d H:i:s'); $relation['created_by'] = ''; try { $this->db->trans_begin(); $this->db->insert($this->table_name, $clinicInfo); $clinic_location_id = $this->db->insert_id(); $this->db->trans_commit(); $ret_msg = array('return' => 1); } catch (Exception $e) { $this->db->trans_rollback(); $ret_msg = array('return' => log_message('error', sprintf('%s : %s : DB transaction failed. Error no: %s, Error msg:%s, Last query: %s', __CLASS__, __FUNCTION__, $e->getCode(), $e->getMessage(), print_r($this->main_db->last_query(), TRUE)))); } $returnArray = $ret_msg; return $returnArray; } public function update_clinic($formFields,$is_main=1) { $ret_msg = false; $ipAddress = $this->mc_constants->remote_ip(); $clinic = ''; $clinicInfo = ''; $relation = ''; $is_suburb = ''; $suburb_id = '0'; $city_id = ''; if($formFields['country']=='AU') { $country = 'Australia'; $returnSuburb = $this->getAusSuburbid($formFields['clinic_suburb'], $formFields['clinic_state'], $formFields['clinic_postcode']); $returnState = $this->getSurburbState($formFields['clinic_state']); $suburb_id = $returnSuburb[0]['suburb_id']; $state = $returnState['state_name']; $is_suburb = '1'; $city = ''; } else { $city_id = $formFields['clinic_city']; $cityData = $this->getCityInfo($city_id); $city = $cityData['city_name']; $state = $cityData['state_name']; $country = $cityData['country_name']; } $clinicNos = implode('::',$formFields['clinic_telephone_no']); $FaxNos = implode('::',$formFields['clinic_fax_number']); $EmailAdd = implode('::',$formFields['clinic_admin_email']); $RoomAdd = implode('::',$formFields['clinic_room']); $clinicInfo['clinic_name'] = $formFields['clinic_name']; $clinicInfo['clinic_contact_email_address'] = $EmailAdd; $clinicInfo['street_address'] = $formFields['clinic_street_address']; $clinicInfo['street_address_2'] = $formFields['clinic_street_address_line2']; $clinicInfo['is_suburb'] = $is_suburb; $clinicInfo['suburb_id'] = $suburb_id; $clinicInfo['city_id'] = $city_id; $clinicInfo['city'] = $city; $clinicInfo['suburb'] = $formFields['clinic_suburb']; $clinicInfo['status'] = $formFields['clinic_status']; $clinicInfo['state'] = $state; $clinicInfo['country'] = $country; $clinicInfo['postcode'] = $formFields['clinic_postcode']; $clinicInfo['clinic_room'] =$RoomAdd; $clinicInfo['telephone'] = $clinicNos; $clinicInfo['fax_number'] = $FaxNos; $clinicInfo['last_modified_ip'] = $ipAddress; $clinicInfo['last_modified_date'] = @date('Y-m-d H:i:s'); $clinicInfo['last_modified_by'] = $formFields['author_id']; try{ $this->db->trans_begin(); if($is_main==1){ $clinic['last_modified_ip'] = $ipAddress; $clinic['last_modified_date'] = date('Y-m-d H:i:s'); $clinic['last_modified_by'] = $formFields['author_id']; $this->db->update($this->table_name, $clinicInfo, array('clinic_id' => $formFields['clinic_id'])); } //$this->db->update($this->users_table_name, $userInfo, array('id' => $formFields['user_id'])); // $this->db->update($this->clinic_table_name, $clinicInfo, array('location_id' => $formFields['clinic_location_id'])); $this->db->trans_commit(); $ret_msg = true; } catch (Exception $e) { $this->db->trans_rollback(); $ret_msg = array('return' => log_message('error', sprintf('%s : %s : DB transaction failed. Error no: %s, Error msg:%s, Last query: %s', __CLASS__, __FUNCTION__, $e->getCode(), $e->getMessage(), print_r($this->main_db->last_query(), TRUE)))); } return $ret_msg; } public function enable_clinic_details($clinicID = '', $author_id = ''){ $ipAddress = $_SERVER['REMOTE_ADDR']; $clinic['status'] = '1'; $clinic['last_modified_ip'] = $ipAddress; $clinic['last_modified_date'] = date('Y-m-d H:i:s'); $clinic['last_modified_by'] = $author_id; $this->db->update($this->table_name, $clinic, array('clinic_id' => $clinicID)); //$this->db->update($this->clinic_table_name, $clinic, array('clinic_id' => $clinicID)); if ($this->db->affected_rows() == '1') { return 'success'; } else { return 'failure'; } } public function disable_clinic_details($clinicID = '', $author_id = ''){ $ipAddress = $_SERVER['REMOTE_ADDR']; $clinic['status'] = '0'; $clinic['last_modified_ip'] = $ipAddress; $clinic['last_modified_date'] = @date('Y-m-d H:i:s'); $clinic['last_modified_by'] = $author_id; $this->db->update($this->table_name, $clinic, array('clinic_id' => $clinicID)); if ($this->db->affected_rows() == '1') { return 'success'; } else { return 'failure'; } } public function getSuburb(){ $return = array(); $this->db->select("suburb_id,suburb_name"); $this->db->from($this->aus_suburb_table_name); $this->db->where('activated', '1'); $this->db->group_by('suburb_name'); $this->db->order_by("suburb_name", "asc"); $query = $this->db->get(); if($query->num_rows()>0){ foreach($query->result_array() as $sub_ary){ $return[$sub_ary['suburb_id']] = $sub_ary['suburb_name']; } } return $return; } public function getCountries() { $countries = array(); $this->db->select("id,name"); $this->db->from($this->countries_table_name); $query = $this->db->get(); $countries[''] = 'Select country'; $countries['AU'] = 'Australia'; if($query->num_rows()>0){ foreach($query->result_array() as $result) { $countries[$result['id']] = $result['name']; } } return $countries; } public function getSuburbAuto($subname = ''){ $return= array(); if($subname!=''){ $this->db->select("suburb_id,suburb_name"); $this->db->from($this->aus_suburb_table_name); $this->db->where('activated', '1'); $this->db->like('suburb_name', $subname, 'after'); $this->db->group_by('suburb_name'); $this->db->order_by("suburb_name", "asc"); $this->db->limit(70); $query = $this->db->get(); if($query->num_rows()>0){ foreach($query->result_array() as $sub_ary){ $return[$sub_ary['suburb_id']] = $sub_ary['suburb_name']; } } } return $return; } public function getAusStatesList($subname = '', $viewType = ''){ $return = array(); if($subname!=''){ $this->db->select('st.state_id, st.state_name'); $this->db->from($this->aus_suburb_table_name .' as surb'); $this->db->join($this->state_table_name .' as st', 'surb.state_id = st.state_id','inner'); $this->db->where('surb.suburb_name', $subname); $this->db->where('surb.activated', '1'); $this->db->where('st.activated', '1'); $this->db->group_by('surb.suburb_name'); $this->db->group_by('surb.state_id'); $this->db->order_by('st.state_name',"ASC"); $query = $this->db->get(); if($query->num_rows()>0){ if($viewType == 'edit_clinic') { foreach($query->result_array() as $result) { $return[$result['state_id']] = $result['state_name']; } } else { $return = $query->result_array(); } } } return $return; } public function getAusSuburbInfo($suburb_id=0){ $return = array(); if(($suburb_id!=0 && $suburb_id!='')) { $this->db->select('surb.*'); $this->db->from($this->aus_suburb_table_name .' as surb'); $this->db->where('surb.suburb_id', $suburb_id); $query = $this->db->get(); if($query->num_rows()>0){ $return = $query->result_array(); } } return $return; } public function getAusSuburbid($subname = '',$state_id=0,$postal_code=0){ $return = array(); if($subname!='' && ($state_id!=0 && $state_id!='') && ($postal_code!=0 && $postal_code!='')) { $this->db->select('surb.suburb_id'); $this->db->from($this->aus_suburb_table_name .' as surb'); $this->db->where('surb.suburb_name', $subname); $this->db->where('surb.state_id', $state_id); $this->db->where('surb.postal_code', $postal_code); $query = $this->db->get(); if($query->num_rows()>0){ $return = $query->result_array(); } } return $return; } public function getCountryStatesList($countryID = '', $viewType = ''){ $returnArray = array(); if($countryID!=''){ $this->db->select('id as state_id, name as state_name'); $this->db->from($this->states_table_name); $this->db->where('country_id', $countryID); $query = $this->db->get(); if($query->num_rows()>0){ if($viewType == 'edit_clinic') { foreach($query->result_array() as $result) { $returnArray[$result['state_id']] = $result['state_name']; } } else { $returnArray =$query->result_array(); } } } return $returnArray; } public function getStatesCitiesList($stateID = '', $viewType = ''){ $returnArray = array(); if($stateID!=''){ $this->db->select('id as city_id, name as city_name'); $this->db->from($this->cities_table_name); $this->db->where('state_id', $stateID); $query = $this->db->get(); if($query->num_rows()>0){ if($viewType == 'edit_clinic') { foreach($query->result_array() as $result) { $returnArray[$result['city_id']] = $result['city_name']; } } else { $returnArray =$query->result_array(); } } } return $returnArray; } public function getPostcodeList($stateId=0,$subname=''){ $return = array(); if($stateId!=0 && $subname!=''){ $this->db->select('suburb_id, postal_code'); $this->db->from($this->aus_suburb_table_name); $this->db->where('suburb_name', $subname); $this->db->where('activated', '1'); $this->db->where('state_id', $stateId); $this->db->group_by('suburb_name'); $this->db->group_by('state_id'); $this->db->group_by('postal_code'); $this->db->order_by('postal_code',"ASC"); $query = $this->db->get(); if($query->num_rows()>0){ $return =$query->result_array(); } } return $return; } public function getDeleteClinic($clinic_id=0){ $return=0; if($clinic_id!=0 && $clinic_id!=''){ $update_data=array('status'=>2,'end_date'=>@date('Y-m-d H:i:s')); $this->db->where('clinic_id',$clinic_id); $this->db->update($this->table_name,$update_data); $update_data2=array('status'=>2,'end_date'=>@date('Y-m-d H:i:s')); $this->db->where('clinic_id',$clinic_id); $this->db->update($this->clinic_table_name,$update_data2); $return = 1; } return $return; } public function getSurburbState($state_id=0){ $return= array(); if($state_id!=0 && $state_id!=''){ $this->db->select("state_name"); $this->db->from($this->state_table_name); $this->db->where('state_id',$state_id); $query = $this->db->get(); if($query->num_rows()>0){ $return=$query->row_array(); } } return $return; } public function getCityInfo($city_id = 0){ $return = array(); if($city_id!=0 && $city_id!='') { $this->db->select('ct.id as city_id, ct.name as city_name, st.id as state_id, st.name as state_name, cn.id as country_id, cn.name as country_name'); $this->db->from($this->cities_table_name .' as ct'); $this->db->join($this->states_table_name .' as st', 'st.id = ct.state_id','inner'); $this->db->join($this->countries_table_name .' as cn', 'cn.id = st.country_id','inner'); $this->db->where('ct.id', $city_id); $query = $this->db->get(); if($query->num_rows()>0){ $return=$query->row_array(); } } return $return; } public function getViewClinic($clinic_id = 0){ $return= array(); if($clinic_id!=0 && $clinic_id!=''){ $this->db->select("*"); $this->db->from($this->table_name .' as clist'); $where = "(status='1' OR status='0')"; $this->db->where('clinic_id',$clinic_id); $this->db->where($where); $query = $this->db->get(); if($query->num_rows()>0){ $return=$query->row_array(); } } return $return; } public function getClinicId($userid = 0){ $return= array(); if($userid!=0 && $userid!=''){ $this->db->select("clist.clinic_id, rcl.relationship_id, rcl.user_id, role.role_id"); $this->db->from($this->table_name .' as clist'); $this->db->join($this->clinic_table_name .' as cloc', 'clist.clinic_id = cloc.clinic_id','inner'); $this->db->join($this->clinic_relationship_table_name .' as rcl', 'cloc.location_id = rcl.clinic_location_id','inner'); $this->db->join($this->role_table_name .' as role', 'rcl.user_id = role.user_id','inner'); $this->db->where('`rcl`.`user_id`',$userid); $this->db->where('`role`.`user_id`',$userid); $query = $this->db->get(); if($query->num_rows()>0){ $return=$query->row(); } } return $return; } public function locationsCount($clinicId = 0){ $return= 0; if($clinicId!=0 && $clinicId!=''){ $this->db->select("count(cloc.clinic_id) as total_locations"); $this->db->from($this->table_name .' as clist'); $this->db->join($this->clinic_table_name .' as cloc', 'clist.clinic_id = cloc.clinic_id','inner'); $where = "(`clist`.`status`='1') AND (`cloc`.`status`='1') AND `cloc`.`clinic_id` ='".$clinicId."'"; $this->db->where($where); $query = $this->db->get(); if($query->num_rows()>0){ $result=$query->row(); if(count($result)>0){ $return=$result->total_locations; } } } return $return; } public function getAllTimeZone(){ $timezone = array(); $timezone['']=$this->lang->line('select_time_zone'); $this->db->select("`zone_id`,`zone_name`"); $this->db->from($this->mc_zone); $this->db->order_by('zone_name', "ASC"); $query = $this->db->get(); if($query->num_rows()>0){ $zones=$query->result_array(); if(count($zones)>0){ foreach($zones as $zone){ $timezone[$zone['zone_name']]=$zone['zone_name']; } } } return $timezone; } public function actHpByAdmin($hpID) { $lastModified = date('Y-m-d H:i:s'); $clinicAdmin = array(); $this->db->set('hp_status', 1); $this->db->set('last_modified_date', $lastModified); $this->db->where('hp_id', $hpID); $this->db->update($this->table_name); if ($this->db->affected_rows() > 0) { $this->db->select("user_id"); $this->db->where("hp_id" , $hpID); $this->db->from($this->table_name); $query = $this->db->get(); $hp_userTableID = $query->row(); $this->db->select("location_id"); $this->db->where("hp_id" , $hpID); $this->db->from($this->table_hp_clinics); $query = $this->db->get(); $locations = $query->result_array(); foreach ($locations as $loc) { $this->db->select("admin_id"); $where = "FIND_IN_SET('".$loc['location_id']."', clinic_loc)"; $this->db->where($where); $this->db->from($this->table_clinic_access); $query = $this->db->get(); $admidIds = $query->result_array(); $counter = 0; foreach ($admidIds as $value) { array_push($clinicAdmin, $admidIds[$counter]['admin_id']); $counter++; } } $userID = array(); if(!empty($clinicAdmin)) { foreach ($clinicAdmin as $cliAd) { $this->db->select("user_id"); $this->db->where("id", $cliAd); $this->db->from($this->table_clinic_admin); $query = $this->db->get(); $userId = $query->result_array(); $k = 0; foreach ($userId as $uID) { array_push($userID, $userId[$k]['user_id']); $k++; } } } //return $userID; if(!empty($userID)) { // echo "<pre>"; // print_r($hp_userTableID->user_id); // die; foreach ($userID as $users_id) { $data = array( 'recipient_id' => $users_id, 'sender_id' => $hp_userTableID->user_id, 'activity_type' => '1', 'time_sent' => date('Y-m-d H:i:s'), 'is_read' => 0, 'created' => date('Y-m-d H:i:s'), 'created_ip' => $this->mc_constants->remote_ip(), ); $inserted = $this->db->insert($this->table_notifications, $data); } //return $inserted; } } return $inserted; } public function dactHpByAdmin($hpID) { $lastModified = date('Y-m-d H:i:s'); $this->db->set('hp_status', 0); $this->db->set('last_modified_date', $lastModified); $this->db->where('hp_id', $hpID); $this->db->update($this->table_name); } }
bhishamtrehan/themedconsult
application/modules/master/models/manage_hp.php
PHP
mit
21,300
{{--do not use Form::open because we don't want the hidden token field --}} <form method="POST" action="{{ config('payment.europabank.mpiUrl') }}" accept-charset="UTF-8" @foreach($attributes as $attribute => $value) {{ $attribute }}="{{ $value }}" @endforeach > {{ Form::hidden('Uid', config('payment.europabank.uid'))}} {{ Form::hidden('Orderid', $order->getPaymentOrderId()) }} {{ Form::hidden('Amount', $order->getPaymentAmount()) }} {{ Form::hidden('Description', $order->getPaymentDescription()) }} {{ Form::hidden('Hash', $hash) }} {{ Form::hidden('Beneficiary', config('app.name')) }} {{ Form::hidden('Redirecttype', 'DIRECT') }} {{ Form::hidden('Redirecturl', URL::route(config('payment.europabank.paymentLandingPageRoute'))) }} {{ Form::hidden('Chemail', $order->getCustomerEmail()) }} {{ Form::hidden('Chlanguage', $order->getCustomerLanguage()) }} @if (config('payment.europabank.formCss')) {{ Form::hidden('Css', config('payment.europabank.formCss')) }} @endif @if (config('payment.europabank.template')) {{ Form::hidden('Template', config('payment.europabank.template')) }} @endif @if (config('payment.europabank.formTitle')) {{ Form::hidden('Title', config('payment.europabank.formTitle')) }} @endif @if (config('payment.europabank.merchantEmail')) {{ Form::hidden('MerchantEmail', config('payment.europabank.merchantEmail')) }} @endif @if (config('payment.europabank.secondChanceEmailSender')) {{ Form::hidden('Emailfrom', config('payment.europabank.secondChanceEmailSender')) }} @endif {{ Form::button(Lang::get('payment::form.submitButtonText'), ["type"=>"submit", "class"=> config('payment.form.submitButtonClass')]) }} </form>
spatie/payment
src/Gateways/Europabank/form.blade.php
PHP
mit
1,701
<?php namespace Heartbeats\Heartbeats\Jobs; use Illuminate\Bus\Queueable; use Heartbeats\Heartbeats\Reporter; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class ReporterJob implements ShouldQueue { use Dispatchable, Queueable; /** * The data to be reported. * * @var array */ protected $data; /** * Create a new job instance. * * @param array $data * @return void */ public function __construct(array $data) { $this->data = $data; } /** * Execute the job. * * @param \Heartbeats\Heartbeats\Reporter $reporter * @return void */ public function handle(Reporter $reporter) { $reporter->report($this->data); } }
heartbeats-pro/heartbeats
src/Jobs/ReporterJob.php
PHP
mit
791
from helper_sql import sqlExecute def insert(t): sqlExecute('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)
bmng-dev/PyBitmessage
src/helper_sent.py
Python
mit
132
module Locomotive module SearchExt class Assign < ::Liquid::Tag include ActionView::Helpers::SanitizeHelper Syntax = /(#{::Liquid::VariableSignature}+)\s*to\s*(#{::Liquid::VariableSignature}+):\s*(#{::Liquid::VariableSignature}+)/ def initialize(tag_name, markup, tokens, context) if markup =~ Syntax @results = $1 @target = $2 @description = "#{@target}_description" @flag = $3 @options = {} markup.scan(::Liquid::TagAttributes) { |key, value| @options[key.to_sym] = value.gsub(/"|'/, '') } else raise ::Liquid::SyntaxError.new("Syntax Error in 'search_assign' - Valid syntax: search_assign results to variable: pagetag") end super end def render(context) @site = context.registers[:site] @result = context[@results][0] result_data = false if @result['content_type_slug'] # its a model entry model = @site.content_types.where(slug: @result['content_type_slug']).first model_item = model.entries.find(@result['original_id']).to_liquid result_data = model_item if model_item context[@flag.to_s] = model.name context[@description.to_s] = @result else # it is a page page = @site.pages.find(@result['original_id']).to_liquid result_data = page if page context[@flag.to_s] = false res = @result['highlighted']['searchable_content'] context[@description] = strip_tags(res) end context[@target.to_s] = result_data Rails.logger.error(result_data) "" end end end end
colibri-software/locomotive_search_ext_plugin
lib/locomotive/search_ext/plugin/assign.rb
Ruby
mit
1,735
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Savage_Hotel_System.Class { class Funcoes { public Funcoes() { } public int verificatelefone(String entrada) { //Verifica Telefone //Se tudo estiver ok, retorna 0 //Caso contrário retorna 1 //Se o tamanho da entrada for diferente de 10 ou 11 retornar 2 (Casas incompletas ou maior que a necessária) int tam = entrada.Length; for (int i = 0; i < tam; i++) { if (entrada[i] > 47 && entrada[i] < 58) { //cout<<entrada[i]<<endl; } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } if (tam < 10 || tam > 11) { return 2; } return 0; } /*public int verificanome(String entrada) { //Verifica Nome //Se tudo estiver ok, retorna 0 //Caso contrário retorna 2 (Tamanho Mínino 1) //Caso contrário retorna 1 (caracteres Inválidos) int tam = entrada.Length; for (int i = 0; i < tam; i++) { if (((entrada[i] > 64 && entrada[i] < 91) || (entrada[i] > 96 && entrada[i] < 123)) || (entrada[i] == 32)) { //cout<<entrada[i]; } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } if (tam <= 1) { return 2; } return 0; }*/ public int verificanome(String entrada) { //Verifica Nome //Se tudo estiver ok, retorna 0 //Caso contrário retorna 2 (Tamanho Mínino 1) //Caso contrário retorna 1 (caracteres Inválidos) int tam = entrada.Length; for (int i = 0; i < tam; i++) { if((int)entrada[i]>64 && (int)entrada[i] < 91){ }else{ if((int)entrada[i] > 96 && (int)entrada[i] < 123){ }else{ if((int)entrada[i] == 32){ }else{ if((int)entrada[i] > 127 && (int)entrada[i] < 145){ }else{ if((int)entrada[i] > 146 && (int)entrada[i] < 155){ }else{ if((int)entrada[i] > 159 && (int)entrada[i] < 166){ }else{ if((int)entrada[i] > 180 && (int)entrada[i] < 184){ }else{ if((int)entrada[i] > 197 && (int)entrada[i] < 200){ }else{ if((int)entrada[i] == 208){ }else{ if((int)entrada[i] > 209 && (int)entrada[i] < 217){ }else{ if((int)entrada[i] == 222){ }else{ if((int)entrada[i] == 224){ }else{ if((int)entrada[i] > 225 && (int)entrada[i] < 230){ }else{ if((int)entrada[i] > 232 && (int)entrada[i] < 238){ }else{ //caracter inválido return 1; } } } } } } } } } } } } } } } if (tam <= 1) { return 2; } return 0; } public int verificacpf(String entrada) { //Verifica CPF //Se tudo estiver ok, retorna 0 //Caso contrário retorna 1 //Se o tamanho da entrada for diferente de 11 retorna 2 (Casas incompletas ou maior que a necessária) int tam = entrada.Length; for (int i = 0; i < tam; i++) { if (entrada[i] > 47 && entrada[i] < 58) { //cout<<entrada[i]<<endl; } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } if (tam != 11) { return 2; } return 0; } public int verificacnpj(String entrada) { //Verifica CPF //Se tudo estiver ok, retorna 0 //Caso contrário retorna 1 //Se o tamanho da entrada for diferente de 14 retorna 2 (Casas incompletas ou maior que a necessária) int tam = entrada.Length; for (int i = 0; i < tam; i++) { if (entrada[i] > 47 && entrada[i] < 58) { //cout<<entrada[i]<<endl; } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } if (tam != 14) { return 2; } return 0; } public int verificasalario(String entrada) { //Verifica Salário //Se tudo estiver ok, retorna 0 //Caso contrário retorna 1 //Caso contrário retorna 2 (Tamanho Mínino 1) int tam = entrada.Length; if (tam < 1) { return 2; } for (int i = 0; i < tam; i++) { if (entrada[i] > 47 && entrada[i] < 58) { //cout<<entrada[i]<<endl; } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } return 0; } public int verificanumeroquarto(String entrada) { //Verifica Numero do Quarto //Se tudo estiver ok, retorna 0 //Caso contrário retorna 1 //Se o tamanho da entrada for diferente de 4 retorna 2 (Casas incompletas ou maior que a necessária) int tam = entrada.Length; for (int i = 0; i < tam; i++) { if (entrada[i] > 47 && entrada[i] < 58) { //cout<<entrada[i]<<endl; } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } if (tam != 4) { return 2; } return 0; } public int verificaQuantidade(String entrada) { //Verifica quantidade generico (valor inteiro maior igual a 0) //Se tudo estiver ok, retorna 0 //Caracter invalido retorna 1 int tam = entrada.Length; for (int i = 0; i < tam; i++) { if (entrada[i] > 47 && entrada[i] < 58) { //cout<<entrada[i]<<endl; } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } return 0; } public int verificavalor(String entrada) { //Verifica Valor //Se tudo estiver ok, retorna 0 //Caso contrário retorna 1 //Caso tenha mais de 2 casas após a vírgula ou se possuir 2 virgulas, retorna 2 int numeropontos = 0; int casas = 0; int tam = entrada.Length; for (int i = 0; i < tam; i++) { if (entrada[i] > 47 && entrada[i] < 58) { //cout<<entrada[i]<<endl; if (numeropontos > 0) { casas++; } if (casas > 2) { return 2; } } else { if (entrada[i] == 46) { if (numeropontos == 0) { numeropontos++; } else { return 2; } } else { //cout<<entrada[i]; //cout<<" caracter invalido"<<endl; return 1; } } } if (numeropontos == 0) { return 2; } if (numeropontos == 1 && casas < 2) { return 2; } if (entrada.Length > 8) { return 3; } return 0; } //Verificar data de nascimentos public int VerificaDataNascimento(String DataSelecionada) { String DatadeHoje = DateTime.Now.ToString(); Console.WriteLine("DataHoje: " + DatadeHoje + " DataSelecionada: " + DataSelecionada); if (DatadeHoje == DataSelecionada) { return 2; } else { int diaHoje = ((((int)DatadeHoje[0]) - 48) * 10); diaHoje += (((int)DatadeHoje[1]) - 48); int mesHoje = ((((int)DatadeHoje[3]) - 48) * 10); mesHoje += (((int)DatadeHoje[4]) - 48); int anoHoje = ((((int)DatadeHoje[6]) - 48) * 1000); anoHoje += ((((int)DatadeHoje[7]) - 48) * 100); anoHoje += ((((int)DatadeHoje[8]) - 48) * 10); anoHoje += (((int)DatadeHoje[9]) - 48); int diaSelecionado = ((((int)DataSelecionada[0])-48) * 10); diaSelecionado += (((int)DataSelecionada[1])-48); int mesSelecionado = ((((int)DataSelecionada[3]) - 48) * 10); mesSelecionado += (((int)DataSelecionada[4]) - 48); int anoSelecionado = ((((int)DataSelecionada[6]) - 48) * 1000); anoSelecionado += ((((int)DataSelecionada[7]) - 48) * 100); anoSelecionado += ((((int)DataSelecionada[8]) - 48) * 10); anoSelecionado += (((int)DataSelecionada[9]) - 48); if (anoSelecionado == anoHoje) { if (mesSelecionado == mesHoje) { if (diaHoje == diaSelecionado) { return 1; } else { if (diaSelecionado > diaHoje) { return 2; } } } else { if (mesSelecionado > mesHoje) { return 2; } } } else { if (anoSelecionado > anoHoje) { return 2; } } } return 0; } //Como regra de negócio vamos definir que //esta data é valida se for do mesmo mes que o dia atual entao retorna 0 // se for do futuro ou mais antiga q um mes retorna 1 public int VerificaDataPedido(DateTime dataSelecionada) { double days = (DateTime.Now - dataSelecionada).TotalDays; if (days > 30 || days < 0) return 1; else return 0; } //Verificar datas entre reservas public int VerificaDataReserva(String DataEntrada,String DataSaida) { String DatadeHoje = DateTime.Now.ToString(); if (DataEntrada == DataSaida) { return 1; } else { int diaHoje = ((((int)DatadeHoje[0]) - 48) * 10); diaHoje += (((int)DatadeHoje[1]) - 48); int mesHoje = ((((int)DatadeHoje[3]) - 48) * 10); mesHoje += (((int)DatadeHoje[4]) - 48); int anoHoje = ((((int)DatadeHoje[6]) - 48) * 1000); anoHoje += ((((int)DatadeHoje[7]) - 48) * 100); anoHoje += ((((int)DatadeHoje[8]) - 48) * 10); anoHoje += (((int)DatadeHoje[9]) - 48); int diaEntrada = ((((int)DataEntrada[0]) - 48) * 10); diaEntrada += (((int)DataEntrada[1]) - 48); int mesEntrada = ((((int)DataEntrada[3]) - 48) * 10); mesEntrada += (((int)DataEntrada[4]) - 48); int anoEntrada = ((((int)DataEntrada[6]) - 48) * 1000); anoEntrada += ((((int)DataEntrada[7]) - 48) * 100); anoEntrada += ((((int)DataEntrada[8]) - 48) * 10); anoEntrada += (((int)DataEntrada[9]) - 48); int diaSaida = ((((int)DataSaida[0]) - 48) * 10); diaSaida += (((int)DataSaida[1]) - 48); int mesSaida = ((((int)DataSaida[3]) - 48) * 10); mesSaida += (((int)DataSaida[4]) - 48); int anoSaida = ((((int)DataSaida[6]) - 48) * 1000); anoSaida += ((((int)DataSaida[7]) - 48) * 100); anoSaida += ((((int)DataSaida[8]) - 48) * 10); anoSaida += (((int)DataSaida[9]) - 48); if ((anoEntrada < anoHoje)||(anoSaida < anoHoje)) { return 2; } if ((mesEntrada < mesHoje) || (mesSaida < mesHoje)) { return 2; } if ((diaEntrada < diaHoje) || (diaSaida < diaHoje)) { return 2; } if (anoSaida == anoEntrada) { if (mesSaida == mesEntrada) { if (diaSaida == diaEntrada) { return 1; } else { if ((diaSaida < diaEntrada)||(diaEntrada > diaSaida)) { return 2; } } } else { if ((mesSaida < mesEntrada)||(mesEntrada>mesSaida)) { return 2; } } } else { if ((anoSaida < anoEntrada)||(anoEntrada>anoSaida)) { return 2; } } } return 0; } } }
pablokintopp/Savage-Hotel
Savage Hotel System/Savage Hotel System/Class/Funcoes.cs
C#
mit
15,537
'use strict'; angular.module('adds').controller('QuestionController', ['$scope', function($scope) { // Question controller logic // ... } ]);
SEAN-KH-RYU/surveySite
public/modules/adds/controllers/question.client.controller.js
JavaScript
mit
148
import setBit from './set-bit' test('sets bits', () => { expect(setBit(0b0, 7, 1)).toEqual(128) expect(setBit(0b11111111, 8, 1)).toEqual(511) expect(setBit(0b1000000000, 9, 0)).toEqual(0) expect(setBit(0, 31, 1)).toEqual(1 << 31) })
dodekeract/bitwise
source/integer/set-bit.test.ts
TypeScript
mit
238
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Welcome!</title> <style type="text/css"> /* Based on The MailChimp Reset INLINE: Yes. */ /* Client-specific Styles */ #outlook a {padding:0;} /* Force Outlook to provide a "view in browser" menu link. */ body{width:100% !important; -webkit-text-size-adjust:100%; -ms-text-size-adjust:100%; margin:0; padding:0;} /* Prevent Webkit and Windows Mobile platforms from changing default font sizes.*/ .ExternalClass {width:100%;} /* Force Hotmail to display emails at full width */ .ExternalClass, .ExternalClass p, .ExternalClass span, .ExternalClass font, .ExternalClass td, .ExternalClass div {line-height: 100%;} /* Forces Hotmail to display normal line spacing. More on that: http://www.emailonacid.com/forum/viewthread/43/ */ #backgroundTable {margin:0; padding:0; width:100% !important; line-height: 100% !important;} /* End reset */ /* Some sensible defaults for images Bring inline: Yes. */ img {outline:none; text-decoration:none; -ms-interpolation-mode: bicubic;} a img {border:none;} .image_fix {display:block;} /* Yahoo paragraph fix Bring inline: Yes. */ p {margin: 1em 0;} /* Hotmail header color reset Bring inline: Yes. */ h1, h2, h3, h4, h5, h6 {color: black !important;} h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {color: blue !important;} h1 a:active, h2 a:active, h3 a:active, h4 a:active, h5 a:active, h6 a:active { color: red !important; /* Preferably not the same color as the normal header link color. There is limited support for psuedo classes in email clients, this was added just for good measure. */ } h1 a:visited, h2 a:visited, h3 a:visited, h4 a:visited, h5 a:visited, h6 a:visited { color: purple !important; /* Preferably not the same color as the normal header link color. There is limited support for psuedo classes in email clients, this was added just for good measure. */ } /* Outlook 07, 10 Padding issue fix Bring inline: No.*/ table td {border-collapse: collapse;} /* Remove spacing around Outlook 07, 10 tables Bring inline: Yes */ table { border-collapse:collapse; mso-table-lspace:0pt; mso-table-rspace:0pt; } /* Styling your links has become much simpler with the new Yahoo. In fact, it falls in line with the main credo of styling in email and make sure to bring your styles inline. Your link colors will be uniform across clients when brought inline. Bring inline: Yes. */ a {color: blue;} /*************************************************** **************************************************** MOBILE TARGETING **************************************************** ***************************************************/ @media screen and (max-width: 480px), screen and (max-device-width: 480px) { /* Part one of controlling phone number linking for mobile. */ a[href^="tel"], a[href^="sms"] { text-decoration: none; color: #FFFFFF; /* or whatever your want */ pointer-events: none; cursor: default; } .mobile_link a[href^="tel"], .mobile_link a[href^="sms"] { text-decoration: default; color: #FFFFFF !important; pointer-events: auto; cursor: default; } /* CSS Styles by github@thetanman */ table[class="m480"], td[class="m480"] {width: 100% !important; max-width: 480px !important;} img[class="m480"] {width: 100% !important; max-width: 480px !important; height: auto !important;} table[id="card"] {border-radius: 3px !important;} td[class="gutter"] {padding-left: 20px !important; padding-right: 20px !important;} td[class="content"] {width: 100% !important; max-width: 480px !important; padding: 0px 20px !important; border-left: 2px solid #efefef; border-right: 2px solid #efefef;} td[class="footer-content"] {width: 100% !important; max-width: 480px !important; padding: 0px 20px !important; border-left: 2px solid #17a4d8; border-right: 2px solid #17a4d8;} *[class].hide {display: none !important;} img[class="spacer"] {width: 100% !important; max-width: 480px !important;} *[class].preheader {display: none !important;} /* Preheader removed from mobile version */ span[class="button"] {width: 240px !important; margin-right: auto !important; margin-left: auto !important; margin-bottom: 10px !important; display: inline-block !important; padding: 10px 20px !important; background-color: #99c739 !important; text-align: center !important; border-radius: 3px !important; border:1px solid #7ea613 !important;} } /* More Specific Targeting */ @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) { /* You guessed it, ipad (tablets, smaller screens, etc) */ /* repeating for the ipad */ a[href^="tel"], a[href^="sms"] { text-decoration: none; color: #FFFFFF; /* or whatever your want */ pointer-events: none; cursor: default; } .mobile_link a[href^="tel"], .mobile_link a[href^="sms"] { text-decoration: default; color: #FFFFFF !important; pointer-events: auto; cursor: default; } } </style> <!-- Targeting Windows Mobile --> <!--[if IEMobile 7]> <style type="text/css"> </style> <![endif]--> <!-- *********************************************** **************************************************** END MOBILE TARGETING **************************************************** ************************************************ --> <!--[if gte mso 9]> <style> /* Target Outlook 2007 and 2010 */ </style> <![endif]--> </head> <body bgcolor="#EFEFEF"> <div class="preheader" height="1" style="display: none; height: 1px; font-size: 1px; line-height: 1px; color: #FFFFFF;"> Message in confidence </div> <table cellpadding="0" cellspacing="0" border="0" id="backgroundTable"> <tr> <td valign="top" height="20" style="font-size: 1px; line-height: 20px;" class="gutter"> &nbsp; </td> </tr> <tr> <td valign="top" class="gutter"> <table cellpadding="0" cellspacing="0" border="0" class="m480" id="card" align="center" bgcolor="#FFFFFF"> <tr> <td width="600" height="40" colspan="3" style="font-size: 1px; line-height: 40px; border-top: 2px solid #ECECEC; border-left: 2px solid #ECECEC; border-right: 2px solid #ECECEC" class="m480"> &nbsp; </td> </tr> <tr> <td width="20" style="font-size: 1px; line-height: 20px; border-left: 2px solid #ECECEC;" class="hide"> &nbsp; </td> <td width="560" height="15" style="font-family: Arial, Helvetica, sans-serif; font-size: 24px; line-height: 30px; color: #888888; text-align: center; font-weight: bold;" class="content"> Your report is ready to download, Catherine :) <table cellpadding="0" cellspacing="0" border="0" class="m480" align="center" bgcolor="#FFFFFF"> <tr> <td width="15" height="15" style="font-size: 1px; line-height: 15px;" class="m480"> &nbsp; </td> </tr> </table> <div><!--[if mso]> <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="http://" style="height:38px;v-text-anchor:middle;width:200px;" arcsize="9%" strokecolor="#7ea613" fill="t"> <v:fill type="tile" src="http://imgur.com/clZqdfM.gif" color="#99c739" /> <w:anchorlock/> <center style="color:#ffffff;font-family:sans-serif;font-size:14px;font-weight:bold;">Download report</center> </v:roundrect> <![endif]--><a href="http://" style="background-color:#99c739;border:1px solid #7ea613;border-radius:none;color:#ffffff;display:inline-block;font-family:sans-serif;font-size:14px;font-weight:bold;line-height:38px;text-align:center;text-decoration:none;width:200px;-webkit-text-size-adjust:none;mso-hide:all;">Download report</a></div> </td> <td width="20" style="font-size: 1px; line-height: 20px; border-right: 2px solid #ECECEC;" class="hide"> &nbsp; </td> </tr> <tr> <td width="600" height="40" colspan="3" style="font-size: 1px; line-height: 40px; border-left: 2px solid #ECECEC; border-right: 2px solid #ECECEC;" class="m480"> &nbsp; </td> </tr> <tr> <td width="600" colspan="3" style="border-left: 2px solid #ECECEC; border-right: 2px solid #ECECEC;" class="m480-content"> <center><img src="../assets/img/report-sm.gif" width="400" height="200" border="0" style="display: block;" class="m480"></center> </td> </tr> </table> </td> </tr> <tr> <td valign="top" class="gutter"> <table cellpadding="0" cellspacing="0" border="0" class="480" align="center" bgcolor="#17a4d8"> <tr> <td width="600" height="20" colspan="3" style="font-size: 1px; line-height: 20px; border-left: 2px solid #ECECEC; border-right: 2px solid #ECECEC" class="m480"> <img src="../assets/img/spacer.gif" width="600" height="1" border="0" alt="Image" style="display: block; max-width: 600px;" class="spacer" /> </td> </tr> <tr> <td width="20" style="font-size: 1px; line-height: 20px; border-left: 2px solid #ECECEC;" class="hide"> &nbsp; </td> <td width="560" style="font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 20px; color: #FFFFFF;" class="content"> <span style="font-size: 18px; line-height: 26px; font-weight: bold;">Need assistance?</span> <table cellpadding="0" cellspacing="0" border="0" class="m480" align="center" bgcolor="#17a4d8"> <tr> <td width="15" height="5" style="font-size: 1px; line-height: 5px;" class="m480"> &nbsp; </td> </tr> </table> If there's anything you need help with or have any general inquiries then contact us on <strong>+612 9700 9707</strong> or send us an <a href="mailto:ben@taoscreative.com.au" style="color: #FFFFFF; font-weight: bold;">email</a>. </td> <td width="20" style="font-size: 1px; line-height: 20px; border-right: 2px solid #ECECEC;" class="hide"> &nbsp; </td> </tr> <tr> <td width="600" height="20" colspan="3" style="font-size: 1px; line-height: 20px; border-left: 2px solid #ECECEC; border-right: 2px solid #ECECEC;" class="m480"> &nbsp; </td> </tr> </table> </td> </tr> </table> </body> </html>
thetanman/wipreport
dist/email/index.html
HTML
mit
10,354
## 111. Minimum Depth of Binary Tree [E] Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. ## Code: ### Round 1 - solution 1 - dfs recursion (12 ms): ```c++ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode* root) { if (!root) return 0; int count = 0; vector<int> temp; helper(root, temp, count); sort(temp.begin(), temp.end()); return temp[0]; } void helper(TreeNode* node, vector<int> & temp, int count) { if (node == NULL) return; if (node -> left == NULL && node -> right == NULL) { temp.push_back(++ count); return; } helper(node -> left, temp, count + 1); helper(node -> right, temp, count + 1); } }; ``` ### Round 2 - solution 2 - dfs iteration (13 ms): ```c++ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { // 2nd round date: 2016-10-24 location: SJSU Student Union public: int minDepth(TreeNode* root) { if (!root) return 0; int res = INT_MAX; stack<MyTreeNode *> s; s.push(new MyTreeNode(root, 1)); while (!s.empty()) { MyTreeNode *curr = s.top(); s.pop(); // op if (!curr->node_->left && !curr->node_->right) res = min(res, curr->height_); // push children if (curr->node_->left) s.push(new MyTreeNode(curr->node_->left, curr->height_ + 1)); if (curr->node_->right) s.push(new MyTreeNode(curr->node_->right, curr->height_ + 1)); } return res; } private: struct MyTreeNode { TreeNode *node_; int height_; MyTreeNode(TreeNode *node, int height) { node_ = node; height_ = height; } }; }; ```
ysong49/LeetCode-Note
algorithm/111. Minimum Depth of Binary Tree.md
Markdown
mit
2,340
/* jshint esversion : 6 */ const mysql = require('mysql'); const connection = mysql.createConnection({ host : 'localhost', user : 'root', password : '@mysql', database : 'node-backend' }); connection.connect(); // dummy function pour vérifier si la connectione à la base est bien établie connection.query('SELECT 42 AS solution', function (error, results, fields) { if (error) throw error; console.log('DATABASE SAYS => The solution is', results[0].solution); }); const get = (clbk, id) => { var query; if (id) query = `SELECT id, mail, avatar, about, is_admin FROM users WHERE id = ${connection.escape(id)}`; else query = 'SELECT id, mail, avatar, about, is_admin FROM users'; connection.query(query, (error, results, fields) => { if (error) throw error; // en cas d'erreur, une exception est levée clbk(results); // on passe les résultats de la requête en argument de la fonction callback }); }; const checkMail = (clbk, mail) => { const query = `SELECT COUNT(*) as count FROM users WHERE mail = ${connection.escape(mail)}`; connection.query(query, (error, results, fields) => { if (error) throw error; // en cas d'erreur, une exception est levée clbk(results); // passe les résultats de requête en arg du callback }); }; const register = (clbk, data) => { checkMail(res => { // console.log(res); if (res[0].count > 0) { // cette adresse mail est déjà en base return clbk({error: true, message: "mail already exists"}); } // la base ne contient pas encore cette adresse mail, poursuivons l'insertion let query = `INSERT INTO users (mail, password) VALUES (${connection.escape(data.mail)}, ${connection.escape(data.password)})`; connection.query(query, (error, results, fields) => { if (error) throw error; results.error = false; results.message = "tadaa : you're now registered !!!"; clbk(results); }); }, data.mail); }; const remove = (clbk, id) => { const query = `DELETE FROM users WHERE id = ${connection.escape(id)}`; connection.query(query, (error, results, fields) => { if (error) throw error; // en cas d'erreur, une exception est levée results.error = false; results.message = "user has been removed from database"; clbk(results); // on passe les résultats de la requête en argument de la fonction callback }); }; const login = (clbk, data) => { const q = `SELECT id, mail, avatar, about, is_admin FROM users WHERE mail = '${data.mail}' AND password = '${data.password}' GROUP BY id`; // console.log(q); connection.query(q, (error, results, fields) => { if (error) throw error; const tmp = results[0] || results; const res = {}; if (Array.isArray(tmp) && !tmp.length) { res.message = "Mauvais mail ou mot de passe"; } else { res.user = tmp; res.message = "Yay : You're now logged in !!"; } clbk(res); }); }; const patchAbout = (clbk, about, id) => { const q = `UPDATE users SET about = ${connection.escape(about)} WHERE id = ${id}`; // console.log(q); connection.query(q, (error, results, fields) => { if (error) throw error; clbk(results); }); }; const patchAvatar = (clbk, avatar, id) => { const q = `UPDATE users SET avatar = ${connection.escape(avatar)} WHERE id = ${id}`; // console.log(q); connection.query(q, (error, results, fields) => { if (error) throw error; clbk(results); }); }; module.exports = { register, get, login, patch: { about: patchAbout, avatar: patchAvatar, }, remove: remove, };
owlab-io/campus-simplon-2
03_js/05_vuejs/43_node_backend/src/models/users.js
JavaScript
mit
3,596
from . import adaptVor_driver from .adaptVor_driver import AdaptiveVoronoiDriver
westpa/westpa
src/westext/adaptvoronoi/__init__.py
Python
mit
82
+++ categories="article" date="2013-12-29T00:21:00+03:00" issue="2013-04" issue_name="2013 - №04" number="3" file = "https://static.nuclear-power-engineering.ru/articles/2013/04/03.pdf" udc="621.181.29" title="Исследование возможности использования на АЭС аккумуляторов тепловой энергии при регулировании частоты тока в сети" authors=["BazhanovVV", "LoshchakovII", "ShchuklinovAP"] tags=["АЭС", "аккумулятор тепловой энергии", "регулирование частоты тока"] rubric = "nuclearpowerplants" rubric_name = "Aтомные электростанции" doi="https://doi.org/10.26583/npe.2013.4.03" +++ Приводятся результаты аналитического исследования, обосновывающие использование системы аккумулирования тепловой энергии АЭС с ВВЭР как элемента, обеспечивающего переменную мощность турбогенератора при участии АЭС в регулировании частоты тока в сети. Исследование проведено применительно к одному из возможных вариантов проекта энергоблока АЭС с ВВЭР NНОМ = 1200 МВт и системой аккумулирования тепловой энергии с несущественными с точки зрения рассматриваемого вопроса отклонениями в схеме, мощности и конструкции системы относительно опубликованных данных по проекту. ### Ссылки 1. Чаховский В.М., Сопленков К.И. Сэкономим? Энергоэффективность теплоаккумулирующих систем в атомной энергетике.– М.: Росэнергоатом, №2, 2010. – 6с. 2. Нормы участия энергоблоков АЭС в нормированном первичном регулировании частоты. СТО 5912820.27.120.20.002-2010.– М.: ОАО «СО ЕЭС», 2010. – 34с. 3. Основные технические требования к внедрению общего первичного регулирования частоты на энергоблоке №2 Ростовской АЭС, ОАО «Концерн Росэнергоатом», 2010. 4. Букринский А.М. Аварийные переходные процессы на АЭС с ВВЭР. – М.: Энергоиздат, 1982.
nuclear-power-engineering/nuclear-power-engineering
content/article/2013/04/03.md
Markdown
mit
2,766
module Solon module Config mattr_accessor :vendor mattr_accessor :gateway_mode end end
pyrat/solon
lib/solon/config.rb
Ruby
mit
99
import os import sys def main(): if len(sys.argv) != 2: print("Usage: Pass the file name for the source transcript txt file.") sys.exit(-1) file = sys.argv[1] out_file = os.path.expanduser( os.path.join( '~/Desktop', os.path.basename(file) ) ) print("Files:") print("Reading source file: ", file) print("Exported version at: ", out_file) fin = open(file, 'r', encoding='utf-8') fout = open(out_file, 'w', encoding='utf-8') with fin, fout: time = "0:00" for line in fin: if is_time(line): time = get_time_text(line) elif line and line.strip(): text = f"{time} {line.strip()}\n\n" fout.write(text) # print(text) def is_time(line: str) -> bool: if not line or not line.strip(): return False parts = line.split(':') if not parts: return False return all(p.strip().isnumeric() for p in parts) def get_time_text(line: str) -> str: if ':' not in line: raise Exception(f"Text doesn't seem to be a time: {line}") parts = line.split(':') hour_text = "0" min_text = "0" sec_text = "0" if len(parts) == 3: hour_text = parts[0].strip() min_text = parts[1].strip() sec_text = parts[2].strip() elif len(parts) == 2: min_text = parts[0].strip() sec_text = parts[1].strip() elif len(parts) == 1: sec_text = parts[0].strip() return f"{hour_text.zfill(2)}:{min_text.zfill(2)}:{sec_text.zfill(2)}" if __name__ == '__main__': main()
mikeckennedy/python_bytes_show_notes
tools/otter_ai_to_our_format.py
Python
mit
1,657
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace Editor { public abstract class DivMathWithOuterBase: DivMath { protected RowContainer outerEquation; public DivMathWithOuterBase(EquationContainer parent) : base(parent) { outerEquation = new RowContainer(this); outerEquation.HAlignment = Editor.HAlignment.Right; //insideEquation.HAlignment = Editor.HAlignment.Right; childEquations.Add(outerEquation); } public override XElement Serialize() { XElement thisElement = new XElement(GetType().Name); thisElement.Add(insideEquation.Serialize()); thisElement.Add(outerEquation.Serialize()); return thisElement; } public override void DeSerialize(XElement xElement) { var elements = xElement.Elements().ToArray(); insideEquation.DeSerialize(elements[0]); outerEquation.DeSerialize(elements[1]); CalculateSize(); } public override void CalculateSize() { CalculateHeight(); CalculateWidth(); } protected override void CalculateWidth() { Width = Math.Max(insideEquation.Width, outerEquation.Width) + divMathSign.Width + LeftGap; } protected override void CalculateHeight() { Height = outerEquation.Height + insideEquation.Height + ExtraHeight; divMathSign.Height = insideEquation.FirstRow.Height + ExtraHeight; } public override double Left { get { return base.Left; } set { base.Left = value; divMathSign.Left = value + LeftGap; insideEquation.Right = Right; outerEquation.Right = Right; } } } }
MovGP0/math-editor
Editor/equations/Division/DivMathWithOuterBase.cs
C#
mit
2,016
require 'spec_helper' describe OmniAuth::Strategies::Appnet do subject do OmniAuth::Strategies::Appnet.new({}) end context "general" do it "should be called appnet" do subject.options.name.should eq('appnet') end end context "endpoints" do it "has correct site" do subject.options.client_options.site.should eq("https://alpha-api.app.net") end it "has correct authorize_url" do subject.options.client_options.authorize_url.should eq("https://alpha.app.net/oauth/authenticate") end it "has correct token_url" do subject.options.client_options.token_url.should eq("https://alpha.app.net/oauth/access_token") end end end
phuu/omniauth-appnet
spec/omniauth/strategies/appnet_spec.rb
Ruby
mit
696
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Ok : MonoBehaviour { private int push_button; public GameObject buttons; public Button ok; // Use this for initialization void Start () { ok = this.gameObject.transform.GetChild(1).gameObject.GetComponent<Button>(); ok.onClick.AddListener(delegate { clickOk(true); }); } // Update is called once per frame void Update () { } void clickOk(bool result) { this.gameObject.transform.parent.gameObject.SendMessage("sendOk", result); } }
GROWrepo/Santa_Inc
Assets/script/monoBehavior/Ok.cs
C#
mit
640
import './fileUpload.js'; import './fileGallery.html'; import './files.html'; import './files.scss'; if (!HTMLCanvasElement.prototype.toBlob) { Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', { value(callback, type, quality) { let binStr = atob(this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len); for (let i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } callback(new Blob([arr], { type: type || 'image/png' })); }, }); } const currentlyEditedFile = new ReactiveVar(undefined); const fileBrowserCallback = new ReactiveVar(undefined); Meteor.startup(function () { _.extend(UltiSite, { fileBrowserShowDialog(id, callback) { UltiSite.State.set('fileBrowserFolder', id); fileBrowserCallback.set(callback); UltiSite.showModal('fileBrowserDialog'); }, fileBrowserHideDialog() { UltiSite.hideModal(); }, }); }); Template.registerHelper('fileRootFolder', function () { return UltiSite.Folders.findOne(UltiSite.settings().rootFolderId); }); const getIcon = function () { let file = this; if (!file.type && this.file) { file = this.file; } if (!file.type) { return 'fa-question'; } if (file.type.indexOf('image') === 0) { return 'fa-file-image-o'; } else if (file.type.indexOf('video') === 0) { return 'fa-file-video-o'; } return 'fa-file-o'; }; // FUTURE: add editing capabilities Template.editFileDialog.helpers({ file() { return currentlyEditedFile.get(); }, icon: getIcon, assozierteElemente() { return UltiSite.getAnyById(currentlyEditedFile.get().associated); }, }); Template.fileBrowser.onCreated(function () { UltiSite.State.set('fileBrowserFolder', UltiSite.settings().rootFolderId); UltiSite.State.setDefault('fileBrowserGalleryView', false); this.autorun(() => { const id = FlowRouter.getParam('_id'); const dataId = Template.currentData().fileBrowserFolder; if (dataId) { UltiSite.State.set('fileBrowserFolder', dataId); } else if (id) { UltiSite.State.set('fileBrowserFolder', id); } }); this.autorun(() => { this.subscribe('Files', UltiSite.State.get('fileBrowserFolder')); }); this.readme = new ReactiveVar(); this.autorun(() => { const readmeFile = UltiSite.Documents.findOne({ associated: UltiSite.State.get('fileBrowserFolder'), name: 'README.md', }); if (readmeFile) { HTTP.get(readmeFile.url(), (err, res) => { if (!err) { this.readme.set(res.content); } }); } else { this.readme.set(undefined); } }); }); Template.fileBrowser.events({ 'click .toggle-gallery-view': function(e, t) { e.preventDefault(); UltiSite.State.set('fileBrowserGalleryView', !UltiSite.State.get('fileBrowserGalleryView')); }, 'click .btn-new-folder': function(e, t) { e.preventDefault(); console.log('Add folder', e); UltiSite.Folders.insert({ rename: true, name: 'Neuer Ordner', associated: [UltiSite.State.get('fileBrowserFolder')], }); }, }); Template.fileBrowser.helpers({ galleryView() { return UltiSite.State.get('fileBrowserGalleryView'); }, readme() { return Template.instance().readme.get(); }, curFolder() { return UltiSite.getAnyById(UltiSite.State.get('fileBrowserFolder')) || { _id: UltiSite.State.get('fileBrowserFolder') }; }, rootFolder() { return UltiSite.getAnyById(UltiSite.settings().rootFolderId); }, }); Template.fileBrowserItem.events({ 'click .remove-file': function(e, t) { e.preventDefault(); UltiSite.confirmDialog(`Willst du die Datei ${this.name} wirklich löschen?`, () => { Meteor.call('removeFile', this._id); }); }, 'click .edit-file': function(e) { e.preventDefault(); currentlyEditedFile.set(this); $('#editFileDialog').modal('show'); }, 'click .select-file': function(e, t) { e.preventDefault(); e.stopPropagation(); const callback = fileBrowserCallback.get(); if (callback) { callback(this); } }, }); Template.fileBrowserItem.helpers({ needsSelect() { return fileBrowserCallback.get(); }, icon: getIcon, }); Template.fileBrowserDialog.onCreated(function () { const self = this; this.initialFolder = UltiSite.State.get('fileBrowserFolder'); this.activePane = new ReactiveVar(this.initialFolder); }); Template.fileBrowserDialog.onDestroyed(function () { fileBrowserCallback.set(null); }); Template.fileBrowserDialog.events({ 'hidden.bs.modal .modal': function(e, t) { fileBrowserCallback.set(null); }, 'click .action-switch-source': function(e, t) { e.preventDefault(); if (t.$(e.currentTarget).attr('data-value') !== 'search') { UltiSite.State.set('fileBrowserFolder', t.$(e.currentTarget).attr('data-value')); } t.activePane.set(t.$(e.currentTarget).attr('data-value')); }, 'click .action-select-nothing': function(e) { e.preventDefault(); const callback = fileBrowserCallback.get(); if (callback) { callback(null); } }, }); Template.fileBrowserDialog.helpers({ initialFolder() { return Template.instance().initialFolder; }, fileBrowserFolder() { return UltiSite.State.get('fileBrowserFolder'); }, activePane() { return Template.instance().activePane.get(); }, dialogSelection() { return fileBrowserCallback.get(); }, }); const helpers = { icon: getIcon, folder() { return UltiSite.getAnyById(UltiSite.State.get('fileBrowserFolder')) || {}; }, files() { return _.sortBy(UltiSite.Images.find({ associated: UltiSite.State.get('fileBrowserFolder'), }).fetch().concat( UltiSite.Documents.find({ associated: UltiSite.State.get('fileBrowserFolder'), }).fetch()), function (doc) { return doc.created; }); }, folders() { const folders = []; if (this.type === 'folder') { const folder = UltiSite.Folders.findOne(this._id); if (folder && folder.associated.length > 0) { folders.push({ name: '..', isParent: true, _id: folder.associated[0], type: 'folder' }); } } return folders.concat(UltiSite.Folders.find({ associated: UltiSite.State.get('fileBrowserFolder'), }).fetch()); }, fileActions() { const element = UltiSite.getAnyById(this._id); if (!element) { return []; } if (element.type === 'tournament') { const tournament = UltiSite.getTournament(element._id); if (!tournament) { return []; } const elems = tournament.teams.map(function (elem) { return { text: `Teamfoto:${elem.name}`, action(file) { console.log('Updating teamfoto'); UltiSite.Images.update(file._id, { $addToSet: { associated: elem._id, }, }); }, }; }); return elems; } }, }; Template.fileBrowserList.onCreated(function () { console.log('List: onCreated'); const self = this; }); Template.fileBrowserList.onRendered(function () { console.log('List: onRendered'); }); Template.fileBrowserList.helpers(_.extend({}, helpers)); Template.fileBrowserList.events({ 'click .folder-link': function(e, t) { UltiSite.State.set('fileBrowserFolder', this._id); e.preventDefault(); }, 'click .remove-folder': function(e, t) { e.preventDefault(); UltiSite.Folders.remove({ _id: this._id, }); }, 'click .rename-folder': function(e, t) { e.preventDefault(); const input = $(e.currentTarget); UltiSite.Folders.update({ _id: this._id, }, { $set: { rename: true, }, }); }, 'change .folder-name': function(e, t) { e.preventDefault(); const input = $(e.currentTarget); UltiSite.Folders.update({ _id: input.data('id'), }, { $set: { name: input.val(), }, $unset: { rename: 1, }, }); }, }); Template.fileBrowserGallery.onCreated(function () { console.log('Gallery created for ID', this.data); const self = this; }); Template.fileBrowserGallery.helpers(helpers); Template.fileBrowserGallery.events({ 'click .action-open-folder': function(e, t) { e.preventDefault(); UltiSite.State.set('fileBrowserFolder', this._id); }, }); Template.fileBrowserGalleryItem.events({ 'click .file-browser-gallery-item .image': function() { try { if (Template.instance().$('.file-browser-item').parent('#fileBrowserDialog')) { const callback = fileBrowserCallback.get(); if (callback) { callback(this.file); return; } } } catch (err) { } FlowRouter.go('image', { _id: this.file._id, associated: this.associatedId, }); }, 'click .file-browser-gallery-item .icon-image': function() { try { if (Template.instance().$('.file-browser-item').parent('#fileBrowserDialog')) { const callback = fileBrowserCallback.get(); if (callback) { callback(this.file); return; } } } catch (err) { } window.open(this.file.url(), '_blank'); }, 'click .remove-file': function(e, t) { e.preventDefault(); UltiSite.confirmDialog(`Willst du die Datei ${this.file.name} wirklich löschen?`, () => { Meteor.call('removeFile', this.file._id); }); }, 'click .edit-file': function(e) { e.preventDefault(); currentlyEditedFile.set(this.file); $('#editFileDialog').modal('show'); }, 'click .select-file': function(e, t) { e.preventDefault(); e.stopPropagation(); const callback = fileBrowserCallback.get(); if (callback) { callback(this.file); } }, 'click .custom-action': function(e, t) { e.preventDefault(); // e.stopPropagation(); console.log('Custom:', this); this.action(t.data.file); }, }); Template.fileBrowserGalleryItem.helpers(helpers); Template.folderTreeItem.helpers({ isSelectedFolder() { return this._id === UltiSite.State.get('fileBrowserFolder'); }, folders() { return UltiSite.Folders.find({ associated: this._id, }); }, });
larswolter/ultisite
imports/client/files/files.js
JavaScript
mit
10,165
<?php namespace PetrKnap\Symfony\MarkdownWeb\Controller; use const PetrKnap\Symfony\MarkdownWeb\CONFIG; use const PetrKnap\Symfony\MarkdownWeb\CONTROLLER_CACHE; use const PetrKnap\Symfony\MarkdownWeb\CRAWLER_SERVICE; use PetrKnap\Symfony\MarkdownWeb\Service\Crawler; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class DefaultController extends Controller { const ROUTE = "markdown_web"; /** * @Route("/{url}", defaults={"url" = ""}, requirements={"url"=".*"}, name="markdown_web") * @param Request $request * @param string $url * @return Response */ public function defaultAction(Request $request, $url) { $pageNumber = $request->get("page"); if (1 == $pageNumber) { return $this->redirectToRoute( static::ROUTE, [ "url" => $url ] ); } $pageNumber = null === $pageNumber ? 1 : $pageNumber; $url = $this->urlModifier("/" . $url); $config = $this->get(CONFIG); if ($config['cache']['enabled']) { // TODO test it /** @var AdapterInterface $cache */ $cache = $this->get(CONTROLLER_CACHE); $cached = $cache->getItem(str_replace( ['+', '/', '='], ['_', '-', ''], base64_encode(sprintf("%s?page=%s", $url, $pageNumber)) )); if (!$cached->isHit()) { $cached->set($this->createResponse($url, $pageNumber)); $cache->save($cached); } return $cached->get(); } else { // TODO test it return $this->createResponse($url, $pageNumber); } } private function createResponse($url, $pageNumber) { /** @var Crawler $crawler */ $crawler = $this->get(CRAWLER_SERVICE); $page = $crawler->getIndex([$this, "urlModifier"])->getPage($url); if (!$page) { throw new NotFoundHttpException("Page with url '{$url}' not found"); } return $page->getResponse(function ($view, $parameters) use ($url, $pageNumber) { $config = $this->get(CONFIG); /** @noinspection PhpInternalEntityUsedInspection */ return $this->renderView($view, [ "url" => $url, "page_number" => $pageNumber, "site" => $config["site"], "base_uri" => $this->urlModifier("/"), ] + $parameters); }); } public function urlModifier($url) { return $this->generateUrl( static::ROUTE, [ "url" => substr($url, 1) ] ); } }
petrknap/trunk
packages/Symfony/MarkdownWeb/src/Controller/DefaultController.php
PHP
mit
3,021
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highcharts]] */ package com.highcharts.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>plotOptions-bb-states-hover-marker-states</code> */ @js.annotation.ScalaJSDefined class PlotOptionsBbStatesHoverMarkerStates extends com.highcharts.HighchartsGenericObject { /** * <p>The normal state of a single point marker. Currently only used * for setting animation when returning to normal state from hover.</p> * @since 6.0.0 */ val normal: js.Any = js.undefined /** * <p>The hover state for a single point marker.</p> * @since 6.0.0 */ val hover: js.Any = js.undefined /** * <p>The appearance of the point marker when selected. In order to * allow a point to be selected, set the <code>series.allowPointSelect</code> * option to true.</p> * @since 6.0.0 */ val select: js.Any = js.undefined } object PlotOptionsBbStatesHoverMarkerStates { /** * @param normal <p>The normal state of a single point marker. Currently only used. for setting animation when returning to normal state from hover.</p> * @param hover <p>The hover state for a single point marker.</p> * @param select <p>The appearance of the point marker when selected. In order to. allow a point to be selected, set the <code>series.allowPointSelect</code>. option to true.</p> */ def apply(normal: js.UndefOr[js.Any] = js.undefined, hover: js.UndefOr[js.Any] = js.undefined, select: js.UndefOr[js.Any] = js.undefined): PlotOptionsBbStatesHoverMarkerStates = { val normalOuter: js.Any = normal val hoverOuter: js.Any = hover val selectOuter: js.Any = select com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsBbStatesHoverMarkerStates { override val normal: js.Any = normalOuter override val hover: js.Any = hoverOuter override val select: js.Any = selectOuter }) } }
Karasiq/scalajs-highcharts
src/main/scala/com/highcharts/config/PlotOptionsBbStatesHoverMarkerStates.scala
Scala
mit
2,113
<?php namespace AppBundle\Twig; use AppBundle\Service\SafeMarkdownParser; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; class MarkdownExtension extends AbstractExtension { private SafeMarkdownParser $safeMarkdownParser; public function __construct(SafeMarkdownParser $safeMarkdownParser) { $this->safeMarkdownParser = $safeMarkdownParser; } public function getFilters() { return [ new TwigFilter('user_provided_markdown_to_safe_html', [$this, 'userMarkdownToHTML'], ['is_safe' => ['all']]), ]; } public function userMarkdownToHTML($markdown) { return $this->safeMarkdownParser->convert($markdown); } }
AdventureLookup/AdventureLookup
src/AppBundle/Twig/MarkdownExtension.php
PHP
mit
705
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>paradoxes: Error 🔥</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[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]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / paradoxes - dev</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> paradoxes <small> dev <span class="label label-danger">Error 🔥</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-29 01:31:58 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-29 01:31:58 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 3 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 2.9.1 Fast, portable, and opinionated build system ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;dev@clarus.me&quot; homepage: &quot;https://github.com/coq-contribs/paradoxes&quot; license: &quot;LGPL 2&quot; build: [ [&quot;coq_makefile&quot; &quot;-f&quot; &quot;Make&quot; &quot;-o&quot; &quot;Makefile&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Paradoxes&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {= &quot;dev&quot;} ] tags: [ &quot;keyword:reynolds paradox&quot; &quot;keyword:burali forti paradox&quot; &quot;keyword:diaconescu paradox&quot; &quot;keyword:set theory&quot; &quot;keyword:system u&quot; &quot;keyword:inconsistency&quot; &quot;keyword:hurkens paradox&quot; &quot;category:Mathematics/Logic/Foundations&quot; ] authors: [ &quot;Bruno Barras &lt;&gt;&quot; &quot;Benjamin Werner &lt;&gt;&quot; &quot;Hugo Herbelin &lt;&gt;&quot; &quot;Thierry Coquand &lt;&gt;&quot; ] synopsis: &quot;Paradoxes in Set Theory and Type Theory.&quot; description: &quot;&quot;&quot; A formalisation of Burali-Forti paradox in system U (the existence of an ordinal of ordinals is inconsistent), of Diaconescu paradox (axiom of choice implies excluded-middle), of Reynolds paradox (there is no set-theoretic model of system F) and Hurkens paradox in system U (adapted by H. Geuvers to show the inconsistency of Excluded-Middle in impredicative-Set Calculus of Inductive Constructions).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;git+https://github.com/coq-contribs/paradoxes.git#master&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-paradoxes.dev coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-paradoxes.dev coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>12 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y coq-paradoxes.dev coq.dev</code></dd> <dt>Return code</dt> <dd>7936</dd> <dt>Duration</dt> <dd>23 s</dd> <dt>Output</dt> <dd><pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 3 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 2.9.1 Fast, portable, and opinionated build system ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers [NOTE] Package coq is already installed (current version is dev). The following actions will be performed: - install coq-paradoxes dev &lt;&gt;&lt;&gt; Gathering sources &gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; [coq-paradoxes.dev] synchronised from git+https://github.com/coq-contribs/paradoxes.git#master &lt;&gt;&lt;&gt; Processing actions &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; [ERROR] The compilation of coq-paradoxes failed at &quot;/home/bench/.opam/opam-init/hooks/sandbox.sh build coq_makefile -f Make -o Makefile&quot;. #=== ERROR while compiling coq-paradoxes.dev ==================================# # context 2.0.6 | linux/x86_64 | ocaml-base-compiler.4.07.1 | file:///home/bench/run/opam-coq-archive/extra-dev # path ~/.opam/ocaml-base-compiler.4.07.1/.opam-switch/build/coq-paradoxes.dev # command ~/.opam/opam-init/hooks/sandbox.sh build coq_makefile -f Make -o Makefile # exit-code 1 # env-file ~/.opam/log/coq-paradoxes-3021-e4db2f.env # output-file ~/.opam/log/coq-paradoxes-3021-e4db2f.out ### output ### # [...] # [-Q physicalpath logicalpath]: look for Coq dependencies starting from # &quot;physicalpath&quot;. The logical path associated to the physical path # is &quot;logicalpath&quot;. # [VARIABLE = value]: Add the variable definition &quot;VARIABLE=value&quot; # [-arg opt]: send option &quot;opt&quot; to coqc # [-docroot path]: Install the documentation in this folder, relative to # &quot;user-contrib&quot;. # [-f file]: take the contents of file as arguments # [-o file]: output should go in file file (recommended) # Output file outside the current directory is forbidden. # [-h]: print this usage summary # [--help]: equivalent to [-h] &lt;&gt;&lt;&gt; Error report &lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt;&lt;&gt; +- The following actions failed | - build coq-paradoxes dev +- - No changes have been performed # Run eval $(opam env) to update the current shell environment </pre></dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.07.1-2.0.6/extra-dev/dev/paradoxes/dev.html
HTML
mit
10,952
#ifndef GUI_CLASSES_H #define GUI_CLASSES_H #include "tetrisdata.h" #include <gui/panel.h> #include <gui/label.h> #include <gui/button.h> #include <gui/textfield.h> #include <gui/checkbox.h> #include <gui/flowlayout.h> #include <gui/borderlayout.h> #include <gui/combobox.h> #include <gui/progressbar.h> namespace { class Bar : public gui::Panel { public: Bar() { setPreferredSize(TetrisData::getInstance().getWindowBarHeight(), TetrisData::getInstance().getWindowBarHeight()); setBackgroundColor(TetrisData::getInstance().getWindowBarColor()); setLayout<gui::FlowLayout>(gui::FlowLayout::LEFT, 5.f, 0.f); } }; class Background : public gui::Panel { public: Background(const mw::Sprite& background) { setBackground(background); setLayout<gui::BorderLayout>(); } }; class Label : public gui::Label { public: Label(std::string text, mw::Font font) : gui::Label(text, font) { auto color = TetrisData::getInstance().getLabelTextColor(); auto color2 = TetrisData::getInstance().getLabelBackgroundColor(); setTextColor(TetrisData::getInstance().getLabelTextColor()); setBackgroundColor(TetrisData::getInstance().getLabelBackgroundColor()); } }; class Button : public gui::Button { public: Button(std::string text, mw::Font font) : gui::Button(text, font) { setFocusColor(TetrisData::getInstance().getButtonFocusColor()); setTextColor(TetrisData::getInstance().getButtonTextColor()); setHoverColor(TetrisData::getInstance().getButtonHoverColor()); setPushColor(TetrisData::getInstance().getButtonPushColor()); setBackgroundColor(TetrisData::getInstance().getButtonBackgroundColor()); setBorderColor(TetrisData::getInstance().getButtonBorderColor()); setAutoSizeToFitText(true); } }; class CheckBox : public gui::CheckBox { public: CheckBox(std::string text, const mw::Font& font) : gui::CheckBox(text, font, TetrisData::getInstance().getCheckboxBoxSprite(), TetrisData::getInstance().getCheckboxCheckSprite()) { setTextColor(TetrisData::getInstance().getCheckboxTextColor()); setBackgroundColor(TetrisData::getInstance().getCheckboxBackgroundColor()); setBoxColor(TetrisData::getInstance().getCheckboxBoxColor()); setCheckColor(TetrisData::getInstance().getChecboxCheckColor()); } }; class RadioButton : public gui::CheckBox { public: RadioButton(std::string text, const mw::Font& font) : gui::CheckBox(text, font, TetrisData::getInstance().getRadioButtonBoxSprite(), TetrisData::getInstance().getRadioButtonCheckSprite()) { setTextColor(TetrisData::getInstance().getRadioButtonTextColor()); setBackgroundColor(TetrisData::getInstance().getRadioButtonBackgroundColor()); setBoxColor(TetrisData::getInstance().getRadioButtonBoxColor()); setCheckColor(TetrisData::getInstance().getRadioButtonCheckColor()); } }; class TransparentPanel : public gui::Panel { public: TransparentPanel(float preferredWidth = 100, float preferredHeight = 100) { setBackgroundColor(1, 1, 1, 0); setPreferredSize(preferredWidth, preferredHeight); } virtual ~TransparentPanel() = default; }; using TextField = gui::TextField; class ComboBox : public gui::ComboBox { public: ComboBox(mw::Font font) : gui::ComboBox(font, TetrisData::getInstance().getComboBoxShowDropDownSprite()) { setFocusColor(TetrisData::getInstance().getComboBoxFocusColor()); setTextColor(TetrisData::getInstance().getComboBoxTextColor()); setSelectedBackgroundColor(TetrisData::getInstance().getComboBoxSelectedBackgroundColor()); setSelectedTextColor(TetrisData::getInstance().getComboBoxSelectedTextColor()); setShowDropDownColor(TetrisData::getInstance().getComboBoxShowDropDownColor()); setBackgroundColor(TetrisData::getInstance().getComboBoxBackgroundColor()); setBorderColor(TetrisData::getInstance().getComboBoxBorderColor()); } }; class ProgressBar : public gui::ProgressBar { public: ProgressBar() { } }; } // Namespace anonymous. #endif // GUI_CLASSES_H
mwthinker/Tetris
src/guiclasses.h
C
mit
4,234
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("Task01")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Task01")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [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("7dd1867e-4ce0-4db9-a869-ac7005e33ebf")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
YoTsenkov/TelerikSoftwareAcademyHomeworks
HTMLReal/HTMLSemanticHW/Task01/Properties/AssemblyInfo.cs
C#
mit
1,366
require 'studio_game/player' require 'studio_game/die' module StudioGame describe Game do before do @game = Game.new("Knuckleheads") @initial_health = 100 @player = Player.new("moe", @initial_health) @game.add_player(@player) end it "has a title" do @game.title.should == "Knuckleheads" end it "w00ts the player if a high number is rolled" do Die.any_instance.stub(:roll).and_return(5) @game.play(2) @player.health.should == @initial_health + (15 * 2) end it "skips the player if a medium number is rolled" do Die.any_instance.stub(:roll).and_return(3) @game.play(2) @player.health.should == @initial_health end it "blams the player if a low number is rolled" do Die.any_instance.stub(:roll).and_return(1) @game.play(2) @player.health.should == @initial_health - (10 * 2) end it "assigns a treasure for points during a player's turn" do game = Game.new("Knuckleheads") player = Player.new("moe") game.add_player(player) game.play(1) player.points.should_not be_zero end it "computes total points as the sum of all player points" do game = Game.new("Knuckleheads") player1 = Player.new("moe") player2 = Player.new("larry") game.add_player(player1) game.add_player(player2) player1.found_treasure(Treasure.new(:hammer, 50)) player1.found_treasure(Treasure.new(:hammer, 50)) player2.found_treasure(Treasure.new(:crowbar, 400)) game.total_points.should == 500 end end end
ecrivain/studio_game
spec/studio_game/game_spec.rb
Ruby
mit
1,677
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import json import os from typing import Any, Dict, Iterator, List from dataflow.core.utterance_tokenizer import UtteranceTokenizer from dataflow.multiwoz.create_programs import create_programs_for_trade_dialogue from dataflow.multiwoz.salience_model import DummySalienceModel, VanillaSalienceModel def load_test_trade_dialogues(data_dir: str) -> Iterator[Dict[str, Any]]: """Returns selected test dialogues. To extract a dialogue from the TRADE processed json file: $ jq '.[] | select (.dialogue_idx == "MUL1626.json")' dev_dials.json """ multiwoz_2_1_dir = os.path.join(data_dir, "multiwoz_2_1") for dialogue_id in [ "MUL1626.json", "PMUL3166.json", "MUL2258.json", "MUL2199.json", "MUL2096.json", "PMUL3470.json", "PMUL4478.json", ]: trade_dialogue_file = os.path.join(multiwoz_2_1_dir, dialogue_id) trade_dialogue = json.load(open(trade_dialogue_file)) yield trade_dialogue def test_create_programs_with_dummy_salience_model(data_dir: str): """Tests creating programs with a dummy salience model.""" utterance_tokenizer = UtteranceTokenizer() salience_model = DummySalienceModel() expected_num_refer_calls = { "MUL1626.json": 0, "PMUL3166.json": 0, "MUL2258.json": 0, "MUL2199.json": 0, "MUL2096.json": 0, "PMUL3470.json": 0, "PMUL4478.json": 0, } for trade_dialogue in load_test_trade_dialogues(data_dir): dataflow_dialogue, num_refer_calls, _ = create_programs_for_trade_dialogue( trade_dialogue=trade_dialogue, keep_all_domains=True, remove_none=False, fill_none=False, salience_model=salience_model, no_revise=False, avoid_empty_plan=False, utterance_tokenizer=utterance_tokenizer, ) dialogue_id = dataflow_dialogue.dialogue_id assert ( num_refer_calls == expected_num_refer_calls[dialogue_id] ), "{} failed".format(dialogue_id) def test_create_programs_without_revise(data_dir: str): """Tests creating programs without revise calls. It should not use refer calls even with a valid salience model. """ utterance_tokenizer = UtteranceTokenizer() salience_model = VanillaSalienceModel() for trade_dialogue in load_test_trade_dialogues(data_dir): for avoid_empty_plan in [True, False]: _, num_refer_calls, _ = create_programs_for_trade_dialogue( trade_dialogue=trade_dialogue, keep_all_domains=True, remove_none=False, fill_none=False, salience_model=salience_model, no_revise=True, avoid_empty_plan=avoid_empty_plan, utterance_tokenizer=utterance_tokenizer, ) assert num_refer_calls == 0 def test_create_programs_with_vanilla_salience_model(data_dir: str): """Tests creating programs with a vanilla salience model. """ utterance_tokenizer = UtteranceTokenizer() salience_model = VanillaSalienceModel() expected_num_refer_calls = { "MUL1626.json": 1, "PMUL3166.json": 0, "MUL2258.json": 1, "MUL2199.json": 1, "MUL2096.json": 0, "PMUL3470.json": 0, "PMUL4478.json": 0, } for trade_dialogue in load_test_trade_dialogues(data_dir): dataflow_dialogue, num_refer_calls, _ = create_programs_for_trade_dialogue( trade_dialogue=trade_dialogue, keep_all_domains=True, remove_none=False, fill_none=False, salience_model=salience_model, no_revise=False, avoid_empty_plan=False, utterance_tokenizer=utterance_tokenizer, ) dialogue_id = dataflow_dialogue.dialogue_id assert ( num_refer_calls == expected_num_refer_calls[dialogue_id] ), "{} failed".format(dialogue_id) def test_create_programs_with_revise(trade_dialogue_1: Dict[str, Any]): utterance_tokenizer = UtteranceTokenizer() salience_model = VanillaSalienceModel() expected_plans: List[str] = [ # turn 1 """(find (Constraint[Hotel] :name (?= "none") :type (?= "none")))""", # turn 2 """(ReviseConstraint :new (Constraint[Hotel] :name (?= "hilton") :pricerange (?= "cheap") :type (?= "guest house")) :oldLocation (Constraint[Constraint[Hotel]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 3 """(ReviseConstraint :new (Constraint[Hotel] :name (?= "none")) :oldLocation (Constraint[Constraint[Hotel]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 4 """(abandon (Constraint[Hotel]))""", # turn 5 """(find (Constraint[Hotel] :area (?= "west")))""", # turn 6 """(find (Constraint[Restaurant] :area (refer (Constraint[Area]))))""", # turn 7 """(ReviseConstraint :new (Constraint[Restaurant] :pricerange (refer (Constraint[Pricerange]))) :oldLocation (Constraint[Constraint[Restaurant]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 8 "()", # turn 9 """(find (Constraint[Taxi] :departure (?= "none")))""", # turn 10 "()", ] dataflow_dialogue, _, _ = create_programs_for_trade_dialogue( trade_dialogue=trade_dialogue_1, keep_all_domains=True, remove_none=False, fill_none=False, salience_model=salience_model, no_revise=False, avoid_empty_plan=False, utterance_tokenizer=utterance_tokenizer, ) for turn, expected_lispress in zip(dataflow_dialogue.turns, expected_plans): lispress = turn.lispress assert lispress == expected_lispress def test_create_programs_with_revise_with_fill_none(trade_dialogue_1: Dict[str, Any]): utterance_tokenizer = UtteranceTokenizer() salience_model = VanillaSalienceModel() expected_plans: List[str] = [ # turn 1 """(find (Constraint[Hotel] :area (?= "none") :book-day (?= "none") :book-people (?= "none") :book-stay (?= "none") :internet (?= "none") :name (?= "none") :parking (?= "none") :pricerange (?= "none") :stars (?= "none") :type (?= "none")))""", # turn 2 """(ReviseConstraint :new (Constraint[Hotel] :name (?= "hilton") :pricerange (?= "cheap") :type (?= "guest house")) :oldLocation (Constraint[Constraint[Hotel]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 3 """(ReviseConstraint :new (Constraint[Hotel] :name (?= "none")) :oldLocation (Constraint[Constraint[Hotel]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 4 """(abandon (Constraint[Hotel]))""", # turn 5 """(find (Constraint[Hotel] :area (?= "west") :book-day (?= "none") :book-people (?= "none") :book-stay (?= "none") :internet (?= "none") :name (?= "none") :parking (?= "none") :pricerange (?= "none") :stars (?= "none") :type (?= "none")))""", # turn 6 """(find (Constraint[Restaurant] :area (refer (Constraint[Area])) :book-day (?= "none") :book-people (?= "none") :book-time (?= "none") :food (?= "none") :name (?= "none") :pricerange (?= "none")))""", # turn 7 """(ReviseConstraint :new (Constraint[Restaurant] :pricerange (refer (Constraint[Pricerange]))) :oldLocation (Constraint[Constraint[Restaurant]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 8 "()", # turn 9 """(find (Constraint[Taxi] :arriveby (?= "none") :departure (?= "none") :destination (?= "none") :leaveat (?= "none")))""", # turn 10 "()", ] dataflow_dialogue, _, _ = create_programs_for_trade_dialogue( trade_dialogue=trade_dialogue_1, keep_all_domains=True, remove_none=False, fill_none=True, salience_model=salience_model, no_revise=False, avoid_empty_plan=False, utterance_tokenizer=utterance_tokenizer, ) for turn, expected_plan in zip( dataflow_dialogue.turns, expected_plans # pylint: disable=no-member ): lispress = turn.lispress assert lispress == expected_plan def test_create_programs_with_revise_with_avoid_empty_plan( trade_dialogue_1: Dict[str, Any] ): utterance_tokenizer = UtteranceTokenizer() salience_model = VanillaSalienceModel() expected_plans: List[str] = [ # turn 1 """(find (Constraint[Hotel] :name (?= "none") :type (?= "none")))""", # turn 2 """(ReviseConstraint :new (Constraint[Hotel] :name (?= "hilton") :pricerange (?= "cheap") :type (?= "guest house")) :oldLocation (Constraint[Constraint[Hotel]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 3 """(ReviseConstraint :new (Constraint[Hotel] :name (?= "none")) :oldLocation (Constraint[Constraint[Hotel]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 4 """(abandon (Constraint[Hotel]))""", # turn 5 """(find (Constraint[Hotel] :area (?= "west")))""", # turn 6 """(find (Constraint[Restaurant] :area (refer (Constraint[Area]))))""", # turn 7 """(ReviseConstraint :new (Constraint[Restaurant] :pricerange (refer (Constraint[Pricerange]))) :oldLocation (Constraint[Constraint[Restaurant]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 8 """(ReviseConstraint :new (Constraint[Restaurant] :pricerange (refer (Constraint[Pricerange]))) :oldLocation (Constraint[Constraint[Restaurant]]) :rootLocation (roleConstraint #(Path "output")))""", # turn 9 """(find (Constraint[Taxi] :departure (?= "none")))""", # turn 10 """(ReviseConstraint :new (Constraint[Taxi] :departure (?= "none")) :oldLocation (Constraint[Constraint[Taxi]]) :rootLocation (roleConstraint #(Path "output")))""", ] dataflow_dialogue, _, _ = create_programs_for_trade_dialogue( trade_dialogue=trade_dialogue_1, keep_all_domains=True, remove_none=False, fill_none=False, salience_model=salience_model, no_revise=False, avoid_empty_plan=True, utterance_tokenizer=utterance_tokenizer, ) for turn_part, expected_plan in zip(dataflow_dialogue.turns, expected_plans): lispress = turn_part.lispress assert lispress == expected_plan
microsoft/task_oriented_dialogue_as_dataflow_synthesis
tests/test_dataflow/multiwoz/test_create_programs.py
Python
mit
10,600
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import base64 import urllib import time import random import urlparse import hmac import binascii import httplib2 try: from urlparse import parse_qs parse_qs # placate pyflakes except ImportError: # fall back for Python 2.5 from cgi import parse_qs try: from hashlib import sha1 sha = sha1 except ImportError: # hashlib was added in Python 2.5 import sha import _version __version__ = _version.__version__ OAUTH_VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' class Error(RuntimeError): """Generic exception class.""" def __init__(self, message='OAuth error occurred.'): self._message = message @property def message(self): """A hack to get around the deprecation errors in 2.6.""" return self._message def __str__(self): return self._message class MissingSignature(Error): pass def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def build_xoauth_string(url, consumer, token=None): """Build an XOAUTH string for use in SMTP/IMPA authentication.""" request = Request.from_consumer_and_token(consumer, token, "GET", url) signing_method = SignatureMethod_HMAC_SHA1() request.sign_request(signing_method, consumer, token) params = [] for k, v in sorted(request.iteritems()): if v is not None: params.append('%s="%s"' % (k, escape(v))) return "%s %s %s" % ("GET", url, ','.join(params)) def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, unicode): if not isinstance(s, str): raise TypeError('You are required to pass either unicode or string here, not: %r (%s)' % (type(s), s)) try: s = s.decode('utf-8') except UnicodeDecodeError, le: raise TypeError('You are required to pass either a unicode object or a utf-8 string here. You passed a Python string object which contained non-utf-8: %r. The UnicodeDecodeError that resulted from attempting to interpret it as utf-8 was: %s' % (s, le,)) return s def to_utf8(s): return to_unicode(s).encode('utf-8') def to_unicode_if_string(s): if isinstance(s, basestring): return to_unicode(s) else: return s def to_utf8_if_string(s): if isinstance(s, basestring): return to_utf8(s) else: return s def to_unicode_optional_iterator(x): """ Raise TypeError if x is a str containing non-utf8 bytes or if x is an iterable which contains such a str. """ if isinstance(x, basestring): return to_unicode(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_unicode(e) for e in l ] def to_utf8_optional_iterator(x): """ Raise TypeError if x is a str or if x is an iterable which contains a str. """ if isinstance(x, basestring): return to_utf8(x) try: l = list(x) except TypeError, e: assert 'is not iterable' in str(e) return x else: return [ to_utf8_if_string(e) for e in l ] def escape(s): """Escape a URL including any /.""" return urllib.quote(s.encode('utf-8'), safe='~') def generate_timestamp(): """Get seconds since epoch (UTC).""" return int(time.time()) def generate_nonce(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) def generate_verifier(length=8): """Generate pseudorandom number.""" return ''.join([str(random.randint(0, 9)) for i in range(length)]) class Consumer(object): """A consumer of OAuth-protected services. The OAuth consumer is a "third-party" service that wants to access protected resources from an OAuth service provider on behalf of an end user. It's kind of the OAuth client. Usually a consumer must be registered with the service provider by the developer of the consumer software. As part of that process, the service provider gives the consumer a *key* and a *secret* with which the consumer software can identify itself to the service. The consumer will include its key in each request to identify itself, but will use its secret only when signing requests, to prove that the request is from that particular registered consumer. Once registered, the consumer can then use its consumer credentials to ask the service provider for a request token, kicking off the OAuth authorization process. """ key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def __str__(self): data = {'oauth_consumer_key': self.key, 'oauth_consumer_secret': self.secret} return urllib.urlencode(data) class Token(object): """An OAuth credential used to request authorization or a protected resource. Tokens in OAuth comprise a *key* and a *secret*. The key is included in requests to identify the token being used, but the secret is used only in the signature, to prove that the requester is who the server gave the token to. When first negotiating the authorization, the consumer asks for a *request token* that the live user authorizes with the service provider. The consumer then exchanges the request token for an *access token* that can be used to access protected resources. """ key = None secret = None callback = None callback_confirmed = None verifier = None def __init__(self, key, secret): self.key = key self.secret = secret if self.key is None or self.secret is None: raise ValueError("Key and secret must be set.") def set_callback(self, callback): self.callback = callback self.callback_confirmed = 'true' def set_verifier(self, verifier=None): if verifier is not None: self.verifier = verifier else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query: query = '%s&oauth_verifier=%s' % (query, self.verifier) else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. The resulting string includes the token's secret, so you should never send or store this string where a third party can read it. """ data = { 'oauth_token': self.key, 'oauth_token_secret': self.secret, } if self.callback_confirmed is not None: data['oauth_callback_confirmed'] = self.callback_confirmed return urllib.urlencode(data) @staticmethod def from_string(s): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(s): raise ValueError("Invalid parameter string.") params = parse_qs(s, keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try: key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request.") token = Token(key, secret) try: token.callback_confirmed = params['oauth_callback_confirmed'][0] except KeyError: pass # 1.0, no callback confirmed. return token def __str__(self): return self.to_string() def setter(attr): name = attr.__name__ def getter(self): try: return self.__dict__[name] except KeyError: raise AttributeError(name) def deleter(self): del self.__dict__[name] return property(getter, attr, deleter) class Request(dict): """The parameters and information for an HTTP request, suitable for authorizing with OAuth credentials. When a consumer wants to access a service's protected resources, it does so using a signed HTTP request identifying itself (the consumer) with its key, and providing an access token authorized by the end user to access those resources. """ version = OAUTH_VERSION def __init__(self, method=HTTP_METHOD, url=None, parameters=None, body='', is_form_encoded=False): if url is not None: self.url = to_unicode(url) self.method = method if parameters is not None: for k, v in parameters.iteritems(): k = to_unicode(k) v = to_unicode_optional_iterator(v) self[k] = v self.body = body self.is_form_encoded = is_form_encoded @setter def url(self, value): self.__dict__['url'] = value if value is not None: scheme, netloc, path, params, query, fragment = urlparse.urlparse(value) # Exclude default port numbers. if scheme == 'http' and netloc[-3:] == ':80': netloc = netloc[:-3] elif scheme == 'https' and netloc[-4:] == ':443': netloc = netloc[:-4] if scheme not in ('http', 'https'): raise ValueError("Unsupported URL %s (%s)." % (value, scheme)) # Normalized URL excludes params, query, and fragment. self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None)) else: self.normalized_url = None self.__dict__['url'] = None @setter def method(self, value): self.__dict__['method'] = value.upper() def _get_timestamp_nonce(self): return self['oauth_timestamp'], self['oauth_nonce'] def get_nonoauth_parameters(self): """Get any non-OAuth parameters.""" return dict([(k, v) for k, v in self.iteritems() if not k.startswith('oauth_')]) def to_header(self, realm=''): """Serialize as a header for an HTTPAuth request.""" oauth_params = ((k, v) for k, v in self.items() if k.startswith('oauth_')) stringy_params = ((k, escape(str(v))) for k, v in oauth_params) header_params = ('%s="%s"' % (k, v) for k, v in stringy_params) params_header = ', '.join(header_params) auth_header = 'OAuth realm="%s"' % realm if params_header: auth_header = "%s, %s" % (auth_header, params_header) return {'Authorization': auth_header} def to_postdata(self): """Serialize as post data for a POST request.""" d = {} for k, v in self.iteritems(): d[k.encode('utf-8')] = to_utf8_optional_iterator(v) # tell urlencode to deal with sequence values and map them correctly # to resulting querystring. for example self["k"] = ["v1", "v2"] will # result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D return urllib.urlencode(d, True).replace('+', '%20') def to_url(self): """Serialize as a URL for a GET request.""" base_url = urlparse.urlparse(self.url) try: query = base_url.query except AttributeError: # must be python <2.5 query = base_url[4] query = parse_qs(query) for k, v in self.items(): query.setdefault(k, []).append(v) try: scheme = base_url.scheme netloc = base_url.netloc path = base_url.path params = base_url.params fragment = base_url.fragment except AttributeError: # must be python <2.5 scheme = base_url[0] netloc = base_url[1] path = base_url[2] params = base_url[3] fragment = base_url[5] url = (scheme, netloc, path, params, urllib.urlencode(query, True), fragment) return urlparse.urlunparse(url) def get_parameter(self, parameter): ret = self.get(parameter) if ret is None: raise Error('Parameter not found: %s' % parameter) return ret def get_normalized_parameters(self): """Return a string that contains the parameters that must be signed.""" items = [] for key, value in self.iteritems(): if key == 'oauth_signature': continue # 1.0a/9.1.1 states that kvp must be sorted by key, then by value, # so we unpack sequence values into multiple items for sorting. if isinstance(value, basestring): items.append((to_utf8_if_string(key), to_utf8(value))) else: try: value = list(value) except TypeError, e: assert 'is not iterable' in str(e) items.append((to_utf8_if_string(key), to_utf8_if_string(value))) else: items.extend((to_utf8_if_string(key), to_utf8_if_string(item)) for item in value) # Include any query string parameters from the provided URL query = urlparse.urlparse(self.url)[4] url_items = self._split_url_string(query).items() url_items = [(to_utf8(k), to_utf8(v)) for k, v in url_items if k != 'oauth_signature' ] items.extend(url_items) items.sort() encoded_str = urllib.urlencode(items) # Encode signature parameters per Oauth Core 1.0 protocol # spec draft 7, section 3.6 # (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6) # Spaces must be encoded with "%20" instead of "+" return encoded_str.replace('+', '%20').replace('%7E', '~') def sign_request(self, signature_method, consumer, token): """Set the signature parameter to the result of sign.""" if not self.is_form_encoded: # according to # http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # section 4.1.1 "OAuth Consumers MUST NOT include an # oauth_body_hash parameter on requests with form-encoded # request bodies." self['oauth_body_hash'] = base64.b64encode(sha(self.body).digest()) if 'oauth_consumer_key' not in self: self['oauth_consumer_key'] = consumer.key if token and 'oauth_token' not in self: self['oauth_token'] = token.key self['oauth_signature_method'] = signature_method.name self['oauth_signature'] = signature_method.sign(self, consumer, token) @classmethod def make_timestamp(cls): """Get seconds since epoch (UTC).""" return str(int(time.time())) @classmethod def make_nonce(cls): """Generate pseudorandom number.""" return str(random.randint(0, 100000000)) @classmethod def from_request(cls, http_method, http_url, headers=None, parameters=None, query_string=None): """Combines multiple parameter sources.""" if parameters is None: parameters = {} # Headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header[6:] try: # Get the parameters from the header. header_params = cls._split_header(auth_header) parameters.update(header_params) except: raise Error('Unable to parse OAuth parameters from ' 'Authorization header.') # GET or POST query string. if query_string: query_params = cls._split_url_string(query_string) parameters.update(query_params) # URL parameters. param_str = urlparse.urlparse(http_url)[4] # query url_params = cls._split_url_string(param_str) parameters.update(url_params) if parameters: return cls(http_method, http_url, parameters) return None @classmethod def from_consumer_and_token(cls, consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None, body='', is_form_encoded=False): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': consumer.key, 'oauth_timestamp': cls.make_timestamp(), 'oauth_nonce': cls.make_nonce(), 'oauth_version': cls.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key if token.verifier: parameters['oauth_verifier'] = token.verifier return Request(http_method, http_url, parameters, body=body, is_form_encoded=is_form_encoded) @classmethod def from_token_and_callback(cls, token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return cls(http_method, http_url, parameters) @staticmethod def _split_header(header): """Turn Authorization: header into parameters.""" params = {} parts = header.split(',') for param in parts: # Ignore realm parameter. if param.find('realm') > -1: continue # Remove whitespace. param = param.strip() # Split key-value. param_parts = param.split('=', 1) # Remove quotes and unescape the value. params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params @staticmethod def _split_url_string(param_str): """Turn URL string into parameters.""" parameters = parse_qs(param_str.encode('utf-8'), keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters class Client(httplib2.Http): """OAuthClient is a worker to attempt to execute a request.""" def __init__(self, consumer, token=None, cache=None, timeout=None, proxy_info=None): if consumer is not None and not isinstance(consumer, Consumer): raise ValueError("Invalid consumer.") if token is not None and not isinstance(token, Token): raise ValueError("Invalid token.") self.consumer = consumer self.token = token self.method = SignatureMethod_HMAC_SHA1() httplib2.Http.__init__(self, cache=cache, timeout=timeout, proxy_info=proxy_info) def set_signature_method(self, method): if not isinstance(method, SignatureMethod): raise ValueError("Invalid signature method.") self.method = method def request(self, uri, method="GET", body='', headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): DEFAULT_POST_CONTENT_TYPE = 'application/x-www-form-urlencoded' if not isinstance(headers, dict): headers = {} if method == "POST": headers['Content-Type'] = headers.get('Content-Type', DEFAULT_POST_CONTENT_TYPE) is_form_encoded = \ headers.get('Content-Type') == 'application/x-www-form-urlencoded' if is_form_encoded and body: parameters = dict([(k,v[0]) for k,v in parse_qs(body).items()]) else: parameters = None req = Request.from_consumer_and_token(self.consumer, token=self.token, http_method=method, http_url=uri, parameters=parameters, body=body, is_form_encoded=is_form_encoded) req.sign_request(self.method, self.consumer, self.token) schema, rest = urllib.splittype(uri) if rest.startswith('//'): hierpart = '//' else: hierpart = '' host, rest = urllib.splithost(rest) realm = schema + ':' + hierpart + host if method == "POST" and is_form_encoded: body = req.to_postdata() elif method == "GET": uri = req.to_url() else: headers.update(req.to_header(realm=realm)) return httplib2.Http.request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) class Server(object): """A skeletal implementation of a service provider, providing protected resources to requests from authorized consumers. This class implements the logic to check requests for authorization. You can use it with your web server or web framework to protect certain resources with OAuth. """ timestamp_threshold = 300 # In seconds, five minutes. version = OAUTH_VERSION signature_methods = None def __init__(self, signature_methods=None): self.signature_methods = signature_methods or {} def add_signature_method(self, signature_method): self.signature_methods[signature_method.name] = signature_method return self.signature_methods def verify_request(self, request, consumer, token): """Verifies an api call and checks all the parameters.""" self._check_version(request) self._check_signature(request, consumer, token) parameters = request.get_nonoauth_parameters() return parameters def build_authenticate_header(self, realm=''): """Optional support for the authenticate header.""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} def _check_version(self, request): """Verify the correct version of the request for this server.""" version = self._get_version(request) if version and version != self.version: raise Error('OAuth version %s not supported.' % str(version)) def _get_version(self, request): """Return the version of the request for this server.""" try: version = request.get_parameter('oauth_version') except: version = OAUTH_VERSION return version def _get_signature_method(self, request): """Figure out the signature with some defaults.""" try: signature_method = request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # Get the signature method object. signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_verifier(self, request): return request.get_parameter('oauth_verifier') def _check_signature(self, request, consumer, token): timestamp, nonce = request._get_timestamp_nonce() self._check_timestamp(timestamp) signature_method = self._get_signature_method(request) try: signature = request.get_parameter('oauth_signature') except: raise MissingSignature('Missing oauth_signature.') # Validate the signature. valid = signature_method.check(request, consumer, token, signature) if not valid: key, base = signature_method.signing_base(request, consumer, token) raise Error('Invalid signature. Expected signature base ' 'string: %s' % base) def _check_timestamp(self, timestamp): """Verify that timestamp is recentish.""" timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise Error('Expired timestamp: given %d and now %s has a ' 'greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) class SignatureMethod(object): """A way of signing requests. The OAuth protocol lets consumers and service providers pick a way to sign requests. This interface shows the methods expected by the other `oauth` modules for signing requests. Subclass it and implement its methods to provide a new way to sign requests. """ def signing_base(self, request, consumer, token): """Calculates the string that needs to be signed. This method returns a 2-tuple containing the starting key for the signing and the message to be signed. The latter may be used in error messages to help clients debug their software. """ raise NotImplementedError def sign(self, request, consumer, token): """Returns the signature for the given request, based on the consumer and token also provided. You should use your implementation of `signing_base()` to build the message to sign. Otherwise it may be less useful for debugging. """ raise NotImplementedError def check(self, request, consumer, token, signature): """Returns whether the given signature is the correct signature for the given consumer and token signing the given request.""" built = self.sign(request, consumer, token) return built == signature class SignatureMethod_HMAC_SHA1(SignatureMethod): name = 'HMAC-SHA1' def signing_base(self, request, consumer, token): if not hasattr(request, 'normalized_url') or request.normalized_url is None: raise ValueError("Base URL for request is not set.") sig = ( escape(request.method), escape(request.normalized_url), escape(request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def sign(self, request, consumer, token): """Builds the base signature string.""" key, raw = self.signing_base(request, consumer, token) hashed = hmac.new(key, raw, sha) # Calculate the digest base 64. return binascii.b2a_base64(hashed.digest())[:-1] class SignatureMethod_PLAINTEXT(SignatureMethod): name = 'PLAINTEXT' def signing_base(self, request, consumer, token): """Concatenates the consumer key and secret with the token's secret.""" sig = '%s&' % escape(consumer.secret) if token: sig = sig + escape(token.secret) return sig, sig def sign(self, request, consumer, token): key, raw = self.signing_base(request, consumer, token) return raw
jasonrubenstein/python_oauth2
oauth2/__init__.py
Python
mit
29,031
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.FrontDoor { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// RoutingRulesOperations operations. /// </summary> internal partial class RoutingRulesOperations : IServiceOperations<FrontDoorManagementClient>, IRoutingRulesOperations { /// <summary> /// Initializes a new instance of the RoutingRulesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RoutingRulesOperations(FrontDoorManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FrontDoorManagementClient /// </summary> public FrontDoorManagementClient Client { get; private set; } /// <summary> /// Lists all of the Routing Rules within a Front Door. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='frontDoorName'> /// Name of the Front Door which is globally unique. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RoutingRule>>> ListByFrontDoorWithHttpMessagesAsync(string resourceGroupName, string frontDoorName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 80) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 80); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"); } } if (frontDoorName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "frontDoorName"); } if (frontDoorName != null) { if (frontDoorName.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "frontDoorName", 64); } if (frontDoorName.Length < 5) { throw new ValidationException(ValidationRules.MinLength, "frontDoorName", 5); } if (!System.Text.RegularExpressions.Regex.IsMatch(frontDoorName, "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$")) { throw new ValidationException(ValidationRules.Pattern, "frontDoorName", "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$"); } } string apiVersion = "2019-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("frontDoorName", frontDoorName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByFrontDoor", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{frontDoorName}", System.Uri.EscapeDataString(frontDoorName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RoutingRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RoutingRule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a Routing Rule with the specified Rule name within the specified Front /// Door. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='frontDoorName'> /// Name of the Front Door which is globally unique. /// </param> /// <param name='routingRuleName'> /// Name of the Routing Rule which is unique within the Front Door. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RoutingRule>> GetWithHttpMessagesAsync(string resourceGroupName, string frontDoorName, string routingRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 80) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 80); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"); } } if (frontDoorName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "frontDoorName"); } if (frontDoorName != null) { if (frontDoorName.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "frontDoorName", 64); } if (frontDoorName.Length < 5) { throw new ValidationException(ValidationRules.MinLength, "frontDoorName", 5); } if (!System.Text.RegularExpressions.Regex.IsMatch(frontDoorName, "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$")) { throw new ValidationException(ValidationRules.Pattern, "frontDoorName", "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$"); } } if (routingRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routingRuleName"); } if (routingRuleName != null) { if (routingRuleName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "routingRuleName", 90); } if (routingRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "routingRuleName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(routingRuleName, "^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$")) { throw new ValidationException(ValidationRules.Pattern, "routingRuleName", "^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$"); } } string apiVersion = "2019-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("frontDoorName", frontDoorName); tracingParameters.Add("routingRuleName", routingRuleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules/{routingRuleName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{frontDoorName}", System.Uri.EscapeDataString(frontDoorName)); _url = _url.Replace("{routingRuleName}", System.Uri.EscapeDataString(routingRuleName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RoutingRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RoutingRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a new Routing Rule with the specified Rule name within the /// specified Front Door. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='frontDoorName'> /// Name of the Front Door which is globally unique. /// </param> /// <param name='routingRuleName'> /// Name of the Routing Rule which is unique within the Front Door. /// </param> /// <param name='routingRuleParameters'> /// Routing Rule properties needed to create a new Front Door. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RoutingRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string frontDoorName, string routingRuleName, RoutingRule routingRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<RoutingRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, frontDoorName, routingRuleName, routingRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes an existing Routing Rule with the specified parameters. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='frontDoorName'> /// Name of the Front Door which is globally unique. /// </param> /// <param name='routingRuleName'> /// Name of the Routing Rule which is unique within the Front Door. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string frontDoorName, string routingRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, frontDoorName, routingRuleName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates a new Routing Rule with the specified Rule name within the /// specified Front Door. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='frontDoorName'> /// Name of the Front Door which is globally unique. /// </param> /// <param name='routingRuleName'> /// Name of the Routing Rule which is unique within the Front Door. /// </param> /// <param name='routingRuleParameters'> /// Routing Rule properties needed to create a new Front Door. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RoutingRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string frontDoorName, string routingRuleName, RoutingRule routingRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 80) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 80); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"); } } if (frontDoorName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "frontDoorName"); } if (frontDoorName != null) { if (frontDoorName.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "frontDoorName", 64); } if (frontDoorName.Length < 5) { throw new ValidationException(ValidationRules.MinLength, "frontDoorName", 5); } if (!System.Text.RegularExpressions.Regex.IsMatch(frontDoorName, "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$")) { throw new ValidationException(ValidationRules.Pattern, "frontDoorName", "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$"); } } if (routingRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routingRuleName"); } if (routingRuleName != null) { if (routingRuleName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "routingRuleName", 90); } if (routingRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "routingRuleName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(routingRuleName, "^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$")) { throw new ValidationException(ValidationRules.Pattern, "routingRuleName", "^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$"); } } if (routingRuleParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routingRuleParameters"); } string apiVersion = "2019-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("frontDoorName", frontDoorName); tracingParameters.Add("routingRuleName", routingRuleName); tracingParameters.Add("routingRuleParameters", routingRuleParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules/{routingRuleName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{frontDoorName}", System.Uri.EscapeDataString(frontDoorName)); _url = _url.Replace("{routingRuleName}", System.Uri.EscapeDataString(routingRuleName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(routingRuleParameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routingRuleParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RoutingRule>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RoutingRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RoutingRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 202) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RoutingRule>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes an existing Routing Rule with the specified parameters. /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='frontDoorName'> /// Name of the Front Door which is globally unique. /// </param> /// <param name='routingRuleName'> /// Name of the Routing Rule which is unique within the Front Door. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string frontDoorName, string routingRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 80) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 80); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"); } } if (frontDoorName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "frontDoorName"); } if (frontDoorName != null) { if (frontDoorName.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "frontDoorName", 64); } if (frontDoorName.Length < 5) { throw new ValidationException(ValidationRules.MinLength, "frontDoorName", 5); } if (!System.Text.RegularExpressions.Regex.IsMatch(frontDoorName, "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$")) { throw new ValidationException(ValidationRules.Pattern, "frontDoorName", "^[a-zA-Z0-9]+([-a-zA-Z0-9]?[a-zA-Z0-9])*$"); } } if (routingRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routingRuleName"); } if (routingRuleName != null) { if (routingRuleName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "routingRuleName", 90); } if (routingRuleName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "routingRuleName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(routingRuleName, "^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$")) { throw new ValidationException(ValidationRules.Pattern, "routingRuleName", "^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$"); } } string apiVersion = "2019-04-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("frontDoorName", frontDoorName); tracingParameters.Add("routingRuleName", routingRuleName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/frontDoors/{frontDoorName}/routingRules/{routingRuleName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{frontDoorName}", System.Uri.EscapeDataString(frontDoorName)); _url = _url.Replace("{routingRuleName}", System.Uri.EscapeDataString(routingRuleName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all of the Routing Rules within a Front Door. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RoutingRule>>> ListByFrontDoorNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByFrontDoorNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RoutingRule>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<RoutingRule>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
jamestao/azure-sdk-for-net
src/SDKs/FrontDoor/Management.FrontDoor/Generated/RoutingRulesOperations.cs
C#
mit
59,304
namespace android.view { [global::MonoJavaBridge.JavaClass()] public partial class GestureDetector : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static GestureDetector() { InitJNI(); } protected GestureDetector(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.GestureDetector.OnDoubleTapListener_))] public interface OnDoubleTapListener : global::MonoJavaBridge.IJavaObject { bool onSingleTapConfirmed(android.view.MotionEvent arg0); bool onDoubleTap(android.view.MotionEvent arg0); bool onDoubleTapEvent(android.view.MotionEvent arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.GestureDetector.OnDoubleTapListener))] public sealed partial class OnDoubleTapListener_ : java.lang.Object, OnDoubleTapListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnDoubleTapListener_() { InitJNI(); } internal OnDoubleTapListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onSingleTapConfirmed8728; bool android.view.GestureDetector.OnDoubleTapListener.onSingleTapConfirmed(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_._onSingleTapConfirmed8728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, global::android.view.GestureDetector.OnDoubleTapListener_._onSingleTapConfirmed8728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTap8729; bool android.view.GestureDetector.OnDoubleTapListener.onDoubleTap(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTap8729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTap8729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTapEvent8730; bool android.view.GestureDetector.OnDoubleTapListener.onDoubleTapEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTapEvent8730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTapEvent8730, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.OnDoubleTapListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$OnDoubleTapListener")); global::android.view.GestureDetector.OnDoubleTapListener_._onSingleTapConfirmed8728 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onSingleTapConfirmed", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTap8729 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onDoubleTap", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.OnDoubleTapListener_._onDoubleTapEvent8730 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnDoubleTapListener_.staticClass, "onDoubleTapEvent", "(Landroid/view/MotionEvent;)Z"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.GestureDetector.OnGestureListener_))] public interface OnGestureListener : global::MonoJavaBridge.IJavaObject { void onLongPress(android.view.MotionEvent arg0); bool onSingleTapUp(android.view.MotionEvent arg0); bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3); bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3); void onShowPress(android.view.MotionEvent arg0); bool onDown(android.view.MotionEvent arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.GestureDetector.OnGestureListener))] public sealed partial class OnGestureListener_ : java.lang.Object, OnGestureListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnGestureListener_() { InitJNI(); } internal OnGestureListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onLongPress8731; void android.view.GestureDetector.OnGestureListener.onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onLongPress8731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onLongPress8731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSingleTapUp8732; bool android.view.GestureDetector.OnGestureListener.onSingleTapUp(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onSingleTapUp8732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onSingleTapUp8732, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onScroll8733; bool android.view.GestureDetector.OnGestureListener.onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onScroll8733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onScroll8733, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onFling8734; bool android.view.GestureDetector.OnGestureListener.onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onFling8734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onFling8734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onShowPress8735; void android.view.GestureDetector.OnGestureListener.onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onShowPress8735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onShowPress8735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDown8736; bool android.view.GestureDetector.OnGestureListener.onDown(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_._onDown8736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.OnGestureListener_.staticClass, global::android.view.GestureDetector.OnGestureListener_._onDown8736, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.OnGestureListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$OnGestureListener")); global::android.view.GestureDetector.OnGestureListener_._onLongPress8731 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.OnGestureListener_._onSingleTapUp8732 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.OnGestureListener_._onScroll8733 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.OnGestureListener_._onFling8734 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.OnGestureListener_._onShowPress8735 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.OnGestureListener_._onDown8736 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.OnGestureListener_.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z"); } } [global::MonoJavaBridge.JavaClass()] public partial class SimpleOnGestureListener : java.lang.Object, OnGestureListener, OnDoubleTapListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static SimpleOnGestureListener() { InitJNI(); } protected SimpleOnGestureListener(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onLongPress8737; public virtual void onLongPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onLongPress8737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onLongPress8737, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSingleTapConfirmed8738; public virtual bool onSingleTapConfirmed(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapConfirmed8738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapConfirmed8738, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTap8739; public virtual bool onDoubleTap(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTap8739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTap8739, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDoubleTapEvent8740; public virtual bool onDoubleTapEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTapEvent8740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTapEvent8740, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onSingleTapUp8741; public virtual bool onSingleTapUp(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapUp8741, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapUp8741, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onScroll8742; public virtual bool onScroll(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onScroll8742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onScroll8742, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onFling8743; public virtual bool onFling(android.view.MotionEvent arg0, android.view.MotionEvent arg1, float arg2, float arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onFling8743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onFling8743, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _onShowPress8744; public virtual void onShowPress(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onShowPress8744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onShowPress8744, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onDown8745; public virtual bool onDown(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener._onDown8745, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._onDown8745, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _SimpleOnGestureListener8746; public SimpleOnGestureListener() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.SimpleOnGestureListener.staticClass, global::android.view.GestureDetector.SimpleOnGestureListener._SimpleOnGestureListener8746); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.SimpleOnGestureListener.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector$SimpleOnGestureListener")); global::android.view.GestureDetector.SimpleOnGestureListener._onLongPress8737 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onLongPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapConfirmed8738 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onSingleTapConfirmed", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTap8739 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDoubleTap", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onDoubleTapEvent8740 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDoubleTapEvent", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onSingleTapUp8741 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onSingleTapUp", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onScroll8742 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onScroll", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onFling8743 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onFling", "(Landroid/view/MotionEvent;Landroid/view/MotionEvent;FF)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._onShowPress8744 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onShowPress", "(Landroid/view/MotionEvent;)V"); global::android.view.GestureDetector.SimpleOnGestureListener._onDown8745 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "onDown", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector.SimpleOnGestureListener._SimpleOnGestureListener8746 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.SimpleOnGestureListener.staticClass, "<init>", "()V"); } } internal static global::MonoJavaBridge.MethodId _onTouchEvent8747; public virtual bool onTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector._onTouchEvent8747, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._onTouchEvent8747, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnDoubleTapListener8748; public virtual void setOnDoubleTapListener(android.view.GestureDetector.OnDoubleTapListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector._setOnDoubleTapListener8748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._setOnDoubleTapListener8748, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setIsLongpressEnabled8749; public virtual void setIsLongpressEnabled(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.GestureDetector._setIsLongpressEnabled8749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._setIsLongpressEnabled8749, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isLongpressEnabled8750; public virtual bool isLongpressEnabled() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.GestureDetector._isLongpressEnabled8750); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.GestureDetector.staticClass, global::android.view.GestureDetector._isLongpressEnabled8750); } internal static global::MonoJavaBridge.MethodId _GestureDetector8751; public GestureDetector(android.view.GestureDetector.OnGestureListener arg0, android.os.Handler arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8751, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8752; public GestureDetector(android.view.GestureDetector.OnGestureListener arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8753; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8754; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1, android.os.Handler arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GestureDetector8755; public GestureDetector(android.content.Context arg0, android.view.GestureDetector.OnGestureListener arg1, android.os.Handler arg2, bool arg3) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.GestureDetector.staticClass, global::android.view.GestureDetector._GestureDetector8755, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.GestureDetector.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/GestureDetector")); global::android.view.GestureDetector._onTouchEvent8747 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.view.GestureDetector._setOnDoubleTapListener8748 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "setOnDoubleTapListener", "(Landroid/view/GestureDetector$OnDoubleTapListener;)V"); global::android.view.GestureDetector._setIsLongpressEnabled8749 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "setIsLongpressEnabled", "(Z)V"); global::android.view.GestureDetector._isLongpressEnabled8750 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "isLongpressEnabled", "()Z"); global::android.view.GestureDetector._GestureDetector8751 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;)V"); global::android.view.GestureDetector._GestureDetector8752 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/view/GestureDetector$OnGestureListener;)V"); global::android.view.GestureDetector._GestureDetector8753 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;)V"); global::android.view.GestureDetector._GestureDetector8754 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;)V"); global::android.view.GestureDetector._GestureDetector8755 = @__env.GetMethodIDNoThrow(global::android.view.GestureDetector.staticClass, "<init>", "(Landroid/content/Context;Landroid/view/GestureDetector$OnGestureListener;Landroid/os/Handler;Z)V"); } } }
koush/androidmono
jni/MonoJavaBridge/android/generated/android/view/GestureDetector.cs
C#
mit
31,077
/* * Copyright (c) 2000-2007 Apple Computer, Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * Mach Operating System * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* File: machine.h * Author: Avadis Tevanian, Jr. * Date: 1986 * * Machine independent machine abstraction. */ #ifndef _MACH_MACHINE_H_ #define _MACH_MACHINE_H_ #ifndef __ASSEMBLER__ #define CPU_STATE_MAX 4 #define CPU_STATE_USER 0 #define CPU_STATE_SYSTEM 1 #define CPU_STATE_IDLE 2 #define CPU_STATE_NICE 3 /* * Capability bits used in the definition of cpu_type. */ #define CPU_ARCH_MASK 0xff000000 /* mask for architecture bits */ #define CPU_ARCH_ABI64 0x01000000 /* 64 bit ABI */ /* * Machine types known by all. */ #define CPU_TYPE_ANY ((cpu_type_t) -1) #define CPU_TYPE_VAX ((cpu_type_t) 1) /* skip ((cpu_type_t) 2) */ /* skip ((cpu_type_t) 3) */ /* skip ((cpu_type_t) 4) */ /* skip ((cpu_type_t) 5) */ #define CPU_TYPE_MC680x0 ((cpu_type_t) 6) #define CPU_TYPE_X86 ((cpu_type_t) 7) #define CPU_TYPE_I386 CPU_TYPE_X86 /* compatibility */ #define CPU_TYPE_X86_64 (CPU_TYPE_X86 | CPU_ARCH_ABI64) /* skip CPU_TYPE_MIPS ((cpu_type_t) 8) */ /* skip ((cpu_type_t) 9) */ #define CPU_TYPE_MC98000 ((cpu_type_t) 10) #define CPU_TYPE_HPPA ((cpu_type_t) 11) #define CPU_TYPE_ARM ((cpu_type_t) 12) #define CPU_TYPE_MC88000 ((cpu_type_t) 13) #define CPU_TYPE_SPARC ((cpu_type_t) 14) #define CPU_TYPE_I860 ((cpu_type_t) 15) /* skip CPU_TYPE_ALPHA ((cpu_type_t) 16) */ /* skip ((cpu_type_t) 17) */ #define CPU_TYPE_POWERPC ((cpu_type_t) 18) #define CPU_TYPE_POWERPC64 (CPU_TYPE_POWERPC | CPU_ARCH_ABI64) /* * Machine subtypes (these are defined here, instead of in a machine * dependent directory, so that any program can get all definitions * regardless of where is it compiled). */ /* * Capability bits used in the definition of cpu_subtype. */ #define CPU_SUBTYPE_MASK 0xff000000 /* mask for feature flags */ #define CPU_SUBTYPE_LIB64 0x80000000 /* 64 bit libraries */ /* * Object files that are hand-crafted to run on any * implementation of an architecture are tagged with * CPU_SUBTYPE_MULTIPLE. This functions essentially the same as * the "ALL" subtype of an architecture except that it allows us * to easily find object files that may need to be modified * whenever a new implementation of an architecture comes out. * * It is the responsibility of the implementor to make sure the * software handles unsupported implementations elegantly. */ #define CPU_SUBTYPE_MULTIPLE ((cpu_subtype_t) -1) #define CPU_SUBTYPE_LITTLE_ENDIAN ((cpu_subtype_t) 0) #define CPU_SUBTYPE_BIG_ENDIAN ((cpu_subtype_t) 1) /* * Machine threadtypes. * This is none - not defined - for most machine types/subtypes. */ #define CPU_THREADTYPE_NONE ((cpu_threadtype_t) 0) /* * VAX subtypes (these do *not* necessary conform to the actual cpu * ID assigned by DEC available via the SID register). */ #define CPU_SUBTYPE_VAX_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_VAX780 ((cpu_subtype_t) 1) #define CPU_SUBTYPE_VAX785 ((cpu_subtype_t) 2) #define CPU_SUBTYPE_VAX750 ((cpu_subtype_t) 3) #define CPU_SUBTYPE_VAX730 ((cpu_subtype_t) 4) #define CPU_SUBTYPE_UVAXI ((cpu_subtype_t) 5) #define CPU_SUBTYPE_UVAXII ((cpu_subtype_t) 6) #define CPU_SUBTYPE_VAX8200 ((cpu_subtype_t) 7) #define CPU_SUBTYPE_VAX8500 ((cpu_subtype_t) 8) #define CPU_SUBTYPE_VAX8600 ((cpu_subtype_t) 9) #define CPU_SUBTYPE_VAX8650 ((cpu_subtype_t) 10) #define CPU_SUBTYPE_VAX8800 ((cpu_subtype_t) 11) #define CPU_SUBTYPE_UVAXIII ((cpu_subtype_t) 12) /* * 680x0 subtypes * * The subtype definitions here are unusual for historical reasons. * NeXT used to consider 68030 code as generic 68000 code. For * backwards compatability: * * CPU_SUBTYPE_MC68030 symbol has been preserved for source code * compatability. * * CPU_SUBTYPE_MC680x0_ALL has been defined to be the same * subtype as CPU_SUBTYPE_MC68030 for binary comatability. * * CPU_SUBTYPE_MC68030_ONLY has been added to allow new object * files to be tagged as containing 68030-specific instructions. */ #define CPU_SUBTYPE_MC680x0_ALL ((cpu_subtype_t) 1) #define CPU_SUBTYPE_MC68030 ((cpu_subtype_t) 1) /* compat */ #define CPU_SUBTYPE_MC68040 ((cpu_subtype_t) 2) #define CPU_SUBTYPE_MC68030_ONLY ((cpu_subtype_t) 3) /* * I386 subtypes */ #define CPU_SUBTYPE_INTEL(f, m) ((cpu_subtype_t) (f) + ((m) << 4)) #define CPU_SUBTYPE_I386_ALL CPU_SUBTYPE_INTEL(3, 0) #define CPU_SUBTYPE_386 CPU_SUBTYPE_INTEL(3, 0) #define CPU_SUBTYPE_486 CPU_SUBTYPE_INTEL(4, 0) #define CPU_SUBTYPE_486SX CPU_SUBTYPE_INTEL(4, 8) // 8 << 4 = 128 #define CPU_SUBTYPE_586 CPU_SUBTYPE_INTEL(5, 0) #define CPU_SUBTYPE_PENT CPU_SUBTYPE_INTEL(5, 0) #define CPU_SUBTYPE_PENTPRO CPU_SUBTYPE_INTEL(6, 1) #define CPU_SUBTYPE_PENTII_M3 CPU_SUBTYPE_INTEL(6, 3) #define CPU_SUBTYPE_PENTII_M5 CPU_SUBTYPE_INTEL(6, 5) #define CPU_SUBTYPE_CELERON CPU_SUBTYPE_INTEL(7, 6) #define CPU_SUBTYPE_CELERON_MOBILE CPU_SUBTYPE_INTEL(7, 7) #define CPU_SUBTYPE_PENTIUM_3 CPU_SUBTYPE_INTEL(8, 0) #define CPU_SUBTYPE_PENTIUM_3_M CPU_SUBTYPE_INTEL(8, 1) #define CPU_SUBTYPE_PENTIUM_3_XEON CPU_SUBTYPE_INTEL(8, 2) #define CPU_SUBTYPE_PENTIUM_M CPU_SUBTYPE_INTEL(9, 0) #define CPU_SUBTYPE_PENTIUM_4 CPU_SUBTYPE_INTEL(10, 0) #define CPU_SUBTYPE_PENTIUM_4_M CPU_SUBTYPE_INTEL(10, 1) #define CPU_SUBTYPE_ITANIUM CPU_SUBTYPE_INTEL(11, 0) #define CPU_SUBTYPE_ITANIUM_2 CPU_SUBTYPE_INTEL(11, 1) #define CPU_SUBTYPE_XEON CPU_SUBTYPE_INTEL(12, 0) #define CPU_SUBTYPE_XEON_MP CPU_SUBTYPE_INTEL(12, 1) #define CPU_SUBTYPE_INTEL_FAMILY(x) ((x) & 15) #define CPU_SUBTYPE_INTEL_FAMILY_MAX 15 #define CPU_SUBTYPE_INTEL_MODEL(x) ((x) >> 4) #define CPU_SUBTYPE_INTEL_MODEL_ALL 0 /* * X86 subtypes. */ #define CPU_SUBTYPE_X86_ALL ((cpu_subtype_t)3) #define CPU_SUBTYPE_X86_64_ALL ((cpu_subtype_t)3) #define CPU_SUBTYPE_X86_ARCH1 ((cpu_subtype_t)4) #define CPU_THREADTYPE_INTEL_HTT ((cpu_threadtype_t) 1) /* * Mips subtypes. */ #define CPU_SUBTYPE_MIPS_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_MIPS_R2300 ((cpu_subtype_t) 1) #define CPU_SUBTYPE_MIPS_R2600 ((cpu_subtype_t) 2) #define CPU_SUBTYPE_MIPS_R2800 ((cpu_subtype_t) 3) #define CPU_SUBTYPE_MIPS_R2000a ((cpu_subtype_t) 4) /* pmax */ #define CPU_SUBTYPE_MIPS_R2000 ((cpu_subtype_t) 5) #define CPU_SUBTYPE_MIPS_R3000a ((cpu_subtype_t) 6) /* 3max */ #define CPU_SUBTYPE_MIPS_R3000 ((cpu_subtype_t) 7) /* * MC98000 (PowerPC) subtypes */ #define CPU_SUBTYPE_MC98000_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_MC98601 ((cpu_subtype_t) 1) /* * HPPA subtypes for Hewlett-Packard HP-PA family of * risc processors. Port by NeXT to 700 series. */ #define CPU_SUBTYPE_HPPA_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_HPPA_7100 ((cpu_subtype_t) 0) /* compat */ #define CPU_SUBTYPE_HPPA_7100LC ((cpu_subtype_t) 1) /* * MC88000 subtypes. */ #define CPU_SUBTYPE_MC88000_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_MC88100 ((cpu_subtype_t) 1) #define CPU_SUBTYPE_MC88110 ((cpu_subtype_t) 2) /* * SPARC subtypes */ #define CPU_SUBTYPE_SPARC_ALL ((cpu_subtype_t) 0) /* * I860 subtypes */ #define CPU_SUBTYPE_I860_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_I860_860 ((cpu_subtype_t) 1) /* * PowerPC subtypes */ #define CPU_SUBTYPE_POWERPC_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_POWERPC_601 ((cpu_subtype_t) 1) #define CPU_SUBTYPE_POWERPC_602 ((cpu_subtype_t) 2) #define CPU_SUBTYPE_POWERPC_603 ((cpu_subtype_t) 3) #define CPU_SUBTYPE_POWERPC_603e ((cpu_subtype_t) 4) #define CPU_SUBTYPE_POWERPC_603ev ((cpu_subtype_t) 5) #define CPU_SUBTYPE_POWERPC_604 ((cpu_subtype_t) 6) #define CPU_SUBTYPE_POWERPC_604e ((cpu_subtype_t) 7) #define CPU_SUBTYPE_POWERPC_620 ((cpu_subtype_t) 8) #define CPU_SUBTYPE_POWERPC_750 ((cpu_subtype_t) 9) #define CPU_SUBTYPE_POWERPC_7400 ((cpu_subtype_t) 10) #define CPU_SUBTYPE_POWERPC_7450 ((cpu_subtype_t) 11) #define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100) /* * ARM subtypes */ #define CPU_SUBTYPE_ARM_ALL ((cpu_subtype_t) 0) #define CPU_SUBTYPE_ARM_V4T ((cpu_subtype_t) 5) #define CPU_SUBTYPE_ARM_V6 ((cpu_subtype_t) 6) #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7) #define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8) #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9) #define CPU_SUBTYPE_ARM_V7F ((cpu_subtype_t) 10) /* Cortex A9 */ #define CPU_SUBTYPE_ARM_V7S ((cpu_subtype_t) 11) #define CPU_SUBTYPE_ARM_V7K ((cpu_subtype_t) 12) /* Kirkwood40 */ #define CPU_SUBTYPE_ARM_V8 ((cpu_subtype_t) 13) #endif /* !__ASSEMBLER__ */ /* * CPU families (sysctl hw.cpufamily) * * These are meant to identify the CPU's marketing name - an * application can map these to (possibly) localized strings. * NB: the encodings of the CPU families are intentionally arbitrary. * There is no ordering, and you should never try to deduce whether * or not some feature is available based on the family. * Use feature flags (eg, hw.optional.altivec) to test for optional * functionality. */ #define CPUFAMILY_UNKNOWN 0 #define CPUFAMILY_POWERPC_G3 0xcee41549 #define CPUFAMILY_POWERPC_G4 0x77c184ae #define CPUFAMILY_POWERPC_G5 0xed76d8aa #define CPUFAMILY_INTEL_6_13 0xaa33392b #define CPUFAMILY_INTEL_YONAH 0x73d67300 #define CPUFAMILY_INTEL_MEROM 0x426f69ef #define CPUFAMILY_INTEL_PENRYN 0x78ea4fbc #define CPUFAMILY_INTEL_NEHALEM 0x6b5a4cd2 #define CPUFAMILY_INTEL_WESTMERE 0x573b5eec #define CPUFAMILY_INTEL_SANDYBRIDGE 0x5490b78c #define CPUFAMILY_INTEL_IVYBRIDGE 0x1f65e835 #define CPUFAMILY_ARM_9 0xe73283ae #define CPUFAMILY_ARM_11 0x8ff620d8 #define CPUFAMILY_ARM_XSCALE 0x53b005f5 #define CPUFAMILY_ARM_13 0x0cc90e64 #define CPUFAMILY_ARM_14 0x96077ef1 /* The following synonyms are deprecated: */ #define CPUFAMILY_INTEL_6_14 CPUFAMILY_INTEL_YONAH #define CPUFAMILY_INTEL_6_15 CPUFAMILY_INTEL_MEROM #define CPUFAMILY_INTEL_6_23 CPUFAMILY_INTEL_PENRYN #define CPUFAMILY_INTEL_6_26 CPUFAMILY_INTEL_NEHALEM #define CPUFAMILY_INTEL_CORE CPUFAMILY_INTEL_YONAH #define CPUFAMILY_INTEL_CORE2 CPUFAMILY_INTEL_MEROM #endif /* _MACH_MACHINE_H_ */
dechaoqiu/atosl_ruby
ext/atosl/cputype.h
C
mit
12,342
# Logicmoo AGI for LM489 This is a SWI-Prolog pack that runs LM489 - LOGICMOO IRC channel #logicmoo on [freenode.net](irc://irc.freenode.net:+6697/logicmoo). - LOGICMOO Telegram at [https://t.me/LogicMoo](https://t.me/LogicMoo) # Installation Using SWI-Prolog 7.1 or later: ?- pack_install('https://github.com/logicmoo/logicmoo_agi.git'). Source code available and pull requests accepted at https://logicmoo.org/gitlab/logicmoo/logicmoo_workspace/-/tree/master/packs_sys/logicmoo_agi ```prolog ?- use_module(library(logicmoo_agi)). true. ``` # Some TODOs Document this pack! Write tests Untangle the 'pack' install deps (Moving predicates over here from logicmoo_base) # Not _obligated_ to maintain a git fork just to contribute Dislike having tons of forks that are several commits behind the main git repo? Be old school - Please ask to be added to logicmoo and Contribute directly ! Still, we wont stop you from doing it the Fork+PullRequest method [BSD 2-Clause License](LICENSE) Copyright (c) 2020, logicmoo and Douglas Miles <logicmoo@gmail.com> All rights reserved.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_agi/README.md
Markdown
mit
1,105
--- layout: article title: 解决Sublime Text 无法显示韩文 tags: others date: 2017-08-29 category: others --- # 解决Sublime Text 无法显示韩文 打开 Sublime text --> Preferences --> Setting -- default 找到"font_options": [] 改成"font_options": [ "directwrite"] 如果无法编辑,请在%appdata%\Sublime Text 3\Packages目录手动建议default文件夹,保存了再重新打开 亲测无法修改default配置文件,只能修改User文件,不过依然有效
flyingSnow-hu/brokenslips
_posts/2017-08-29-sublime.md
Markdown
mit
500
import Ember from 'ember'; import { moduleFor, test } from 'ember-qunit'; // The default (application) serializer is the DRF adapter. // see app/serializers/application.js moduleFor('serializer:application', 'DRFSerializer', {}); test('normalizeResponse - results', function(assert) { let serializer = this.subject(); serializer._super = sinon.spy(); let primaryModelClass = {modelName: 'person'}; let payload = { count: 'count', next: '/api/posts/?page=3', previous: '/api/posts/?page=1', other: 'stuff', results: ['result'] }; serializer.normalizeResponse('store', primaryModelClass, payload, 1, 'requestType'); assert.equal(serializer._super.callCount, 1); assert.equal(serializer._super.lastCall.args[0],'store'); assert.propEqual(serializer._super.lastCall.args[1], primaryModelClass); assert.equal(serializer._super.lastCall.args[3], 1); assert.equal(serializer._super.lastCall.args[4], 'requestType'); let modifiedPayload = serializer._super.lastCall.args[2]; assert.equal('result', modifiedPayload[primaryModelClass.modelName][0]); assert.ok(modifiedPayload.meta); assert.equal(modifiedPayload.meta['next'], 3); assert.equal(modifiedPayload.meta['previous'], 1); // Unknown metadata has been passed along to the meta object. assert.equal(modifiedPayload.meta['other'], 'stuff'); }); test('normalizeResponse - results (cursor pagination)', function(assert) { let serializer = this.subject(); serializer._super = sinon.spy(); let primaryModelClass = {modelName: 'person'}; let payload = { next: '/api/posts/?page=3', previous: '/api/posts/?page=1', other: 'stuff', results: ['result'] }; serializer.normalizeResponse('store', primaryModelClass, payload, 1, 'requestType'); assert.equal(serializer._super.callCount, 1); assert.equal(serializer._super.lastCall.args[0],'store'); assert.propEqual(serializer._super.lastCall.args[1], primaryModelClass); assert.equal(serializer._super.lastCall.args[3], 1); assert.equal(serializer._super.lastCall.args[4], 'requestType'); let modifiedPayload = serializer._super.lastCall.args[2]; assert.equal('result', modifiedPayload[primaryModelClass.modelName][0]); assert.ok(modifiedPayload.meta); assert.equal(modifiedPayload.meta['next'], 3); assert.equal(modifiedPayload.meta['previous'], 1); // Unknown metadata has been passed along to the meta object. assert.equal(modifiedPayload.meta['other'], 'stuff'); }); test('normalizeResponse - no results', function(assert) { let serializer = this.subject(); serializer._super = sinon.stub().returns('extracted array'); let primaryModelClass = {modelName: 'person'}; let payload = {other: 'stuff'}; let result = serializer.normalizeResponse('store', primaryModelClass, payload, 1, 'requestType'); assert.equal(result, 'extracted array'); let convertedPayload = {}; convertedPayload[primaryModelClass.modelName] = payload; assert.ok(serializer._super.calledWith('store', primaryModelClass, convertedPayload, 1, 'requestType'), '_super not called properly'); }); test('serializeIntoHash', function(assert) { var serializer = this.subject(); serializer.serialize = sinon.stub().returns({serialized: 'record'}); var hash = {existing: 'hash'}; serializer.serializeIntoHash(hash, 'type', 'record', 'options'); assert.ok(serializer.serialize.calledWith( 'record', 'options' ), 'serialize not called properly'); assert.deepEqual(hash, {serialized: 'record', existing: 'hash'}); }); test('keyForAttribute', function(assert) { var serializer = this.subject(); var result = serializer.keyForAttribute('firstName'); assert.equal(result, 'first_name'); }); test('keyForRelationship', function(assert) { var serializer = this.subject(); var result = serializer.keyForRelationship('projectManagers', 'hasMany'); assert.equal(result, 'project_managers'); }); test('extractPageNumber', function(assert) { var serializer = this.subject(); assert.equal(serializer.extractPageNumber('http://xmpl.com/a/p/?page=3234'), 3234, 'extractPageNumber failed on absolute URL'); assert.equal(serializer.extractPageNumber('/a/p/?page=3234'), 3234, 'extractPageNumber failed on relative URL'); assert.equal(serializer.extractPageNumber(null), null, 'extractPageNumber failed on null URL'); assert.equal(serializer.extractPageNumber('/a/p/'), null, 'extractPageNumber failed on URL without query params'); assert.equal(serializer.extractPageNumber('/a/p/?ordering=-timestamp&user=123'), null, 'extractPageNumber failed on URL with other query params'); assert.equal(serializer.extractPageNumber('/a/p/?fpage=23&pages=[1,2,3],page=123g&page=g123'), null, 'extractPageNumber failed on URL with similar query params'); }); test('extractRelationships', function(assert) { assert.expect(47); // Generates a payload hash for the specified urls array. This is used to generate // new payloads to test with different the relationships types. function ResourceHash(urls) { this.id = 1; var letter = 'a'; var self = this; urls.forEach(function(url) { self[letter] = url; letter = String.fromCharCode(letter.charCodeAt(0) + 1); }); } // Generates a typeClass object for the specified relationship and payload. This is used to generate // new stubbed out typeClasses to test with different the relationships types and payload. function TypeClass(relationship, resourceHash) { this.eachRelationship = function(callback, binding) { for (var key in resourceHash) { if (resourceHash.hasOwnProperty(key) && key !== 'links' && key !== 'id') { callback.call(binding, key, {kind: relationship}); } } }; } // More URLs can be tested by adding them to the correct section and adjusting // the expectedPayloadKeys and the expectedLinksKeys variables. var testURLs = [ // Valid relationship URLs. '/api/users/1', 'https://example.com/api/users/1', 'http://example.com/api/users/1', '//example.com/api/users/1', // Invalid relationship URLs 'api', 'ftp://example.com//api/users/1', 'http//example.com/api/users/1', 'https//example.com/api/users/1', '///example.com/api/users/1', '', null ]; // Error messages. var missingKeyMessage = 'Modified payload for the %@ relationship is missing the %@ property.'; var wrongSizePayloadMessage = 'Modified payload for the %@ relationship is not the correct size.'; var wrongSizeLinksMessage = 'The links hash for the %@ relationship is not the correct size.'; var serializer = this.subject(); // Add a spy to _super because we only want to test our code. serializer._super = sinon.spy(); // Test with hasMany and belongsTo relationships. var validRelationships = ['hasMany', 'belongsTo']; validRelationships.forEach(function(relationship) { var resourceHash = new ResourceHash(testURLs); serializer.extractRelationships(new TypeClass(relationship, resourceHash), resourceHash); assert.equal(Object.keys(resourceHash).length, 9, Ember.String.fmt(wrongSizePayloadMessage, [relationship])); // 'j' & 'k' need to be handled separately because they are false values. var expectedPayloadKeys = ['id', 'links', 'e', 'f', 'g', 'h', 'i']; expectedPayloadKeys.forEach(function(key) { assert.ok(resourceHash[key], Ember.String.fmt(missingKeyMessage, [relationship, key])); }); assert.equal(resourceHash['j'], '', Ember.String.fmt(missingKeyMessage, [relationship, 'j'])); assert.equal(resourceHash['k'], null, Ember.String.fmt(missingKeyMessage, [relationship], 'k')); assert.equal(Object.keys(resourceHash.links).length, 4, Ember.String.fmt(wrongSizeLinksMessage, [relationship])); var i = 0; var expectedLinksKeys = ['a', 'b', 'c', 'd']; expectedLinksKeys.forEach(function(key) { assert.equal(resourceHash.links[key], testURLs[i], Ember.String.fmt('Links value of property %@ in the %@ relationship is not correct.', [key, relationship])); i++; }); }); assert.equal(serializer._super.callCount, 2, '_super() was not called once for each relationship.'); // Test with an unknown relationship. var relationship = 'xxUnknownXX'; var payload = new ResourceHash(testURLs); serializer.extractRelationships(new TypeClass(relationship, payload), payload); assert.equal(Object.keys(payload).length, 13, Ember.String.fmt(wrongSizePayloadMessage, [relationship])); // 'j' & 'k' need to be handled separately because they are false values. var expectedPayloadKeys = ['id', 'links', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']; expectedPayloadKeys.forEach(function(key) { assert.ok(payload[key], Ember.String.fmt(missingKeyMessage, [relationship, key])); }); assert.equal(payload['j'], '', Ember.String.fmt(missingKeyMessage, [relationship, 'j'])); assert.equal(payload['k'], null, Ember.String.fmt(missingKeyMessage, [relationship], 'k')); assert.equal(Object.keys(payload.links).length, 0, Ember.String.fmt(wrongSizeLinksMessage, [relationship])); assert.equal(serializer._super.callCount, 3, Ember.String.fmt('_super() was not called for the %@ relationship.', [relationship])); });
benkonrath/ember-django-adapter
tests/unit/serializers/drf-test.js
JavaScript
mit
9,271
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Imaging; using ImageTagWPF.Data; using ImageTagWPF.Model; using Microsoft.Win32; using Image = ImageTagWPF.Data.Image; using Color = System.Windows.Media.Color; using PixelFormat = System.Windows.Media.PixelFormat; using Point = System.Drawing.Point; using Size = System.Drawing.Size; namespace ImageTagWPF.Code { public static class Util { private static Random Random = new Random(); public static string GetFileHashSHA1(string filename) { string hash = null; using (var cryptoProvider = new SHA1CryptoServiceProvider()) { using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { hash = BitConverter.ToString(cryptoProvider.ComputeHash(fs)).Replace("-", "").ToLowerInvariant(); } } return hash; } public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions) { if (extensions == null) throw new ArgumentNullException("extensions"); IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>(); foreach (string ext in extensions) { files = files.Concat(dir.GetFiles(ext)); } return files; } // https://stackoverflow.com/questions/5936628/get-items-in-view-within-a-listbox public static bool BoundsContainsItem(this FrameworkElement container, FrameworkElement element) { if (!element.IsVisible) return false; Rect bounds = element.TransformToAncestor(container) .TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight)); var rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight); return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight); } /* public static Color ToColor(this TagType type) { switch (type) { case TagType.Descriptor: return Colors.Black; case TagType.Subject: return Colors.DarkOrange; case TagType.Artist: return Colors.MediumPurple; case TagType.Series: return Colors.Crimson; default: return Colors.Gray; } } */ public static BitmapImage GetThumbnailForImage(string fullPath, int thumbWidth = 200) { BitmapImage thumbImage = null; if (File.Exists(fullPath)) { thumbImage = new BitmapImage(); bool isWebM = false; try { // BitmapImage.UriSource must be in a BeginInit/EndInit block thumbImage.BeginInit(); thumbImage.CacheOption = BitmapCacheOption.OnLoad; thumbImage.UriSource = new Uri(fullPath, UriKind.Absolute); // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. thumbImage.DecodePixelWidth = thumbWidth; thumbImage.EndInit(); thumbImage.Freeze(); } catch (Exception ex) { if (fullPath.ToLowerInvariant().EndsWith(".webm")) { isWebM = true; } else { App.Log.Error("Couldn't create thumbnnail for: " + fullPath + " : " + ex.Message); thumbImage = null; } } if (isWebM) { try { var tempImageFilename = Guid.NewGuid().ToString() + ".png"; var tempImagePath = Path.Combine(App.ImageTag.Settings.TempDirectory, tempImageFilename); var ffMpeg = new NReco.VideoConverter.FFMpegConverter(); ffMpeg.GetVideoThumbnail(fullPath, tempImagePath, 5); thumbImage = new BitmapImage(); thumbImage.BeginInit(); thumbImage.CacheOption = BitmapCacheOption.OnLoad; thumbImage.UriSource = new Uri(tempImagePath, UriKind.Absolute); thumbImage.DecodePixelWidth = thumbWidth; thumbImage.EndInit(); thumbImage.Freeze(); File.Delete(tempImagePath); } catch (Exception ex) { App.Log.Error("Couldn't create thumbnnail for webm: " + fullPath + " : " + ex.Message); thumbImage = null; } } } return thumbImage; } public static BitmapImage GetThumbnailForImageSafe(string fullPath, int thumbWidth = 200) { BitmapImage thumbImage = null; if (File.Exists(fullPath)) { thumbImage = new BitmapImage(); try { Stream stream = new System.IO.MemoryStream(); // Create new MemoryStream Bitmap bitmap = new Bitmap(fullPath); // Create new Bitmap (System.Drawing.Bitmap) from the existing image file (albumArtSource set to its path name) bitmap.Save(stream, ImageFormat.Png); // Save the loaded Bitmap into the MemoryStream - Png format was the only one I tried that didn't cause an error (tried Jpg, Bmp, MemoryBmp) bitmap.Dispose(); // Dispose bitmap so it releases the source image file // BitmapImage.UriSource must be in a BeginInit/EndInit block thumbImage.BeginInit(); thumbImage.CacheOption = BitmapCacheOption.OnLoad; //thumbImage.UriSource = new Uri(fullPath, UriKind.Absolute); thumbImage.StreamSource = stream; // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. thumbImage.DecodePixelWidth = thumbWidth; thumbImage.EndInit(); thumbImage.Freeze(); } catch (Exception ex) { App.Log.Error("Couldn't create thumbnnail for: " + fullPath + " : " + ex.Message); thumbImage = null; } } return thumbImage; } public static void UpdateParentTagsRecursive(Image image, Tag tag) { foreach (var parentTag in tag.ParentTags) { if (!image.Tags.Contains(parentTag)) image.Tags.Add(parentTag); UpdateParentTagsRecursive(image, parentTag); } } public static void UpdateImageTags(List<ImageFileThumbData> images, List<TagModel> tags, CancellationToken token, bool addOnly = false) { int threadDivisor = 16; int threadListSize = images.Count/threadDivisor; bool useThreading = false; if (!useThreading || images.Count < threadDivisor) { // Do it the old way, just iterate // Go through selected files and add tags foreach (var imageItem in images) { if (token.IsCancellationRequested) break; UpdateSingleImageTags(imageItem, tags, addOnly); } } else { // Thread it! var imagesListLists = new List<List<ImageFileThumbData>>(); for (int i = 0; i < threadDivisor; i++) { List<ImageFileThumbData> threadList = null; if (i == threadDivisor - 1) { // Last; take all remainder threadList = images.Skip(i*threadListSize).ToList(); } else { threadList = images.Skip(i * threadListSize).Take(threadListSize).ToList(); } imagesListLists.Add(threadList); } ThreadSafeImages = new BlockingCollection<Image>(); var taskList = new List<Task>(); foreach (var imageList in imagesListLists) { var task = Task.Run(() => { foreach (var imageItem in imageList) { UpdateSingleImageTags(imageItem, tags, addOnly, useSafeCollection:true); } }); taskList.Add(task); } // Check for dupes //var firstList = imagesListLists[0]; //var fullList = new List<ImageFileThumbData>(); //foreach (var imagesList in imagesListLists) //{ // fullList.AddRange(imagesList); //} //var dupeImages = from i in fullList // group i by new { i.FullPath } // into grp // where grp.Count() > 1 // select grp.Key; //foreach (var dupe in dupeImages) //{ // App.Log.Error("Duplicate file: " + dupe.FullPath); //} bool allTasksDone = false; while (!allTasksDone) { bool done = true; foreach (var task in taskList) { if (!task.IsCompleted) { done = false; break; } } if (done) { foreach (var threadSafeImage in ThreadSafeImages) { App.ImageTag.Entities.Images.Add(threadSafeImage); } ThreadSafeImages.Dispose(); allTasksDone = true; break; } } } } private static BlockingCollection<Image> ThreadSafeImages; public static void UpdateSingleImageTags(ImageFileThumbData imageItem, List<TagModel> tags, bool addOnly = false, bool useSafeCollection = false) { // Get the image data if (imageItem != null) { // If it's still null, must be legit if (imageItem.Image == null) { // Add a new image to the database, and tag it var newImageRecord = new Image() { Path = imageItem.FullPath, Checksum = Util.GetFileHashSHA1(imageItem.FullPath) }; // Add all selected tags foreach (var tag in tags) { if (!newImageRecord.Tags.Contains(tag.Tag)) newImageRecord.Tags.Add(tag.Tag); // Also add parent tags UpdateParentTagsRecursive(newImageRecord, tag.Tag); // Update recently used on tag tag.Tag.LastUsed = DateTime.Now; } imageItem.Image = newImageRecord; if (!useSafeCollection) App.ImageTag.Entities.Images.Add(newImageRecord); else ThreadSafeImages.Add(newImageRecord); } else { // We have this image already, just add the tag to it var existingImage = imageItem.Image; // Remove tags that we don't have selected if (!addOnly) { var selectedTagIDs = tags.Select(x => (int)x.Tag.ID); var removedList = existingImage.Tags.Where(x => !selectedTagIDs.Contains((int)x.ID)).ToArray(); foreach (var removeTag in removedList) { existingImage.Tags.Remove(removeTag); } } // Add all selected tags foreach (var tag in tags) { if (existingImage.Tags.Count == 0 || !existingImage.Tags.Contains(tag.Tag)) { existingImage.Tags.Add(tag.Tag); // Also add parent tags UpdateParentTagsRecursive(existingImage, tag.Tag); // Update recently used on tag tag.Tag.LastUsed = DateTime.Now; } } } } } public static void RemoveImageTags(List<ImageFileThumbData> images, List<TagModel> tags) { // Go through selected files and add tags foreach (var imageItem in images) { // Get the image data if (imageItem != null) { if (imageItem.Image == null) { // Skip, it's not tagged } else { // We have this image already, just add the tag to it var existingImage = imageItem.Image; foreach (var removeTag in tags) { existingImage.Tags.Remove(removeTag.Tag); } } } } } public static void UpdateImageParentTags(Image image) { // Go through selected files and add tags var tags = image.Tags.ToList(); foreach (var tag in tags) { // Get the image data if (tag != null) { UpdateParentTagsRecursive(image, tag); // Update recently used on tag tag.LastUsed = DateTime.Now; } } } public static bool RetryMove(string filename, string dest, int interval = 1000, int retries = 10) { for (int i = 0; i < retries; i++) { try { File.Move(filename, dest); return true; } catch (Exception ex) { App.Log.Error("Couldn't rename file: " + filename + ": " + dest + ". Retry " + (i + 1)); } Thread.Sleep(interval); } return false; } public static void UpdateImageRating(List<ImageFileThumbData> images, int rating) { // Go through selected files and add tags foreach (var imageItem in images) { if (App.CancellationTokenSource.Token.IsCancellationRequested) break; // Get the image data if (imageItem != null) { if (imageItem.Image == null) { // Add a new image to the database, and tag it var newImageRecord = new Image() { Path = imageItem.FullPath, Checksum = Util.GetFileHashSHA1(imageItem.FullPath) }; newImageRecord.Rating = rating; imageItem.Image = newImageRecord; App.ImageTag.Entities.Images.Add(newImageRecord); } else { // We have this image already, just add the tag to it var existingImage = imageItem.Image; existingImage.Rating = rating; } } } } public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = Random.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } public static T GetVisualChild<T>(this Visual referenceVisual) where T : Visual { Visual child = null; if (referenceVisual == null) return null; for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceVisual); i++) { child = VisualTreeHelper.GetChild(referenceVisual, i) as Visual; if (child != null && child is T) { break; } else if (child != null) { child = GetVisualChild<T>(child); if (child != null && child is T) { break; } } } return child as T; } /// <summary> /// Searches a TreeView for the provided object and selects it if found /// </summary> /// <param name="treeView">The TreeView containing the item</param> /// <param name="item">The item to search and select</param> public static void SelectItem(this TreeView treeView, object item, bool select = true) { ExpandAndSelectItem(treeView, item, select); } public static void ExpandFirstItem(this TreeView treeView) { foreach (var item in treeView.Items) { TreeViewItem itm = (TreeViewItem)treeView.ItemContainerGenerator.ContainerFromItem(item); if (itm == null) continue; itm.IsExpanded = true; } } /// <summary> /// Finds the provided object in an ItemsControl's children and selects it /// </summary> /// <param name="parentContainer">The parent container whose children will be searched for the selected item</param> /// <param name="itemToSelect">The item to select</param> /// <returns>True if the item is found and selected, false otherwise</returns> private static bool ExpandAndSelectItem(ItemsControl container, object itemToSelect, bool select = true) { // Check all items at the current level foreach (Object currentItem in container.Items) { // If the data item matches the item we want to select, set the corresponding IsSelected to true if (currentItem == itemToSelect) { TreeViewItem currentContainer = container.ItemContainerGenerator.ContainerFromItem(currentItem) as TreeViewItem; if (currentContainer != null) { currentContainer.IsExpanded = true; if (select) { currentContainer.IsSelected = true; currentContainer.BringIntoView(); currentContainer.Focus(); } // The itemToSelect was found and has been selected return true; } } } // If we get to this point, the SelectedItem was not found at the // current level, so we must check the children foreach (Object item in container.Items) { TreeViewItem currentContainer = container.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem; // If the currentContainer has children if (currentContainer != null && currentContainer.Items.Count > 0) { // Keep track of if the TreeViewItem was expanded or not bool wasExpanded = currentContainer.IsExpanded; // Expand the current TreeViewItem so we can check its child TreeViewItems currentContainer.IsExpanded = true; // If the TreeViewItem child containers have not been generated, we must listen to // the StatusChanged event until they are if (currentContainer.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) { //store the event handler in a variable so we can remove it (in the handler itself) EventHandler eh = null; eh = new EventHandler(delegate { if (currentContainer.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) { //SelectItem(currentContainer, itemToSelect); if (ExpandAndSelectItem(currentContainer, itemToSelect, select) == false) { //The assumption is that code executing in this EventHandler is the result of the parent not //being expanded since the containers were not generated. //since the itemToSelect was not found in the children, collapse the parent since it was previously collapsed currentContainer.IsExpanded = false; } //remove the StatusChanged event handler since we just handled it (we only needed it once) currentContainer.ItemContainerGenerator.StatusChanged -= eh; } }); currentContainer.ItemContainerGenerator.StatusChanged += eh; } else //otherwise the containers have been generated, so look for item to select in the children { if (ExpandAndSelectItem(currentContainer, itemToSelect, select) == false) { //restore the current TreeViewItem's expanded state currentContainer.IsExpanded = wasExpanded; } else //otherwise the node was found and selected, so return true { return true; } } } } //no item was found return false; } public static string GetFullDirectory(this OrganizeDirectory dir) { if (dir.ParentDirectories.Count > 0) { var parent = dir.ParentDirectories.ToList()[0]; var parentDir = GetFullDirectory(parent); return Path.Combine(parentDir, dir.Name); } return dir.Name; } //https://stackoverflow.com/questions/5512921/wpf-richtextbox-appending-coloured-text public static void AppendText(this RichTextBox box, string text, Color color) { TextRange tr = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd); tr.Text = text; try { tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(color)); } catch (FormatException) { } } public static bool TryGetRegisteredApplication(string extension, out string registeredApp) { string extensionId = GetClassesRootKeyDefaultValue(extension); if (extensionId == null) { registeredApp = null; return false; } string openCommand = GetClassesRootKeyDefaultValue( Path.Combine(new[] { extensionId, "shell", "open", "command" })); if (openCommand == null) { registeredApp = null; return false; } if (openCommand.Contains("\"")) { openCommand = openCommand.Split(new[] { "\"" }, StringSplitOptions.RemoveEmptyEntries)[0]; } else { openCommand = openCommand.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0]; } registeredApp = openCommand; return true; } private static string GetClassesRootKeyDefaultValue(string keyPath) { using (var key = Registry.ClassesRoot.OpenSubKey(keyPath)) { if (key == null) { return null; } var defaultValue = key.GetValue(null); if (defaultValue == null) { return null; } return defaultValue.ToString(); } } // https://stackoverflow.com/questions/15558107/quickest-way-to-compare-two-bitmapimages-to-check-if-they-are-different-in-wpf public static bool IsEqual(this BitmapImage image1, BitmapImage image2) { if (image1 == null || image2 == null) { return false; } return image1.ToBytes().SequenceEqual(image2.ToBytes()); } public static byte[] ToBytes(this BitmapImage image) { byte[] data = new byte[] { }; if (image != null) { try { var encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(image)); using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); data = ms.ToArray(); } return data; } catch (Exception ex) { } } return data; } public static bool ImageCompareString(Bitmap firstImage, Bitmap secondImage) { MemoryStream ms = new MemoryStream(); firstImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png); String firstBitmap = Convert.ToBase64String(ms.ToArray()); ms.Position = 0; secondImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png); String secondBitmap = Convert.ToBase64String(ms.ToArray()); if (firstBitmap.Equals(secondBitmap)) { return true; } else { return false; } } public static List<bool> GetHash(Bitmap bmpSource) { List<bool> lResult = new List<bool>(); //create new image with 16x16 pixel Bitmap bmpMin = new Bitmap(bmpSource, new Size(16, 16)); for (int j = 0; j < bmpMin.Height; j++) { for (int i = 0; i < bmpMin.Width; i++) { //reduce colors to true / false lResult.Add(bmpMin.GetPixel(i, j).GetBrightness() < 0.5f); } } return lResult; } public static string GetMD5Hash(string filename) { using (FileStream fStream = File.OpenRead(filename)) { return GetHash<MD5>(fStream); } } public static String GetHash<T>(Stream stream) where T : HashAlgorithm { StringBuilder sb = new StringBuilder(); MethodInfo create = typeof(T).GetMethod("Create", new Type[] { }); using (T crypt = (T)create.Invoke(null, null)) { byte[] hashBytes = crypt.ComputeHash(stream); foreach (byte bt in hashBytes) { sb.Append(bt.ToString("x2")); } } return sb.ToString(); } public static Size GetImageSizeQuick(string file) { int height = 0; int width = 0; using (var imageStream = File.OpenRead(file)) { var decoder = BitmapDecoder.Create(imageStream, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.Default); height = decoder.Frames[0].PixelHeight; width = decoder.Frames[0].PixelWidth; } return new Size(width, height); } } }
drogoganor/ImageTagWPF
src/ImageTagWPF/Code/Util.cs
C#
mit
31,547
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class T_absensi_model extends MY_Model { public $table = 't_absensi'; public $primary_key = 'absensi_id'; public $label = 'absensi_id'; public $fillable = array(); // If you want, you can set an array with the fields that can be filled by insert/update public $protected = array('absensi_id'); // ...Or you can set an array with the fields that cannot be filled by insert/update function __construct() { parent::__construct(); $this->soft_deletes = TRUE; $this->has_one['t_jadwal'] = array('T_jadwal_model','jadwal_id','jadwal_id'); $this->has_one['t_siswa'] = array('T_siswa_model','t_siswa_id','t_siswa_id'); } // get total rows function get_limit_data($limit, $start) { $order = $this->input->post('order'); $dataorder = array(); $where = array(); $i=1; $dataorder[$i++] = 'jadwal_id'; $dataorder[$i++] = 't_siswa_id'; $dataorder[$i++] = 'kehadiran'; if(!empty($this->input->post('jadwal_id'))){ $where['jadwal_id'] = $this->input->post('jadwal_id'); } if(!empty($this->input->post('t_siswa_id'))){ $where['t_siswa_id'] = $this->input->post('t_siswa_id'); } if(!empty($this->input->post('kehadiran'))){ $where['LOWER(kehadiran) LIKE'] = '%'.strtolower($this->input->post('kehadiran')).'%'; } $this->where($where); $result['total_rows'] = $this->count_rows(); $this->where($where); $this->order_by( $dataorder[$order[0]["column"]], $order[0]["dir"]); $this->limit($start, $limit); $result['get_db']=$this ->with_t_jadwal() ->with_t_siswa() ->get_all(); return $result; } } /* End of file T_absensi_model.php */ /* Location: ./application/models/T_absensi_model.php */ /* Please DO NOT modify this information : */ /* http://harviacode.com */
creatindo/sim_sekolah
application/models/T_absensi_model.php
PHP
mit
2,110
<!DOCTYPE html> <meta charset="utf-8"> <html> <head> <title>GitHub statistics</title> <meta property="og:title" content="GitHub statistics" /> <meta property="og:image" content="http://www.richard-musiol.de/ghstats/screenshot4.png" /> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } .line { fill: none; stroke-width: 1.5px; } </style> </head> <body> <script src="d3.v3.js"></script> <script> var margin = {top: 20, right: 100, bottom: 50, left: 50}; var width = window.innerWidth; var height = window.innerHeight; var parseDate = d3.time.format("%Y-%m-%d").parse; var x = d3.time.scale() .range([0, width - margin.left - margin.right]); var y = d3.scale.log() .range([height - margin.top - margin.bottom, 0]); var color = d3.scale.category10(); var line = d3.svg.line() .interpolate("basis") .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.value); }); var svg = d3.select("body").append("svg"); svg.attr("width", width); svg.attr("height", height); svg = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.tsv("output.tsv", function(error, data) { var domain = d3.keys(data[0]).filter(function(name) { return name !== "date"; }); color.domain(domain); var languages = domain.map(function(name) { return { name: name, values: data.map(function(d) { return { date: parseDate(d.date), value: +d[name] }; }) }; }); x.domain(d3.extent(data, function(d) { return parseDate(d.date); })); y.domain([0.45, d3.max(languages, function(c) { return d3.max(c.values, function(v) { return v.value; }); })]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height - margin.top - margin.bottom) + ")") .call(d3.svg.axis().scale(x).orient("bottom")); svg.append("g") .attr("class", "y axis") .call(d3.svg.axis().scale(y).orient("left").tickFormat(d3.format(".1f"))) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("% GitHub Repositories With At Least 500 Stars"); var language = svg.selectAll() .data(languages) .enter().append("g") language.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d) { return color(d.name); }); language.append("text") .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; }) .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.value) + ")"; }) .attr("x", 3) .attr("dy", ".35em") .style("fill", function(d) { return color(d.name); }) .text(function(d) { return d.name; }); }); </script> <a href="https://github.com/neelance/neelance.github.io/tree/master/ghstats">Source Code</a> </body> </html>
neelance/neelance.github.io
ghstats/index.html
HTML
mit
3,155
/* * The MIT License (MIT) * Copyright (c) 2015 SK PLANET. All Rights Reserved. * * 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. */ #ifndef _RUIBUFFERVIDEOENCODER_H #define _RUIBUFFERVIDEOENCODER_H #include "../Common/RUIDef.h" #include "IPPVideoEncoder.h" #include "../h264/common/vm_plus/umc_sys_info.h" #include "RUIBuffer.h" #include "RUIBufferList.h" #include "RUIUDPFrameList.h" using namespace UMC; //#define WRITE_ENCODED_FILE class RUIBufferVideoEncoder : public IPPVideoEncoder { public: RUIBufferVideoEncoder(); ~RUIBufferVideoEncoder(); private: BOOL m_bStop; Ipp64f tickDuration; DWORD m_dwLastReadVideoSourceTick; RUIBuffer* m_pRUIBufferRGB; RUIBufferList* m_pRUIBufferList264; DWORD m_dwEncodedSize; // Áö±Ý±îÁö ÀÎÄÚµùµÈ °á°úÀÇ Å©±â ÇÕ // Socket BOOL m_bUseSocket; BYTE m_nFrameType; DWORD m_dwFrameKey; RUIUDPFrameList* m_pRUIBufferListSend; #ifdef WRITE_ENCODED_FILE BOOL m_bFile; CFile m_fileEncoded; #endif BOOL m_bFirstFrame; public: BOOL GetStop() { return m_bStop; } void SetStop(BOOL bStop) { m_bStop = bStop; } DWORD GetEncodedSize() { return m_dwEncodedSize; } // Socket BOOL GetUseSocket() { return m_bUseSocket; } void SetUseSocket(BOOL bUseSocket) { m_bUseSocket = bUseSocket; } BYTE GetFrameType() { return m_nFrameType; } void SetFrameType(BYTE nFrameType) { m_nFrameType = nFrameType; } RUIUDPFrameList* GetRUIBufferSend() { return m_pRUIBufferListSend; } void SetRUIBufferSend(RUIUDPFrameList* pRUIUDPFrameList) { m_pRUIBufferListSend = pRUIUDPFrameList; } Ipp32s Encode(RUIBuffer* pRUIBufferRGB, RUIBufferList* pRUIBufferList264, int nWidth, int nHeight, DWORD dwBitRate); #ifdef WRITE_ENCODED_FILE BOOL GetFileEnable() { return m_bFile; } void SetFileEnable(BOOL bFile) { m_bFile = bFile; } CFile* GetFile() { return &m_fileEncoded; } #endif public: virtual Status PutOutputData(MediaData* out); virtual Ipp64f GetTick(); virtual int ReadVideoSource (BYTE* pBuffer, DWORD dwOffset, int nItemSize, int nItemCount); virtual int WriteVideoTarget(BYTE* pBuffer, int nItemSize, int nItemCount, FrameType frameType); }; #endif
skplanet/RemoteTestService
TA/skvideo/RUILib/RUIBufferVideoEncoder.h
C
mit
3,524
import { InternalUIConfig, PlayerWrapper, UIManager } from '../src/ts/uimanager'; import { PlayerAPI } from 'bitmovin-player'; import { MockHelper, TestingPlayerAPI } from './helper/MockHelper'; import { MobileV3PlayerEvent } from '../src/ts/mobilev3playerapi'; jest.mock('../src/ts/dom'); // This just simulates a Class that can be wrapped by our PlayerWrapper. // To enable this simple class structure we need a lot of any casts in the tests. class A { private value: object = undefined; get a() { return this.value; } // This is needed to change the actual value of the property giveValueAValue() { this.value = { foo: 'bar' }; } } class B extends A { get b() { return {}; } } class C extends B { get c() { return {}; } } describe('UIManager', () => { describe('PlayerWrapper', () => { let playerWrapper: PlayerWrapper; describe('without inheritance', () => { let superClassInstance: A; beforeEach(() => { const testInstance: PlayerAPI = new A() as any as PlayerAPI; playerWrapper = new PlayerWrapper(testInstance); (testInstance as any).giveValueAValue(); // Change the value of the actual property to simulate async loaded module superClassInstance = playerWrapper.getPlayer() as any as A; }); it('wraps functions', () => { expect(superClassInstance.a).not.toBeUndefined(); }); }); describe('with inheritance', () => { let inheritedClassInstance: C; beforeEach(() => { const testInstance: PlayerAPI = new C() as any as PlayerAPI; playerWrapper = new PlayerWrapper(testInstance); (testInstance as any).giveValueAValue(); // Change the value of the actual property to simulate async loaded module inheritedClassInstance = playerWrapper.getPlayer() as any as C; }); it('wraps functions of super class', () => { expect(inheritedClassInstance.a).not.toBeUndefined(); }); }); }); describe('mobile v3 handling', () => { let playerMock: TestingPlayerAPI; beforeEach(() => { playerMock = MockHelper.getPlayerMock(); // disable HTML element interactions UIManager.prototype.switchToUiVariant = jest.fn(); }); describe('when a PlaylistTransition event is part of PlayerEvent', () => { beforeEach(() => { (playerMock.exports.PlayerEvent as any).SourceError = MobileV3PlayerEvent.SourceError; (playerMock.exports.PlayerEvent as any).PlayerError = MobileV3PlayerEvent.PlayerError; (playerMock.exports.PlayerEvent as any).PlaylistTransition = MobileV3PlayerEvent.PlaylistTransition; }); it('attaches the listener', () => { const onSpy = jest.spyOn(playerMock, 'on'); new UIManager(playerMock, MockHelper.generateDOMMock() as any); expect(onSpy).toHaveBeenCalledWith('playlisttransition', expect.any(Function)); }); describe('and a PlaylistTransition event occurs', () => { it('dispatches onUpdated', () => { const uiManager = new UIManager(playerMock, MockHelper.generateDOMMock() as any); let onUpdatedSpy = jest.fn(); (uiManager.getConfig() as InternalUIConfig).events.onUpdated.subscribe(onUpdatedSpy); playerMock.eventEmitter.firePlaylistTransitionEvent(); expect(onUpdatedSpy).toHaveBeenCalled(); }); }); }); describe('when no PlaylistTransition event is part of PlayerEvent', () => { beforeEach(() => { delete (playerMock.exports.PlayerEvent as any).PlaylistTransition; }); it('does not attach a listener', () => { const onSpy = jest.spyOn(playerMock, 'on'); new UIManager(playerMock, MockHelper.generateDOMMock() as any); expect(onSpy).not.toHaveBeenCalledWith('playlisttransition', expect.any(Function)); }); }); }); });
bitmovin/bitmovin-player-ui
spec/uimanager.spec.ts
TypeScript
mit
3,892
#include "ofTessellator.h" //-------------- polygons ---------------------------------- // // to do polygons, we need tesselation // to do tesselation, we need glu and callbacks.... // ------------------------------------ // one of the callbacks creates new vertices (on intersections, etc), // and there is a potential for memory leaks // if we don't clean up properly // ------------------------------------ // also the easiest system, using beginShape // vertex(), endShape, will also use dynamically // allocated memory // ------------------------------------ // so, therefore, we will be using a static vector here // for two things: // // a) collecting vertices // b) new vertices on combine callback // // important note! // // this assumes single threaded polygon creation // you can have big problems if creating polygons in // multiple threads... please be careful // // (but also be aware that alot of opengl code // is single threaded anyway, so you will have problems // with many things opengl related across threads) // // ------------------------------------ // (note: this implementation is based on code from ftgl) // ------------------------------------ void * memAllocator( void *userData, unsigned int size ){ return malloc(size); } void * memReallocator( void *userData, void* ptr, unsigned int size ){ return realloc(ptr,size); } void memFree( void *userData, void *ptr ){ free (ptr); } //---------------------------------------------------------- ofTessellator::ofTessellator() : cacheTess(NULL) { init(); } //---------------------------------------------------------- ofTessellator::~ofTessellator(){ tessDeleteTess(cacheTess); } //---------------------------------------------------------- ofTessellator::ofTessellator(const ofTessellator & mom) : cacheTess(NULL) { if(&mom != this){ if(cacheTess) tessDeleteTess(cacheTess); init(); } } //---------------------------------------------------------- ofTessellator & ofTessellator::operator=(const ofTessellator & mom){ if(&mom != this){ if(cacheTess) tessDeleteTess(cacheTess); init(); } return *this; } //---------------------------------------------------------- void ofTessellator::init(){ tessAllocator.memalloc = memAllocator; tessAllocator.memrealloc = memReallocator; tessAllocator.memfree = memFree; tessAllocator.meshEdgeBucketSize=0; tessAllocator.meshVertexBucketSize=0; tessAllocator.meshFaceBucketSize=0; tessAllocator.dictNodeBucketSize=0; tessAllocator.regionBucketSize=0; tessAllocator.extraVertices=0; cacheTess = tessNewTess( &tessAllocator ); } //---------------------------------------------------------- void ofTessellator::tessellateToMesh( const ofPolyline& src, ofPolyWindingMode polyWindingMode, ofMesh& dstmesh, bool bIs2D){ ofPolyline& polyline = const_cast<ofPolyline&>(src); tessAddContour( cacheTess, bIs2D?2:3, &polyline.getVertices()[0], sizeof(ofPoint), polyline.size()); performTessellation( polyWindingMode, dstmesh, bIs2D ); } //---------------------------------------------------------- void ofTessellator::tessellateToMesh( const vector<ofPolyline>& src, ofPolyWindingMode polyWindingMode, ofMesh & dstmesh, bool bIs2D ) { // pass vertex pointers to GLU tessellator for ( int i=0; i<(int)src.size(); ++i ) { ofPolyline& polyline = const_cast<ofPolyline&>(src[i]); tessAddContour( cacheTess, bIs2D?2:3, &polyline.getVertices()[0].x, sizeof(ofPoint), polyline.size()); } performTessellation( polyWindingMode, dstmesh, bIs2D ); } //---------------------------------------------------------- void ofTessellator::tessellateToPolylines( const ofPolyline& src, ofPolyWindingMode polyWindingMode, vector<ofPolyline>& dstpoly, bool bIs2D){ ofPolyline& polyline = const_cast<ofPolyline&>(src); tessAddContour( cacheTess, bIs2D?2:3, &polyline.getVertices()[0], sizeof(ofPoint), polyline.size()); performTessellation( polyWindingMode, dstpoly, bIs2D ); } //---------------------------------------------------------- void ofTessellator::tessellateToPolylines( const vector<ofPolyline>& src, ofPolyWindingMode polyWindingMode, vector<ofPolyline>& dstpoly, bool bIs2D ) { // pass vertex pointers to GLU tessellator for ( int i=0; i<(int)src.size(); ++i ) { ofPolyline& polyline = const_cast<ofPolyline&>(src[i]); tessAddContour( cacheTess, bIs2D?2:3, &polyline.getVertices()[0].x, sizeof(ofPoint), polyline.size()); } performTessellation( polyWindingMode, dstpoly, bIs2D ); } //---------------------------------------------------------- void ofTessellator::performTessellation(ofPolyWindingMode polyWindingMode, ofMesh& dstmesh, bool bIs2D ) { if (!tessTesselate(cacheTess, polyWindingMode, TESS_POLYGONS, 3, 3, 0)){ ofLogError("ofTessellator") << "performTessellation(): mesh polygon tessellation failed, winding mode " << polyWindingMode; return; } int numVertices = tessGetVertexCount( cacheTess ); int numIndices = tessGetElementCount( cacheTess )*3; dstmesh.clear(); dstmesh.addVertices((ofVec3f*)tessGetVertices(cacheTess),numVertices); dstmesh.addIndices((ofIndexType*)tessGetElements(cacheTess),numIndices); /*ofIndexType * tessElements = (ofIndexType *)tessGetElements(cacheTess); for(int i=0;i<numIndices;i++){ if(tessElements[i]!=TESS_UNDEF) dstmesh.addIndex(tessElements[i]); }*/ dstmesh.setMode(OF_PRIMITIVE_TRIANGLES); } //---------------------------------------------------------- void ofTessellator::performTessellation(ofPolyWindingMode polyWindingMode, vector<ofPolyline>& dstpoly, bool bIs2D ) { if (!tessTesselate(cacheTess, polyWindingMode, TESS_BOUNDARY_CONTOURS, 0, 3, 0)){ ofLogError("ofTessellator") << "performTesselation(): polyline boundary contours tessellation failed, winding mode " << polyWindingMode; return; } const ofPoint* verts = (ofPoint*)tessGetVertices(cacheTess); const TESSindex* elems = tessGetElements(cacheTess); const int nelems = tessGetElementCount(cacheTess); dstpoly.resize(nelems); for (int i = 0; i < nelems; ++i) { int b = elems[i*2]; int n = elems[i*2+1]; dstpoly[i].clear(); dstpoly[i].addVertices(&verts[b],n); dstpoly[i].setClosed(true); } }
SpecularStudio/ofQt
of_v0.9.0/libs/openFrameworks/graphics/ofTessellator.cpp
C++
mit
6,142
define(['plugins/router', 'durandal/app', 'services/config', 'services/datacontext', 'services/logger','knockout'], function (router, app, config, datacontext, logger,ko) { var routes = ko.observableArray([]); var isAdminUser = ko.observable(); var showSplash = ko.observable(false); var vm = { router: router, showSplash:showSplash, isAdminUser:isAdminUser, routes:routes, activate: activate, deactivate:deactivate }; return vm; //called automatically by Durandal function activate() { return datacontext.fetchMetadata().then(function() { return true; }).then(function() { return datacontext.getUserAccountDataLocal() .then(function () { return isAdminUser(datacontext.checkAdmin()); }); }).then(function() { window.globalRoutes.forEach(function(r) { routes.push(r); }); return router.map(routes()).buildNavigationModel(); }).then(function () { setupRouter(); return boot(); }).fail(function(e) { return logger.log(e.message,null,null,true); }); } function setupRouter() { return router.mapUnknownRoutes('dashboard/index', 'not-found'); } function boot() { return router.activate(); } function deactivate() { return true; } });
kmlewis/_old_stuff
ReferralTracker/ReferralReboot/App/shell.js
JavaScript
mit
1,512
Nikos Chrisochoides Nikos Chrisochoides Nikos Chrisochoides Nikos Chrisochoides Nikos Chrisochoides Nikos P. Chrisochoides Nikos Chrisochoides Nikos P. Chrisochoides Nikos Chrisochoides Nikos P. Chrisochoides
ML-SWAT/Web2KnowledgeBase
course-cotrain-data/inlinks/non-course/http:^^www.cs.cornell.edu^Info^People^nikosc^nikosc.html
HTML
mit
217
--- layout: page title: Clements Trade Award Ceremony date: 2016-05-24 author: Carl Hicks tags: weekly links, java status: published summary: Donec ornare mi eu massa fringilla eleifend. Aliquam erat. banner: images/banner/leisure-01.jpg booking: startDate: 11/30/2019 endDate: 12/03/2019 ctyhocn: MFEPRHX groupCode: CTAC published: true --- Sed suscipit dictum viverra. Aliquam ornare nulla nisi, sit amet tempus turpis tempor sed. Ut a risus ut risus imperdiet tincidunt sed sed velit. Praesent tincidunt, risus id consectetur bibendum, velit leo cursus ligula, eu condimentum lorem augue at tellus. Duis congue semper nisi sit amet pretium. Proin a ipsum libero. Nulla sollicitudin sem ut ex bibendum, vel volutpat tortor luctus. Pellentesque porttitor quis enim ut dictum. Aliquam erat volutpat. Suspendisse ut arcu congue, lacinia erat eget, fermentum odio. Proin finibus massa vel lacinia commodo. Duis viverra massa pellentesque magna sollicitudin vehicula. In placerat justo vitae ultricies pellentesque. Suspendisse purus neque, lacinia at diam eu, malesuada interdum dui. In molestie, tortor non lacinia congue, nibh lacus bibendum erat, blandit molestie metus augue non erat. Morbi suscipit maximus erat, sed finibus lacus convallis sit amet. Ut quam augue, egestas eget hendrerit eget, dapibus porta metus. * In consectetur urna et dapibus pharetra * Ut tempus augue eu neque varius iaculis * Cras dictum nisl ac nisi cursus, quis auctor nibh efficitur * Mauris dapibus urna eget cursus congue. Fusce viverra convallis varius. Proin ut ipsum eget eros cursus interdum mollis at magna. Praesent urna leo, mattis vel velit a, lobortis eleifend urna. Pellentesque ac nibh neque. Aenean ullamcorper enim vel dui lobortis sodales. Sed nec aliquam sapien. Vestibulum laoreet non diam sit amet pharetra. Nunc iaculis pulvinar felis at sollicitudin. Phasellus sed facilisis orci. Nulla purus nibh, ultrices quis semper non, tempus nec risus. Praesent facilisis hendrerit molestie. Proin interdum odio at nisl ornare commodo. Nulla facilisi. Nulla consequat luctus lacus eget accumsan. Aliquam porta nibh neque, a luctus neque semper sed.
KlishGroup/prose-pogs
pogs/M/MFEPRHX/CTAC/index.md
Markdown
mit
2,152
# We slice the array in two parts at index d, then print them # in reverse order. n, d = map(int, input().split()) A = list(map(int, input().split())) print(*(A[d:] + A[:d]))
yznpku/HackerRank
solution/practice/data-structures/arrays/array-left-rotation/solution.py
Python
mit
177
package mcjty.rftools.blocks.logic.invchecker; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import mcjty.lib.container.ContainerFactory; import mcjty.lib.container.DefaultSidedInventory; import mcjty.lib.container.InventoryHelper; import mcjty.lib.gui.widgets.ChoiceLabel; import mcjty.lib.gui.widgets.TextField; import mcjty.lib.tileentity.LogicTileEntity; import mcjty.lib.typed.TypedMap; import mcjty.lib.varia.BlockPosTools; import mcjty.lib.varia.CapabilityTools; import mcjty.lib.varia.Logging; import mcjty.rftools.RFTools; import mcjty.theoneprobe.api.IProbeHitData; import mcjty.theoneprobe.api.IProbeInfo; import mcjty.theoneprobe.api.ProbeMode; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.fml.common.Optional; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.oredict.OreDictionary; import java.util.List; import static mcjty.rftools.blocks.logic.invchecker.GuiInvChecker.META_MATCH; import static mcjty.rftools.blocks.logic.invchecker.GuiInvChecker.OREDICT_USE; public class InvCheckerTileEntity extends LogicTileEntity implements ITickable, DefaultSidedInventory { public static final String CMD_SETAMOUNT = "inv.setCounter"; public static final String CMD_SETSLOT = "inv.setSlot"; public static final String CMD_SETOREDICT = "inv.setOreDict"; public static final String CMD_SETMETA = "inv.setUseMeta"; public static final String CONTAINER_INVENTORY = "container"; public static final int SLOT_ITEMMATCH = 0; public static final ContainerFactory CONTAINER_FACTORY = new ContainerFactory(new ResourceLocation(RFTools.MODID, "gui/invchecker.gui")); private int amount = 1; private int slot = 0; private boolean oreDict = false; private boolean useMeta = false; private TIntSet set1 = null; private int checkCounter = 0; private InventoryHelper inventoryHelper = new InventoryHelper(this, CONTAINER_FACTORY, 1); @Override protected boolean needsCustomInvWrapper() { return true; } public InvCheckerTileEntity() { } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; markDirtyClient(); } public int getSlot() { return slot; } public void setSlot(int slot) { this.slot = slot; markDirtyClient(); } public boolean isOreDict() { return oreDict; } public void setOreDict(boolean oreDict) { this.oreDict = oreDict; markDirtyClient(); } public boolean isUseMeta() { return useMeta; } public void setUseMeta(boolean useMeta) { this.useMeta = useMeta; markDirtyClient(); } @Override public void setInventorySlotContents(int index, ItemStack stack) { // Clear the oredict cache set1 = null; getInventoryHelper().setInventorySlotContents(getInventoryStackLimit(), index, stack); } @Override public void update() { if (getWorld().isRemote) { return; } checkCounter--; if (checkCounter > 0) { return; } checkCounter = 10; setRedstoneState(checkOutput() ? 15 : 0); } public boolean checkOutput() { boolean newout = false; EnumFacing inputSide = getFacing(getWorld().getBlockState(getPos())).getInputSide(); BlockPos inputPos = getPos().offset(inputSide); TileEntity te = getWorld().getTileEntity(inputPos); if (InventoryHelper.isInventory(te)) { ItemStack stack = ItemStack.EMPTY; if (CapabilityTools.hasItemCapabilitySafe(te)) { IItemHandler capability = CapabilityTools.getItemCapabilitySafe(te); if (capability == null) { Block errorBlock = getWorld().getBlockState(inputPos).getBlock(); Logging.logError("Block: " + errorBlock.getLocalizedName() + " at " + BlockPosTools.toString(inputPos) + " returns null for getCapability(). Report to mod author"); } else if (slot >= 0 && slot < capability.getSlots()) { stack = capability.getStackInSlot(slot); } } else if (te instanceof IInventory) { IInventory inventory = (IInventory) te; if (slot >= 0 && slot < inventory.getSizeInventory()) { stack = inventory.getStackInSlot(slot); } } if (!stack.isEmpty()) { int nr = isItemMatching(stack); newout = nr >= amount; } } return newout; } private int isItemMatching(ItemStack stack) { int nr = 0; ItemStack matcher = inventoryHelper.getStackInSlot(0); if (!matcher.isEmpty()) { if (oreDict) { if (isEqualForOredict(matcher, stack)) { if ((!useMeta) || matcher.getMetadata() == stack.getMetadata()) { nr = stack.getCount(); } } } else { if (useMeta) { if (matcher.isItemEqual(stack)) { nr = stack.getCount(); } } else { if (matcher.getItem() == stack.getItem()) { nr = stack.getCount(); } } } } else { nr = stack.getCount(); } return nr; } private boolean isEqualForOredict(ItemStack s1, ItemStack s2) { if (set1 == null) { int[] oreIDs1 = OreDictionary.getOreIDs(s1); set1 = new TIntHashSet(oreIDs1); } if (set1.isEmpty()) { // The first item is not an ore. In this case we do normal equality of item return s1.getItem() == s2.getItem(); } int[] oreIDs2 = OreDictionary.getOreIDs(s2); if (oreIDs2.length == 0) { // The first is an ore but this isn't. So we cannot match. return false; } TIntSet set2 = new TIntHashSet(oreIDs2); set2.retainAll(set1); return !set2.isEmpty(); } @Override public InventoryHelper getInventoryHelper() { return inventoryHelper; } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { return false; } @Override public boolean isEmpty() { return false; } @Override public boolean isUsableByPlayer(EntityPlayer player) { return canPlayerAccess(player); } @Override public void readFromNBT(NBTTagCompound tagCompound) { super.readFromNBT(tagCompound); powerOutput = tagCompound.getBoolean("rs") ? 15 : 0; } @Override public void readRestorableFromNBT(NBTTagCompound tagCompound) { super.readRestorableFromNBT(tagCompound); readBufferFromNBT(tagCompound, inventoryHelper); amount = tagCompound.getInteger("amount"); slot = tagCompound.getInteger("slot"); oreDict = tagCompound.getBoolean("oredict"); useMeta = tagCompound.getBoolean("useMeta"); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); tagCompound.setBoolean("rs", powerOutput > 0); return tagCompound; } @Override public void writeRestorableToNBT(NBTTagCompound tagCompound) { super.writeRestorableToNBT(tagCompound); writeBufferToNBT(tagCompound, inventoryHelper); tagCompound.setInteger("amount", amount); tagCompound.setInteger("slot", slot); tagCompound.setBoolean("oredict", oreDict); tagCompound.setBoolean("useMeta", useMeta); } @Override public boolean execute(EntityPlayerMP playerMP, String command, TypedMap params) { boolean rc = super.execute(playerMP, command, params); if (rc) { return true; } if (CMD_SETMETA.equals(command)) { setUseMeta(META_MATCH.equals(params.get(ChoiceLabel.PARAM_CHOICE))); return true; } else if (CMD_SETOREDICT.equals(command)) { setOreDict(OREDICT_USE.equals(params.get(ChoiceLabel.PARAM_CHOICE))); return true; } else if (CMD_SETSLOT.equals(command)) { int slot; try { slot = Integer.parseInt(params.get(TextField.PARAM_TEXT)); } catch (NumberFormatException e) { slot = 0; } setSlot(slot); return true; } else if (CMD_SETAMOUNT.equals(command)) { int amount; try { amount = Integer.parseInt(params.get(TextField.PARAM_TEXT)); } catch (NumberFormatException e) { amount = 1; } setAmount(amount); return true; } return false; } @Override @Optional.Method(modid = "theoneprobe") public void addProbeInfo(ProbeMode mode, IProbeInfo probeInfo, EntityPlayer player, World world, IBlockState blockState, IProbeHitData data) { super.addProbeInfo(mode, probeInfo, player, world, blockState, data); boolean rc = checkOutput(); probeInfo.text(TextFormatting.GREEN + "Output: " + TextFormatting.WHITE + (rc ? "on" : "off")); } @SideOnly(Side.CLIENT) @Override @Optional.Method(modid = "waila") public void addWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { super.addWailaBody(itemStack, currenttip, accessor, config); } }
McJty/RFTools
src/main/java/mcjty/rftools/blocks/logic/invchecker/InvCheckerTileEntity.java
Java
mit
10,522
/** * @license Highmaps JS v9.3.2 (2021-11-29) * @module highcharts/modules/tilemap * @requires highcharts * @requires highcharts/modules/map * * Tilemap module * * (c) 2010-2021 Highsoft AS * * License: www.highcharts.com/license */ 'use strict'; import '../../Series/Tilemap/TilemapSeries.js';
cdnjs/cdnjs
ajax/libs/highcharts/9.3.2/es-modules/masters/modules/tilemap.src.js
JavaScript
mit
307
// author BOSS #pragma once // added by BOSS /* * Copyright 2005-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* Internal ASN1 structures and functions: not for application use */ int asn1_time_to_tm(struct tm *tm, const ASN1_TIME *d); int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d); int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d); /* ASN1 scan context structure */ struct asn1_sctx_st { /* The ASN1_ITEM associated with this field */ const ASN1_ITEM *it; /* If ASN1_TEMPLATE associated with this field */ const ASN1_TEMPLATE *tt; /* Various flags associated with field and context */ unsigned long flags; /* If SEQUENCE OF or SET OF, field index */ int skidx; /* ASN1 depth of field */ int depth; /* Structure and field name */ const char *sname, *fname; /* If a primitive type the type of underlying field */ int prim_type; /* The field value itself */ ASN1_VALUE **field; /* Callback to pass information to */ int (*scan_cb) (ASN1_SCTX *ctx); /* Context specific application data */ void *app_data; } /* ASN1_SCTX */ ; typedef struct mime_param_st MIME_PARAM; DEFINE_STACK_OF(MIME_PARAM) typedef struct mime_header_st MIME_HEADER; DEFINE_STACK_OF(MIME_HEADER) void asn1_string_embed_free(ASN1_STRING *a, int embed); int asn1_get_choice_selector(ASN1_VALUE **pval, const ASN1_ITEM *it); int asn1_set_choice_selector(ASN1_VALUE **pval, int value, const ASN1_ITEM *it); ASN1_VALUE **asn1_get_field_ptr(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); const ASN1_TEMPLATE *asn1_do_adb(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt, int nullerr); int asn1_do_lock(ASN1_VALUE **pval, int op, const ASN1_ITEM *it); void asn1_enc_init(ASN1_VALUE **pval, const ASN1_ITEM *it); void asn1_enc_free(ASN1_VALUE **pval, const ASN1_ITEM *it); int asn1_enc_restore(int *len, unsigned char **out, ASN1_VALUE **pval, const ASN1_ITEM *it); int asn1_enc_save(ASN1_VALUE **pval, const unsigned char *in, int inlen, const ASN1_ITEM *it); void asn1_item_embed_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed); void asn1_primitive_free(ASN1_VALUE **pval, const ASN1_ITEM *it, int embed); void asn1_template_free(ASN1_VALUE **pval, const ASN1_TEMPLATE *tt); ASN1_OBJECT *c2i_ASN1_OBJECT(ASN1_OBJECT **a, const unsigned char **pp, long length); int i2c_ASN1_BIT_STRING(ASN1_BIT_STRING *a, unsigned char **pp); ASN1_BIT_STRING *c2i_ASN1_BIT_STRING(ASN1_BIT_STRING **a, const unsigned char **pp, long length); int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp); ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp, long length); /* Internal functions used by x_int64.c */ int c2i_uint64_int(uint64_t *ret, int *neg, const unsigned char **pp, long len); int i2c_uint64_int(unsigned char *p, uint64_t r, int neg); ASN1_TIME *asn1_time_from_tm(ASN1_TIME *s, struct tm *ts, int type);
koobonil/Boss2D
Boss2D/addon/openssl-1.1.1a_for_boss/crypto/asn1/asn1_locl.h
C
mit
3,392
using System.Runtime.CompilerServices; #if DEBUG [assembly:InternalsVisibleTo("OpenSource.Data.HashFunction.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010085f076d56d0e4c1461db01820a06d1814c38d171cebad2714bf251a15ad82214fa3c51cd0c76e26265b4e46f96dd5ab5c9843b7406815d301bea7d7904c61c21ac54f4921b95a79443d801eeda3ffd6d32c3f458f73babb09a22d06f303dfd1afbb6e27eecffd072c8fe17c669d666b954c8a423ea9b4a9313691daf942a74b1")] #endif
brandondahler/Data.HashFunction
src/FriendAssemblies.cs
C#
mit
457
--- slug: led-by-hanging name: Led By Hanging ---
lignertys/lignertys.github.io
_my_categories/led-by-hanging.md
Markdown
mit
52
/* Zepto 1.1.3 - zepto event ajax form ie detect - zeptojs.com/license */ var Zepto = (function() { var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter, document = window.document, elementDisplay = {}, classCache = {}, cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 }, fragmentRE = /^\s*<(\w+|!)[^>]*>/, singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rootNodeRE = /^(?:body|html)$/i, capitalRE = /([A-Z])/g, // special attributes that should be get/set via method calls methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ], table = document.createElement('table'), tableRow = document.createElement('tr'), containers = { 'tr': document.createElement('tbody'), 'tbody': table, 'thead': table, 'tfoot': table, 'td': tableRow, 'th': tableRow, '*': document.createElement('div') }, readyRE = /complete|loaded|interactive/, simpleSelectorRE = /^[\w-]*$/, class2type = {}, toString = class2type.toString, zepto = {}, camelize, uniq, tempParent = document.createElement('div'), propMap = { 'tabindex': 'tabIndex', 'readonly': 'readOnly', 'for': 'htmlFor', 'class': 'className', 'maxlength': 'maxLength', 'cellspacing': 'cellSpacing', 'cellpadding': 'cellPadding', 'rowspan': 'rowSpan', 'colspan': 'colSpan', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'contenteditable': 'contentEditable' }, isArray = Array.isArray || function(object){ return object instanceof Array } zepto.matches = function(element, selector) { if (!selector || !element || element.nodeType !== 1) return false var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector if (matchesSelector) return matchesSelector.call(element, selector) // fall back to performing a selector: var match, parent = element.parentNode, temp = !parent if (temp) (parent = tempParent).appendChild(element) match = ~zepto.qsa(parent, selector).indexOf(element) temp && tempParent.removeChild(element) return match } function type(obj) { return obj == null ? String(obj) : class2type[toString.call(obj)] || "object" } function isFunction(value) { return type(value) == "function" } function isWindow(obj) { return obj != null && obj == obj.window } function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE } function isObject(obj) { return type(obj) == "object" } function isPlainObject(obj) { return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype } function likeArray(obj) { return typeof obj.length == 'number' } function compact(array) { return filter.call(array, function(item){ return item != null }) } function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array } camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) } function dasherize(str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase() } uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) } function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)')) } function maybeAddPx(name, value) { return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value } function defaultDisplay(nodeName) { var element, display if (!elementDisplay[nodeName]) { element = document.createElement(nodeName) document.body.appendChild(element) display = getComputedStyle(element, '').getPropertyValue("display") element.parentNode.removeChild(element) display == "none" && (display = "block") elementDisplay[nodeName] = display } return elementDisplay[nodeName] } function children(element) { return 'children' in element ? slice.call(element.children) : $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node }) } // `$.zepto.fragment` takes a html string and an optional tag name // to generate DOM nodes nodes from the given html string. // The generated DOM nodes are returned as an array. // This function can be overriden in plugins for example to make // it compatible with browsers that don't support the DOM fully. zepto.fragment = function(html, name, properties) { var dom, nodes, container // A special case optimization for a single tag if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) if (!dom) { if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>") if (name === undefined) name = fragmentRE.test(html) && RegExp.$1 if (!(name in containers)) name = '*' container = containers[name] container.innerHTML = '' + html dom = $.each(slice.call(container.childNodes), function(){ container.removeChild(this) }) } if (isPlainObject(properties)) { nodes = $(dom) $.each(properties, function(key, value) { if (methodAttributes.indexOf(key) > -1) nodes[key](value) else nodes.attr(key, value) }) } return dom } // `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. Note that `__proto__` is not supported on Internet // Explorer. This method can be overriden in plugins. zepto.Z = function(dom, selector) { dom = dom || [] dom.__proto__ = $.fn dom.selector = selector || '' return dom } // `$.zepto.isZ` should return `true` if the given object is a Zepto // collection. This method can be overriden in plugins. zepto.isZ = function(object) { return object instanceof zepto.Z } // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and // takes a CSS selector and an optional context (and handles various // special cases). // This method can be overriden in plugins. zepto.init = function(selector, context) { var dom // If nothing given, return an empty Zepto collection if (!selector) return zepto.Z() // Optimize for string selectors else if (typeof selector == 'string') { selector = selector.trim() // If it's a html fragment, create nodes from it // Note: In both Chrome 21 and Firefox 15, DOM error 12 // is thrown if the fragment doesn't begin with < if (selector[0] == '<' && fragmentRE.test(selector)) dom = zepto.fragment(selector, RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // If it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // If a function is given, call it when the DOM is ready else if (isFunction(selector)) return $(document).ready(selector) // If a Zepto collection is given, just return it else if (zepto.isZ(selector)) return selector else { // normalize array if an array of nodes is given if (isArray(selector)) dom = compact(selector) // Wrap DOM nodes. else if (isObject(selector)) dom = [selector], selector = null // If it's a html fragment, create nodes from it else if (fragmentRE.test(selector)) dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // And last but no least, if it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // create a new Zepto collection from the nodes found return zepto.Z(dom, selector) } // `$` will be the base `Zepto` object. When calling this // function just call `$.zepto.init, which makes the implementation // details of selecting nodes and creating Zepto collections // patchable in plugins. $ = function(selector, context){ return zepto.init(selector, context) } function extend(target, source, deep) { for (key in source) if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) target[key] = {} if (isArray(source[key]) && !isArray(target[key])) target[key] = [] extend(target[key], source[key], deep) } else if (source[key] !== undefined) target[key] = source[key] } // Copy all but undefined properties from one or more // objects to the `target` object. $.extend = function(target){ var deep, args = slice.call(arguments, 1) if (typeof target == 'boolean') { deep = target target = args.shift() } args.forEach(function(arg){ extend(target, arg, deep) }) return target } // `$.zepto.qsa` is Zepto's CSS selector implementation which // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`. // This method can be overriden in plugins. zepto.qsa = function(element, selector){ var found, maybeID = selector[0] == '#', maybeClass = !maybeID && selector[0] == '.', nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked isSimple = simpleSelectorRE.test(nameOnly) return (isDocument(element) && isSimple && maybeID) ? ( (found = element.getElementById(nameOnly)) ? [found] : [] ) : (element.nodeType !== 1 && element.nodeType !== 9) ? [] : slice.call( isSimple && !maybeID ? maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class element.getElementsByTagName(selector) : // Or a tag element.querySelectorAll(selector) // Or it's not simple, and we need to query all ) } function filtered(nodes, selector) { return selector == null ? $(nodes) : $(nodes).filter(selector) } $.contains = function(parent, node) { return parent !== node && parent.contains(node) } function funcArg(context, arg, idx, payload) { return isFunction(arg) ? arg.call(context, idx, payload) : arg } function setAttribute(node, name, value) { value == null ? node.removeAttribute(name) : node.setAttribute(name, value) } // access className property while respecting SVGAnimatedString function className(node, value){ var klass = node.className, svg = klass && klass.baseVal !== undefined if (value === undefined) return svg ? klass.baseVal : klass svg ? (klass.baseVal = value) : (node.className = value) } // "true" => true // "false" => false // "null" => null // "42" => 42 // "42.5" => 42.5 // "08" => "08" // JSON => parse if valid // String => self function deserializeValue(value) { var num try { return value ? value == "true" || ( value == "false" ? false : value == "null" ? null : !/^0/.test(value) && !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value ) : value } catch(e) { return value } } $.type = type $.isFunction = isFunction $.isWindow = isWindow $.isArray = isArray $.isPlainObject = isPlainObject $.isEmptyObject = function(obj) { var name for (name in obj) return false return true } $.inArray = function(elem, array, i){ return emptyArray.indexOf.call(array, elem, i) } $.camelCase = camelize $.trim = function(str) { return str == null ? "" : String.prototype.trim.call(str) } // plugin compatibility $.uuid = 0 $.support = { } $.expr = { } $.map = function(elements, callback){ var value, values = [], i, key if (likeArray(elements)) for (i = 0; i < elements.length; i++) { value = callback(elements[i], i) if (value != null) values.push(value) } else for (key in elements) { value = callback(elements[key], key) if (value != null) values.push(value) } return flatten(values) } $.each = function(elements, callback){ var i, key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) if (callback.call(elements[i], i, elements[i]) === false) return elements } else { for (key in elements) if (callback.call(elements[key], key, elements[key]) === false) return elements } return elements } $.grep = function(elements, callback){ return filter.call(elements, callback) } if (window.JSON) $.parseJSON = JSON.parse // Populate the class2type map $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase() }) // Define methods that will be available on all // Zepto collections $.fn = { // Because a collection acts like an array // copy over these useful array functions. forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, sort: emptyArray.sort, indexOf: emptyArray.indexOf, concat: emptyArray.concat, // `map` and `slice` in the jQuery API work differently // from their array counterparts map: function(fn){ return $($.map(this, function(el, i){ return fn.call(el, i, el) })) }, slice: function(){ return $(slice.apply(this, arguments)) }, ready: function(callback){ // need to check if document.body exists for IE as that browser reports // document ready when it hasn't yet created the body element if (readyRE.test(document.readyState) && document.body) callback($) else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false) return this }, get: function(idx){ return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length] }, toArray: function(){ return this.get() }, size: function(){ return this.length }, remove: function(){ return this.each(function(){ if (this.parentNode != null) this.parentNode.removeChild(this) }) }, each: function(callback){ emptyArray.every.call(this, function(el, idx){ return callback.call(el, idx, el) !== false }) return this }, filter: function(selector){ if (isFunction(selector)) return this.not(this.not(selector)) return $(filter.call(this, function(element){ return zepto.matches(element, selector) })) }, add: function(selector,context){ return $(uniq(this.concat($(selector,context)))) }, is: function(selector){ return this.length > 0 && zepto.matches(this[0], selector) }, not: function(selector){ var nodes=[] if (isFunction(selector) && selector.call !== undefined) this.each(function(idx){ if (!selector.call(this,idx)) nodes.push(this) }) else { var excludes = typeof selector == 'string' ? this.filter(selector) : (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector) this.forEach(function(el){ if (excludes.indexOf(el) < 0) nodes.push(el) }) } return $(nodes) }, has: function(selector){ return this.filter(function(){ return isObject(selector) ? $.contains(this, selector) : $(this).find(selector).size() }) }, eq: function(idx){ return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1) }, first: function(){ var el = this[0] return el && !isObject(el) ? el : $(el) }, last: function(){ var el = this[this.length - 1] return el && !isObject(el) ? el : $(el) }, find: function(selector){ var result, $this = this if (typeof selector == 'object') result = $(selector).filter(function(){ var node = this return emptyArray.some.call($this, function(parent){ return $.contains(parent, node) }) }) else if (this.length == 1) result = $(zepto.qsa(this[0], selector)) else result = this.map(function(){ return zepto.qsa(this, selector) }) return result }, closest: function(selector, context){ var node = this[0], collection = false if (typeof selector == 'object') collection = $(selector) while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector))) node = node !== context && !isDocument(node) && node.parentNode return $(node) }, parents: function(selector){ var ancestors = [], nodes = this while (nodes.length > 0) nodes = $.map(nodes, function(node){ if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) { ancestors.push(node) return node } }) return filtered(ancestors, selector) }, parent: function(selector){ return filtered(uniq(this.pluck('parentNode')), selector) }, children: function(selector){ return filtered(this.map(function(){ return children(this) }), selector) }, contents: function() { return this.map(function() { return slice.call(this.childNodes) }) }, siblings: function(selector){ return filtered(this.map(function(i, el){ return filter.call(children(el.parentNode), function(child){ return child!==el }) }), selector) }, empty: function(){ return this.each(function(){ this.innerHTML = '' }) }, // `pluck` is borrowed from Prototype.js pluck: function(property){ return $.map(this, function(el){ return el[property] }) }, show: function(){ return this.each(function(){ this.style.display == "none" && (this.style.display = '') if (getComputedStyle(this, '').getPropertyValue("display") == "none") this.style.display = defaultDisplay(this.nodeName) }) }, replaceWith: function(newContent){ return this.before(newContent).remove() }, wrap: function(structure){ var func = isFunction(structure) if (this[0] && !func) var dom = $(structure).get(0), clone = dom.parentNode || this.length > 1 return this.each(function(index){ $(this).wrapAll( func ? structure.call(this, index) : clone ? dom.cloneNode(true) : dom ) }) }, wrapAll: function(structure){ if (this[0]) { $(this[0]).before(structure = $(structure)) var children // drill down to the inmost element while ((children = structure.children()).length) structure = children.first() $(structure).append(this) } return this }, wrapInner: function(structure){ var func = isFunction(structure) return this.each(function(index){ var self = $(this), contents = self.contents(), dom = func ? structure.call(this, index) : structure contents.length ? contents.wrapAll(dom) : self.append(dom) }) }, unwrap: function(){ this.parent().each(function(){ $(this).replaceWith($(this).children()) }) return this }, clone: function(){ return this.map(function(){ return this.cloneNode(true) }) }, hide: function(){ return this.css("display", "none") }, toggle: function(setting){ return this.each(function(){ var el = $(this) ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide() }) }, prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') }, next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') }, html: function(html){ return arguments.length === 0 ? (this.length > 0 ? this[0].innerHTML : null) : this.each(function(idx){ var originHtml = this.innerHTML $(this).empty().append( funcArg(this, html, idx, originHtml) ) }) }, text: function(text){ return arguments.length === 0 ? (this.length > 0 ? this[0].textContent : null) : this.each(function(){ this.textContent = (text === undefined) ? '' : ''+text }) }, attr: function(name, value){ var result return (typeof name == 'string' && value === undefined) ? (this.length == 0 || this[0].nodeType !== 1 ? undefined : (name == 'value' && this[0].nodeName == 'INPUT') ? this.val() : (!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result ) : this.each(function(idx){ if (this.nodeType !== 1) return if (isObject(name)) for (key in name) setAttribute(this, key, name[key]) else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name))) }) }, removeAttr: function(name){ return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) }) }, prop: function(name, value){ name = propMap[name] || name return (value === undefined) ? (this[0] && this[0][name]) : this.each(function(idx){ this[name] = funcArg(this, value, idx, this[name]) }) }, data: function(name, value){ var data = this.attr('data-' + name.replace(capitalRE, '-$1').toLowerCase(), value) return data !== null ? deserializeValue(data) : undefined }, val: function(value){ return arguments.length === 0 ? (this[0] && (this[0].multiple ? $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') : this[0].value) ) : this.each(function(idx){ this.value = funcArg(this, value, idx, this.value) }) }, offset: function(coordinates){ if (coordinates) return this.each(function(index){ var $this = $(this), coords = funcArg(this, coordinates, index, $this.offset()), parentOffset = $this.offsetParent().offset(), props = { top: coords.top - parentOffset.top, left: coords.left - parentOffset.left } if ($this.css('position') == 'static') props['position'] = 'relative' $this.css(props) }) if (this.length==0) return null var obj = this[0].getBoundingClientRect() return { left: obj.left + window.pageXOffset, top: obj.top + window.pageYOffset, width: Math.round(obj.width), height: Math.round(obj.height) } }, css: function(property, value){ if (arguments.length < 2) { var element = this[0], computedStyle = getComputedStyle(element, '') if(!element) return if (typeof property == 'string') return element.style[camelize(property)] || computedStyle.getPropertyValue(property) else if (isArray(property)) { var props = {} $.each(isArray(property) ? property: [property], function(_, prop){ props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop)) }) return props } } var css = '' if (type(property) == 'string') { if (!value && value !== 0) this.each(function(){ this.style.removeProperty(dasherize(property)) }) else css = dasherize(property) + ":" + maybeAddPx(property, value) } else { for (key in property) if (!property[key] && property[key] !== 0) this.each(function(){ this.style.removeProperty(dasherize(key)) }) else css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';' } return this.each(function(){ this.style.cssText += ';' + css }) }, index: function(element){ return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0]) }, hasClass: function(name){ if (!name) return false return emptyArray.some.call(this, function(el){ return this.test(className(el)) }, classRE(name)) }, addClass: function(name){ if (!name) return this return this.each(function(idx){ classList = [] var cls = className(this), newName = funcArg(this, name, idx, cls) newName.split(/\s+/g).forEach(function(klass){ if (!$(this).hasClass(klass)) classList.push(klass) }, this) classList.length && className(this, cls + (cls ? " " : "") + classList.join(" ")) }) }, removeClass: function(name){ return this.each(function(idx){ if (name === undefined) return className(this, '') classList = className(this) funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){ classList = classList.replace(classRE(klass), " ") }) className(this, classList.trim()) }) }, toggleClass: function(name, when){ if (!name) return this return this.each(function(idx){ var $this = $(this), names = funcArg(this, name, idx, className(this)) names.split(/\s+/g).forEach(function(klass){ (when === undefined ? !$this.hasClass(klass) : when) ? $this.addClass(klass) : $this.removeClass(klass) }) }) }, scrollTop: function(value){ if (!this.length) return var hasScrollTop = 'scrollTop' in this[0] if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset return this.each(hasScrollTop ? function(){ this.scrollTop = value } : function(){ this.scrollTo(this.scrollX, value) }) }, scrollLeft: function(value){ if (!this.length) return var hasScrollLeft = 'scrollLeft' in this[0] if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset return this.each(hasScrollLeft ? function(){ this.scrollLeft = value } : function(){ this.scrollTo(value, this.scrollY) }) }, position: function() { if (!this.length) return var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( $(elem).css('margin-top') ) || 0 offset.left -= parseFloat( $(elem).css('margin-left') ) || 0 // Add offsetParent borders parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0 parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0 // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } }, offsetParent: function() { return this.map(function(){ var parent = this.offsetParent || document.body while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static") parent = parent.offsetParent return parent }) } } // for now $.fn.detach = $.fn.remove // Generate the `width` and `height` functions ;['width', 'height'].forEach(function(dimension){ var dimensionProperty = dimension.replace(/./, function(m){ return m[0].toUpperCase() }) $.fn[dimension] = function(value){ var offset, el = this[0] if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] : isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : (offset = this.offset()) && offset[dimension] else return this.each(function(idx){ el = $(this) el.css(dimension, funcArg(this, value, idx, el[dimension]())) }) } }) function traverseNode(node, fun) { fun(node) for (var key in node.childNodes) traverseNode(node.childNodes[key], fun) } // Generate the `after`, `prepend`, `before`, `append`, // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods. adjacencyOperators.forEach(function(operator, operatorIndex) { var inside = operatorIndex % 2 //=> prepend, append $.fn[operator] = function(){ // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings var argType, nodes = $.map(arguments, function(arg) { argType = type(arg) return argType == "object" || argType == "array" || arg == null ? arg : zepto.fragment(arg) }), parent, copyByClone = this.length > 1 if (nodes.length < 1) return this return this.each(function(_, target){ parent = inside ? target : target.parentNode // convert all methods to a "before" operation target = operatorIndex == 0 ? target.nextSibling : operatorIndex == 1 ? target.firstChild : operatorIndex == 2 ? target : null nodes.forEach(function(node){ if (copyByClone) node = node.cloneNode(true) else if (!parent) return $(node).remove() traverseNode(parent.insertBefore(node, target), function(el){ if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' && (!el.type || el.type === 'text/javascript') && !el.src) window['eval'].call(window, el.innerHTML) }) }) }) } // after => insertAfter // prepend => prependTo // before => insertBefore // append => appendTo $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){ $(html)[operator](this) return this } }) zepto.Z.prototype = $.fn // Export internal API functions in the `$.zepto` namespace zepto.uniq = uniq zepto.deserializeValue = deserializeValue $.zepto = zepto return $ })() window.Zepto = Zepto window.$ === undefined && (window.$ = Zepto) ;(function($){ var _zid = 1, undefined, slice = Array.prototype.slice, isFunction = $.isFunction, isString = function(obj){ return typeof obj == 'string' }, handlers = {}, specialEvents={}, focusinSupported = 'onfocusin' in window, focus = { focus: 'focusin', blur: 'focusout' }, hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' } specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents' function zid(element) { return element._zid || (element._zid = _zid++) } function findHandlers(element, event, fn, selector) { event = parse(event) if (event.ns) var matcher = matcherFor(event.ns) return (handlers[zid(element)] || []).filter(function(handler) { return handler && (!event.e || handler.e == event.e) && (!event.ns || matcher.test(handler.ns)) && (!fn || zid(handler.fn) === zid(fn)) && (!selector || handler.sel == selector) }) } function parse(event) { var parts = ('' + event).split('.') return {e: parts[0], ns: parts.slice(1).sort().join(' ')} } function matcherFor(ns) { return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)') } function eventCapture(handler, captureSetting) { return handler.del && (!focusinSupported && (handler.e in focus)) || !!captureSetting } function realEvent(type) { return hover[type] || (focusinSupported && focus[type]) || type } function add(element, events, fn, data, selector, delegator, capture){ var id = zid(element), set = (handlers[id] || (handlers[id] = [])) events.split(/\s/).forEach(function(event){ if (event == 'ready') return $(document).ready(fn) var handler = parse(event) handler.fn = fn handler.sel = selector // emulate mouseenter, mouseleave if (handler.e in hover) fn = function(e){ var related = e.relatedTarget if (!related || (related !== this && !$.contains(this, related))) return handler.fn.apply(this, arguments) } handler.del = delegator var callback = delegator || fn handler.proxy = function(e){ e = compatible(e) if (e.isImmediatePropagationStopped()) return e.data = data var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args)) if (result === false) e.preventDefault(), e.stopPropagation() return result } handler.i = set.length set.push(handler) if ('addEventListener' in element) element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) } function remove(element, events, fn, selector, capture){ var id = zid(element) ;(events || '').split(/\s/).forEach(function(event){ findHandlers(element, event, fn, selector).forEach(function(handler){ delete handlers[id][handler.i] if ('removeEventListener' in element) element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) }) } $.event = { add: add, remove: remove } $.proxy = function(fn, context) { if (isFunction(fn)) { var proxyFn = function(){ return fn.apply(context, arguments) } proxyFn._zid = zid(fn) return proxyFn } else if (isString(context)) { return $.proxy(fn[context], fn) } else { throw new TypeError("expected function") } } $.fn.bind = function(event, data, callback){ return this.on(event, data, callback) } $.fn.unbind = function(event, callback){ return this.off(event, callback) } $.fn.one = function(event, selector, data, callback){ return this.on(event, selector, data, callback, 1) } var returnTrue = function(){return true}, returnFalse = function(){return false}, ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/, eventMethods = { preventDefault: 'isDefaultPrevented', stopImmediatePropagation: 'isImmediatePropagationStopped', stopPropagation: 'isPropagationStopped' } function compatible(event, source) { if (source || !event.isDefaultPrevented) { source || (source = event) $.each(eventMethods, function(name, predicate) { var sourceMethod = source[name] event[name] = function(){ this[predicate] = returnTrue return sourceMethod && sourceMethod.apply(source, arguments) } event[predicate] = returnFalse }) if (source.defaultPrevented !== undefined ? source.defaultPrevented : 'returnValue' in source ? source.returnValue === false : source.getPreventDefault && source.getPreventDefault()) event.isDefaultPrevented = returnTrue } return event } function createProxy(event) { var key, proxy = { originalEvent: event } for (key in event) if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key] return compatible(proxy, event) } $.fn.delegate = function(selector, event, callback){ return this.on(event, selector, callback) } $.fn.undelegate = function(selector, event, callback){ return this.off(event, selector, callback) } $.fn.live = function(event, callback){ $(document.body).delegate(this.selector, event, callback) return this } $.fn.die = function(event, callback){ $(document.body).undelegate(this.selector, event, callback) return this } $.fn.on = function(event, selector, data, callback, one){ var autoRemove, delegator, $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.on(type, selector, data, fn, one) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = data, data = selector, selector = undefined if (isFunction(data) || data === false) callback = data, data = undefined if (callback === false) callback = returnFalse return $this.each(function(_, element){ if (one) autoRemove = function(e){ remove(element, e.type, callback) return callback.apply(this, arguments) } if (selector) delegator = function(e){ var evt, match = $(e.target).closest(selector, element).get(0) if (match && match !== element) { evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element}) return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1))) } } add(element, event, callback, data, selector, delegator || autoRemove) }) } $.fn.off = function(event, selector, callback){ var $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.off(type, selector, fn) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = selector, selector = undefined if (callback === false) callback = returnFalse return $this.each(function(){ remove(this, event, callback, selector) }) } $.fn.trigger = function(event, args){ event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event) event._args = args return this.each(function(){ // items in the collection might not be DOM elements if('dispatchEvent' in this) this.dispatchEvent(event) else $(this).triggerHandler(event, args) }) } // triggers event handlers on current element just as if an event occurred, // doesn't trigger an actual event, doesn't bubble $.fn.triggerHandler = function(event, args){ var e, result this.each(function(i, element){ e = createProxy(isString(event) ? $.Event(event) : event) e._args = args e.target = element $.each(findHandlers(element, event.type || event), function(i, handler){ result = handler.proxy(e) if (e.isImmediatePropagationStopped()) return false }) }) return result } // shortcut methods for `.bind(event, fn)` for each event type ;('focusin focusout load resize scroll unload click dblclick '+ 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+ 'change select keydown keypress keyup error').split(' ').forEach(function(event) { $.fn[event] = function(callback) { return callback ? this.bind(event, callback) : this.trigger(event) } }) ;['focus', 'blur'].forEach(function(name) { $.fn[name] = function(callback) { if (callback) this.bind(name, callback) else this.each(function(){ try { this[name]() } catch(e) {} }) return this } }) $.Event = function(type, props) { if (!isString(type)) props = type, type = props.type var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name]) event.initEvent(type, bubbles, true) return compatible(event) } })(Zepto) ;(function($){ var jsonpID = 0, document = window.document, key, name, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, scriptTypeRE = /^(?:text|application)\/javascript/i, xmlTypeRE = /^(?:text|application)\/xml/i, jsonType = 'application/json', htmlType = 'text/html', blankRE = /^\s*$/ // trigger a custom event and return false if it was cancelled function triggerAndReturn(context, eventName, data) { var event = $.Event(eventName) $(context).trigger(event, data) return !event.isDefaultPrevented() } // trigger an Ajax "global" event function triggerGlobal(settings, context, eventName, data) { if (settings.global) return triggerAndReturn(context || document, eventName, data) } // Number of active Ajax requests $.active = 0 function ajaxStart(settings) { if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart') } function ajaxStop(settings) { if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop') } // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable function ajaxBeforeSend(xhr, settings) { var context = settings.context if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false) return false triggerGlobal(settings, context, 'ajaxSend', [xhr, settings]) } function ajaxSuccess(data, xhr, settings, deferred) { var context = settings.context, status = 'success' settings.success.call(context, data, status, xhr) if (deferred) deferred.resolveWith(context, [data, status, xhr]) triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data]) ajaxComplete(status, xhr, settings) } // type: "timeout", "error", "abort", "parsererror" function ajaxError(error, type, xhr, settings, deferred) { var context = settings.context settings.error.call(context, xhr, type, error) if (deferred) deferred.rejectWith(context, [xhr, type, error]) triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type]) ajaxComplete(type, xhr, settings) } // status: "success", "notmodified", "error", "timeout", "abort", "parsererror" function ajaxComplete(status, xhr, settings) { var context = settings.context settings.complete.call(context, xhr, status) triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings]) ajaxStop(settings) } // Empty function, used as default callback function empty() {} $.ajaxJSONP = function(options, deferred){ if (!('type' in options)) return $.ajax(options) var _callbackName = options.jsonpCallback, callbackName = ($.isFunction(_callbackName) ? _callbackName() : _callbackName) || ('jsonp' + (++jsonpID)), script = document.createElement('script'), originalCallback = window[callbackName], responseData, abort = function(errorType) { $(script).triggerHandler('error', errorType || 'abort') }, xhr = { abort: abort }, abortTimeout if (deferred) deferred.promise(xhr) $(script).on('load error', function(e, errorType){ clearTimeout(abortTimeout) $(script).off().remove() if (e.type == 'error' || !responseData) { ajaxError(null, errorType || 'error', xhr, options, deferred) } else { ajaxSuccess(responseData[0], xhr, options, deferred) } window[callbackName] = originalCallback if (responseData && $.isFunction(originalCallback)) originalCallback(responseData[0]) originalCallback = responseData = undefined }) if (ajaxBeforeSend(xhr, options) === false) { abort('abort') return xhr } window[callbackName] = function(){ responseData = arguments } script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName) document.head.appendChild(script) if (options.timeout > 0) abortTimeout = setTimeout(function(){ abort('timeout') }, options.timeout) return xhr } $.ajaxSettings = { // Default type of request type: 'GET', // Callback that is executed before request beforeSend: empty, // Callback that is executed if the request succeeds success: empty, // Callback that is executed the the server drops error error: empty, // Callback that is executed on request complete (both: error and success) complete: empty, // The context for the callbacks context: null, // Whether to trigger "global" Ajax events global: true, // Transport xhr: function () { return new window.XMLHttpRequest() }, // MIME types mapping // IIS returns Javascript as "application/x-javascript" accepts: { script: 'text/javascript, application/javascript, application/x-javascript', json: jsonType, xml: 'application/xml, text/xml', html: htmlType, text: 'text/plain' }, // Whether the request is to another domain crossDomain: false, // Default timeout timeout: 0, // Whether data should be serialized to string processData: true, // Whether the browser should be allowed to cache GET responses cache: true } function mimeToDataType(mime) { if (mime) mime = mime.split(';', 2)[0] return mime && ( mime == htmlType ? 'html' : mime == jsonType ? 'json' : scriptTypeRE.test(mime) ? 'script' : xmlTypeRE.test(mime) && 'xml' ) || 'text' } function appendQuery(url, query) { if (query == '') return url return (url + '&' + query).replace(/[&?]{1,2}/, '?') } // serialize payload and append it to the URL for GET requests function serializeData(options) { if (options.processData && options.data && $.type(options.data) != "string") options.data = $.param(options.data, options.traditional) if (options.data && (!options.type || options.type.toUpperCase() == 'GET')) options.url = appendQuery(options.url, options.data), options.data = undefined } $.ajax = function(options){ var settings = $.extend({}, options || {}), deferred = $.Deferred && $.Deferred() for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key] ajaxStart(settings) if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) && RegExp.$2 != window.location.host if (!settings.url) settings.url = window.location.toString() serializeData(settings) if (settings.cache === false) settings.url = appendQuery(settings.url, '_=' + Date.now()) var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url) if (dataType == 'jsonp' || hasPlaceholder) { if (!hasPlaceholder) settings.url = appendQuery(settings.url, settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?') return $.ajaxJSONP(settings, deferred) } var mime = settings.accepts[dataType], headers = { }, setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] }, protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol, xhr = settings.xhr(), nativeSetHeader = xhr.setRequestHeader, abortTimeout if (deferred) deferred.promise(xhr) if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest') setHeader('Accept', mime || '*/*') if (mime = settings.mimeType || mime) { if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0] xhr.overrideMimeType && xhr.overrideMimeType(mime) } if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET')) setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded') if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name]) xhr.setRequestHeader = setHeader xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { xhr.onreadystatechange = empty clearTimeout(abortTimeout) var result, error = false if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) { dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type')) result = xhr.responseText try { // http://perfectionkills.com/global-eval-what-are-the-options/ if (dataType == 'script') (1,eval)(result) else if (dataType == 'xml') result = xhr.responseXML else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result) } catch (e) { error = e } if (error) ajaxError(error, 'parsererror', xhr, settings, deferred) else ajaxSuccess(result, xhr, settings, deferred) } else { ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred) } } } if (ajaxBeforeSend(xhr, settings) === false) { xhr.abort() ajaxError(null, 'abort', xhr, settings, deferred) return xhr } if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name] var async = 'async' in settings ? settings.async : true xhr.open(settings.type, settings.url, async, settings.username, settings.password) for (name in headers) nativeSetHeader.apply(xhr, headers[name]) if (settings.timeout > 0) abortTimeout = setTimeout(function(){ xhr.onreadystatechange = empty xhr.abort() ajaxError(null, 'timeout', xhr, settings, deferred) }, settings.timeout) // avoid sending empty string (#319) xhr.send(settings.data ? settings.data : null) return xhr } // handle optional data/success arguments function parseArguments(url, data, success, dataType) { if ($.isFunction(data)) dataType = success, success = data, data = undefined if (!$.isFunction(success)) dataType = success, success = undefined return { url: url , data: data , success: success , dataType: dataType } } $.get = function(/* url, data, success, dataType */){ return $.ajax(parseArguments.apply(null, arguments)) } $.post = function(/* url, data, success, dataType */){ var options = parseArguments.apply(null, arguments) options.type = 'POST' return $.ajax(options) } $.getJSON = function(/* url, data, success */){ var options = parseArguments.apply(null, arguments) options.dataType = 'json' return $.ajax(options) } $.fn.load = function(url, data, success){ if (!this.length) return this var self = this, parts = url.split(/\s/), selector, options = parseArguments(url, data, success), callback = options.success if (parts.length > 1) options.url = parts[0], selector = parts[1] options.success = function(response){ self.html(selector ? $('<div>').html(response.replace(rscript, "")).find(selector) : response) callback && callback.apply(self, arguments) } $.ajax(options) return this } var escape = encodeURIComponent function serialize(params, obj, traditional, scope){ var type, array = $.isArray(obj), hash = $.isPlainObject(obj) $.each(obj, function(key, value) { type = $.type(value) if (scope) key = traditional ? scope : scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']' // handle data in serializeArray() format if (!scope && array) params.add(value.name, value.value) // recurse into nested objects else if (type == "array" || (!traditional && type == "object")) serialize(params, value, traditional, key) else params.add(key, value) }) } $.param = function(obj, traditional){ var params = [] params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) } serialize(params, obj, traditional) return params.join('&').replace(/%20/g, '+') } })(Zepto) ;(function($){ $.fn.serializeArray = function() { var result = [], el $([].slice.call(this.get(0).elements)).each(function(){ el = $(this) var type = el.attr('type') if (this.nodeName.toLowerCase() != 'fieldset' && !this.disabled && type != 'submit' && type != 'reset' && type != 'button' && ((type != 'radio' && type != 'checkbox') || this.checked)) result.push({ name: el.attr('name'), value: el.val() }) }) return result } $.fn.serialize = function(){ var result = [] this.serializeArray().forEach(function(elm){ result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value)) }) return result.join('&') } $.fn.submit = function(callback) { if (callback) this.bind('submit', callback) else if (this.length) { var event = $.Event('submit') this.eq(0).trigger(event) if (!event.isDefaultPrevented()) this.get(0).submit() } return this } })(Zepto) ;(function($){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })(Zepto) ;(function($){ function detect(ua){ var os = this.os = {}, browser = this.browser = {}, webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/), android = ua.match(/(Android);?[\s\/]+([\d.]+)?/), osx = !!ua.match(/\(Macintosh\; Intel /), ipad = ua.match(/(iPad).*OS\s([\d_]+)/), ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/), iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/), webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/), touchpad = webos && ua.match(/TouchPad/), kindle = ua.match(/Kindle\/([\d.]+)/), silk = ua.match(/Silk\/([\d._]+)/), blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/), bb10 = ua.match(/(BB10).*Version\/([\d.]+)/), rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/), playbook = ua.match(/PlayBook/), chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/), firefox = ua.match(/Firefox\/([\d.]+)/), ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/), webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/), safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/) // Todo: clean this up with a better OS/browser seperation: // - discern (more) between multiple browsers on android // - decide if kindle fire in silk mode is android or not // - Firefox on Android doesn't specify the Android version // - possibly devide in os, device and browser hashes if (browser.webkit = !!webkit) browser.version = webkit[1] if (android) os.android = true, os.version = android[2] if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.') if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.') if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null if (webos) os.webos = true, os.version = webos[2] if (touchpad) os.touchpad = true if (blackberry) os.blackberry = true, os.version = blackberry[2] if (bb10) os.bb10 = true, os.version = bb10[2] if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2] if (playbook) browser.playbook = true if (kindle) os.kindle = true, os.version = kindle[1] if (silk) browser.silk = true, browser.version = silk[1] if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true if (chrome) browser.chrome = true, browser.version = chrome[1] if (firefox) browser.firefox = true, browser.version = firefox[1] if (ie) browser.ie = true, browser.version = ie[1] if (safari && (osx || os.ios)) {browser.safari = true; if (osx) browser.version = safari[1]} if (webview) browser.webview = true os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) || (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/))) os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 || (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) || (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/)))) } detect.call($, navigator.userAgent) // make available to unit tests $.__detect = detect })(Zepto)
mamboer/3gz
src/js/libs/zepto/zepto.js
JavaScript
mit
57,961
var mailer = require('nodemailer'); var smtpTransport = require('nodemailer-smtp-transport'); var config = require('../config'); var util = require('util'); var transport = mailer.createTransport(smtpTransport(config.mail_opts)); //域名domain没有的时留空,devMode下读取host var SITE_ROOT_URL = 'http://' + ((config.domain && !config.devMode)?config.domain:(config.host+":"+config.port)); /** * Send an email * @param {Object} data 邮件对象 */ var sendMail = function (data) { //need_active_mail=false不发送邮件 if (!config.need_active_mail) { return; } // 遍历邮件数组,发送每一封邮件,如果有发送失败的,就再压入数组,同时触发mailEvent事件 transport.sendMail(data, function (err) { if (err) { // 写为日志 console.log(err); } }); }; exports.sendMail = sendMail; /** * 发送激活通知邮件 * @param {String} who 接收人的邮件地址 * @param {String} token 重置用的token字符串 * @param {String} name 接收人的用户名 */ exports.sendActiveMail = function (who, token, name) { var from = util.format('%s <%s>', config.name, config.mail_opts.auth.user); var to = who; var subject = config.name + '帐号激活'; var html = '<p>您好:' + name + '</p>' + '<p>我们收到您在' + config.name + '的注册信息,请点击下面的链接来激活帐户:</p>' + '<a href = "' + SITE_ROOT_URL + '/active_account?key=' + token + '&name=' + name + '">激活链接</a>' + '<p>若您没有在' + config.name + '填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' + '<p>' + config.name + ' 谨上。</p>'; exports.sendMail({ from: from, to: to, subject: subject, html: html }); }; /** * 发送密码重置通知邮件 * @param {String} who 接收人的邮件地址 * @param {String} token 重置用的token字符串 * @param {String} name 接收人的用户名 */ exports.sendResetPassMail = function (who, token, name) { var from = util.format('%s <%s>', config.name, config.mail_opts.auth.user); var to = who; var subject = config.name + '密码重置'; var html = '<p>您好:' + name + '</p>' + '<p>我们收到您在' + config.name + '重置密码的请求,请在24小时内单击下面的链接来重置密码:</p>' + '<a href="' + SITE_ROOT_URL + '/reset_pass?key=' + token + '&name=' + name + '">重置密码链接</a>' + '<p>若您没有在' + config.name + '填写过注册信息,说明有人滥用了您的电子邮箱,请删除此邮件,我们对给您造成的打扰感到抱歉。</p>' + '<p>' + config.name + ' 谨上。</p>'; exports.sendMail({ from: from, to: to, subject: subject, html: html }); };
giscafer/Vue-order
src/server/common/mail.js
JavaScript
mit
2,869
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaUserMd extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m13.1 30q0 0.6-0.5 1t-1 0.4-1-0.4-0.4-1 0.4-1 1-0.4 1 0.4 0.5 1z m22.8 1.4q0 2.7-1.6 4.2t-4.3 1.5h-19.5q-2.7 0-4.4-1.5t-1.6-4.2q0-1.6 0.1-3t0.6-3 1-3 1.8-2.3 2.7-1.4q-0.5 1.2-0.5 2.7v4.6q-1.3 0.4-2.1 1.5t-0.7 2.5q0 1.8 1.2 3t3 1.3 3.1-1.3 1.2-3q0-1.4-0.8-2.5t-2-1.5v-4.6q0-1.4 0.5-2 3 2.3 6.6 2.3t6.6-2.3q0.6 0.6 0.6 2v1.5q-2.4 0-4.1 1.6t-1.7 4.1v2q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.6t1.5 0.6 1.5-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.2 0.9-2t2-0.9 2 0.9 0.8 2v2q-0.7 0.6-0.7 1.5 0 0.9 0.6 1.6t1.5 0.6 1.6-0.6 0.6-1.6q0-0.9-0.7-1.5v-2q0-1.5-0.8-2.9t-2.1-2.1q0-0.2 0-0.9t0-1.1 0-0.9-0.2-1.1-0.3-0.8q1.5 0.3 2.7 1.3t1.8 2.3 1.1 3 0.5 3 0.1 3z m-7.1-20q0 3.6-2.5 6.1t-6.1 2.5-6-2.5-2.6-6.1 2.6-6 6-2.5 6.1 2.5 2.5 6z"/></g> </IconBase> ); } }
scampersand/sonos-front
app/react-icons/fa/user-md.js
JavaScript
mit
997
#!/usr/bin/env bash brew cask install alfred # Open the app so the preference files get initialized open "$HOME/Applications/Alfred 2.app"
losted/dotfiles
osx/apps/alfred.sh
Shell
mit
141
class PlayableAction def apply_to(game_engine:) raise NotImplementedError end end
randomcodenz/canasta
app/models/playable_action.rb
Ruby
mit
90
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highmaps]] */ package com.highmaps.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>plotOptions-roc-states-hover-marker-states</code> */ @js.annotation.ScalaJSDefined class PlotOptionsRocStatesHoverMarkerStates extends com.highcharts.HighchartsGenericObject { /** * <p>The normal state of a single point marker. Currently only used * for setting animation when returning to normal state from hover.</p> * @since 6.0.0 */ val normal: js.Any = js.undefined /** * <p>The hover state for a single point marker.</p> * @since 6.0.0 */ val hover: js.Any = js.undefined /** * <p>The appearance of the point marker when selected. In order to * allow a point to be selected, set the <code>series.allowPointSelect</code> * option to true.</p> * @since 6.0.0 */ val select: js.Any = js.undefined } object PlotOptionsRocStatesHoverMarkerStates { /** * @param normal <p>The normal state of a single point marker. Currently only used. for setting animation when returning to normal state from hover.</p> * @param hover <p>The hover state for a single point marker.</p> * @param select <p>The appearance of the point marker when selected. In order to. allow a point to be selected, set the <code>series.allowPointSelect</code>. option to true.</p> */ def apply(normal: js.UndefOr[js.Any] = js.undefined, hover: js.UndefOr[js.Any] = js.undefined, select: js.UndefOr[js.Any] = js.undefined): PlotOptionsRocStatesHoverMarkerStates = { val normalOuter: js.Any = normal val hoverOuter: js.Any = hover val selectOuter: js.Any = select com.highcharts.HighchartsGenericObject.toCleanObject(new PlotOptionsRocStatesHoverMarkerStates { override val normal: js.Any = normalOuter override val hover: js.Any = hoverOuter override val select: js.Any = selectOuter }) } }
Karasiq/scalajs-highcharts
src/main/scala/com/highmaps/config/PlotOptionsRocStatesHoverMarkerStates.scala
Scala
mit
2,114
require 'test_helper' class EventsControllerTest < ActionDispatch::IntegrationTest setup do @event = events(:one) end test "should get index" do get events_url assert_response :success end test "should get new" do get new_event_url assert_response :success end test "should create event" do assert_difference('Event.count') do post events_url, params: { event: { category: @event.category, coach_name: @event.coach_name, date: @event.date, description: @event.description, location: @event.location, photo: @event.photo } } end assert_redirected_to event_url(Event.last) end test "should show event" do get event_url(@event) assert_response :success end test "should get edit" do get edit_event_url(@event) assert_response :success end test "should update event" do patch event_url(@event), params: { event: { category: @event.category, coach_name: @event.coach_name, date: @event.date, description: @event.description, location: @event.location, photo: @event.photo } } assert_redirected_to event_url(@event) end test "should destroy event" do assert_difference('Event.count', -1) do delete event_url(@event) end assert_redirected_to events_url end end
dragonator/sport-za-vsichki
test/controllers/events_controller_test.rb
Ruby
mit
1,276
require 'spec_helper' describe "admin/users/index" do before(:each) do assign(:users, users) end let(:users) do users =[ stub_model(User), stub_model(User) ] WillPaginate::Collection.create(1, 10, users.length) do |pager| pager.replace users end end it "renders a list of users" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select 'td' end end
concord-consortium/lara
spec/views/admin/users/index.html.erb_spec.rb
Ruby
mit
449
class Portal < Broadcaster def self.port 1260 end def channel Channels::Portal end end
migbar/vizu
lib/vizu/broadcasters/portal.rb
Ruby
mit
108
/// <reference path="references.ts"/> class Index { public instance; public addMarker; public addTopoJson; public addGeoJson; public addPanel; public center; public updateMarker; public updateMap; public updateFeature; public removeMarker; public resetMarker; public findMarker; public findFeature; public locate; public crossfilter = require('crossfilter'); zoom(zoom?: number): number { if (typeof zoom === 'undefined') { return this.instance.getZoom(); } else { this.instance.setZoom(zoom); } } constructor(options, cb) { var addMarker = new AddMarker(this); this.addMarker = function(marker, options) { return addMarker.addMarker(marker, options); }; var addFeature = new AddFeature(this); this.addTopoJson = function(data, options) { return addFeature.addTopoJson(data, options); }; this.addGeoJson = function(data, options) { return addFeature.addGeoJson(data, options); }; var addPanel = new AddPanel(this); this.addPanel = function(options, cb) { return addPanel.addPanel(options, cb); }; this.center = new Center().pos; this.locate = new Locate().locate; var updateMarker = new UpdateMarker(this); this.updateMarker = function(args, options) { return updateMarker.update(args, options); }; var updateMap = new UpdateMap(this); this.updateMap = function(args) { updateMap.updateMap(args) }; var updateFeature = new UpdateFeature(this); this.updateFeature = function(args, options) { return updateFeature.update(args, options); }; var removeMarker = new RemoveMarker(this); this.removeMarker = function(args) { return removeMarker.removeMarker(args) }; var resetMarker = new ResetMarker(this); this.resetMarker = function(args, options) { return resetMarker.resetMarker(args, options) }; var findMarker = new Filter(this, 'markers'); this.findMarker = function(args, options) { return findMarker.filter(args, options); }; // Unit Tests? var findFeature = new Filter(this, 'json'); this.findFeature = function(args, options) { return findFeature.filter(args, options); }; var map = new AddMap(this); map.load(options, cb); } } // Node module.exports = Index;
yagoferrer/map-tools-ts
lib/index.ts
TypeScript
mit
2,369
class KnormError extends Error { constructor(...args) { const [message] = args; const hasMessage = typeof message === 'string'; super(hasMessage ? message : undefined); if (!hasMessage) { this.message = this.formatMessage(...args); } this.name = this.constructor.name; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error(this.message).stack; } } formatMessage(message) { return message; } } export { KnormError };
joelmukuthu/knorm
packages/knorm/src/KnormError.js
JavaScript
mit
568
using Aragas.Network.Data; using Aragas.Network.IO; namespace PokeD.Core.Packets.PokeD.Chat { public class ChatPrivateMessagePacket : PokeDPacket { public VarInt PlayerID { get; set; } public string Message { get; set; } = string.Empty; public override void Deserialize(ProtobufDeserialiser deserialiser) { PlayerID = deserialiser.Read(PlayerID); Message = deserialiser.Read(Message); } public override void Serialize(ProtobufSerializer serializer) { serializer.Write(PlayerID); serializer.Write(Message); } } }
PokeD/PokeD.Core
PokeD.Core/Packets/PokeD/Chat/ChatPrivateMessagePacket.cs
C#
mit
642
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Siparisler extends Model { protected $table = "siparisler"; protected $fillable = ['urun_id', 'urun_adi', 'adet', 'birim_fiyat', 'toplam_fiyat','toplam_odenen', 'kullanici_id', 'siparis_detay_id', 'siparis_kodu', 'created_at', 'updated_at']; protected $hidden = ['id']; }
aliarslan10/Laravel-Eticaret
app/Siparisler.php
PHP
mit
380
// // TAKUserDefaultsViewCell.h // // Created by Takahiro Oishi // Copyright (c) 2014 Takahiro Oishi. All rights reserved. // Released under the MIT license. // #import <UIKit/UIKit.h> @interface TAKUserDefaultsViewCell : UITableViewCell - (void)bindWithKey:(NSString *)key value:(id)value; - (CGFloat)calculateHeight; @end
taka0125/TAKKit
Classes/UserDefaults/TAKUserDefaultsViewCell.h
C
mit
333
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Grunt Workshop</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="styles/foundation.min.css" /> <link rel="stylesheet" href="styles/custom.min.css" /> </head> <body> <section class="container"> <h1 class="grunt-title"><strong>Grunt</strong> é puro Rock n' Roll!</h1> <div class="grunt-page grunt-show"> <img class="grunt-logo left" src="images/grunt.png" /> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Poterat autem inpune; An hoc usque quaque, aliter in vita? Aufert enim sensus actionemque tollit omnem. Tu vero, inquam, ducas licet, si sequetur; Solum praeterea formosum, solum liberum, solum civem, stultost; Duo Reges: constructio interrete. Cur id non ita fit? Te enim iudicem aequum puto, modo quae dicat ille bene noris. Ergo id est convenienter naturae vivere, a natura discedere. Primum Theophrasti, Strato, physicum se voluit. <a class="label round success" href="#">#grunt</a> <a class="label round" href="#">#daveEhDev</a></p> <p><a id="grunt-button" href="#">Leia mais</a></p> </div> <div class="grunt-page" id="grunt-read-more"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Poterat autem inpune; An hoc usque quaque, aliter in vita? Aufert enim sensus actionemque tollit omnem. Tu vero, inquam, ducas licet, si sequetur; Solum praeterea formosum, solum liberum, solum civem, stultost; Duo Reges: constructio interrete. Cur id non ita fit? Te enim iudicem aequum puto, modo quae dicat ille bene noris. Ergo id est convenienter naturae vivere, a natura discedere. Primum Theophrasti, Strato, physicum se voluit.</p> </div> <pre> Lorem ipsum dolor sit amet com tag pre </pre> </section> <script src="scripts/all.min.js"></script> </body> </html>
almirfilho/grunt-workshop
src/index.html
HTML
mit
2,309
# frozen_string_literal: true module Lib module Messages def messages @messages ||= {} end def message name, &block messages[name] = block end def generate_message name, *args generator = messages[name] || return msg = generator.call(*args) msg[:msg] = name msg end end end
doooby/srsi_de_tram
server/lib/messages.rb
Ruby
mit
344
import { AsyncStorage } from 'react-native'; import {applyMiddleware, compose, createStore} from 'redux'; import thunk from 'redux-thunk'; import createLogger from 'redux-logger'; import client from './apolloClient'; import { initialState as configs } from '../reducers/configurations'; import rootReducer from '../reducers/index' import {autoRehydrate, persistStore} from "redux-persist"; const isProduction = process.env.NODE_ENV !== 'development'; const isClient = typeof document !== 'undefined'; const initialState = { configs, }; /* Commonly used middlewares and enhancers */ /* See: http://redux.js.org/docs/advanced/Middleware.html*/ const middlewares = [thunk, client.middleware()]; const enhancers = []; if (!isProduction && isClient) { const loggerMiddleware = createLogger(); middlewares.push(loggerMiddleware); if (typeof devToolsExtension === 'function') { const devToolsExtension = window.devToolsExtension; enhancers.push(devToolsExtension()); } } const composedEnhancers = compose( applyMiddleware(...middlewares), ...enhancers ); /* Hopefully by now you understand what a store is and how redux uses them, * But if not, take a look at: https://github.com/reactjs/redux/blob/master/docs/api/createStore.md * And https://egghead.io/lessons/javascript-redux-implementing-store-from-scratch */ const store = createStore( rootReducer, initialState, composedEnhancers, autoRehydrate(), ); // Add the autoRehydrate middleware to your redux store //const store_ = createStore(rootReducer, autoRehydrate()); //const createStoreWithMiddleware = applyMiddleware(...middlewares)(store); /* See: https://github.com/reactjs/react-router-redux/issues/305 */ //export const history = syncHistoryWithStore(browserHistory, store); /* Hot reloading of reducers. How futuristic!! */ /*if (module.hot) { module.hot.accept('./reducers', () => { /!*eslint-disable *!/ // Allow require const nextRootReducer = require('./reducers').default; /!*eslint-enable *!/ store.replaceReducer(nextRootReducer); }); }*/ //export { store }; export default configureStore = (navReducer, onComplete) => { let store = createStore( rootReducer, initialState, composedEnhancers, autoRehydrate(), ); persistStore(store, { storage: AsyncStorage }, onComplete); return store; };
khosimorafo/reactmastende
src/store/store.js
JavaScript
mit
2,425
module Argumentative VERSION = "0.0.1beta" end
dillonkearns/argumentative
lib/argumentative/version.rb
Ruby
mit
49
require 'foto/config' module Foto class Client attr_accessor *Foto::Config::VALID_OPTIONS def initialize(options={}) settings = Foto::Config.options.merge(options) Config::VALID_OPTIONS.each do |option| send("#{option}=", settings[option]) end end end end
optimis/foto
lib/foto/client.rb
Ruby
mit
301
<?php return ['293420026' => '三里','293420003' => '上庄','293420011' => '下垣内','293420006' => '久安寺','293420008' => '信貴山','293420009' => '信貴畑','293420021' => '光ケ丘','293420020' => '初香台','293420005' => '北信貴ケ丘','293420028' => '吉新','293420022' => '平等寺','293420002' => '春日丘','293420016' => '梨本','293420010' => '椣原','293420025' => '椹原','293420014' => '椿井','293420015' => '椿台','293420001' => '櫟原','293420012' => '白石畑','293420023' => '福貴','293420024' => '福貴畑','293420013' => '竜田川','293420027' => '緑ケ丘','293420029' => '若井','293420030' => '若葉台','293420004' => '菊美台','293420019' => '西向','293420018' => '西宮','293420007' => '越木塚','293420017' => '鳴川',];
nagoring/jp-address
src/Nago/JpAddress/StreetData/29/29342.php
PHP
mit
790
<?php namespace Kit\SystemBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\HttpFoundation\File\UploadedFile; /** * Page */ class Page { /** * @var integer */ private $id; /** * @var string */ private $slug; /** * @var string */ private $image; /** * @var string */ private $title; /** * @var string */ private $nameInMenu; /** * @var string */ private $body; /** * @var string */ private $keywords; /** * @var string */ private $description; /** * @var \DateTime */ private $createdAt; /** * @var \DateTime */ private $updatedAt; /** * @var \DateTime */ private $deletedAt; public function __construct() { $this->setCreatedAt(new \DateTime()); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set title * * @param string $title * @return Page */ public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Get title * * @return string */ public function getSlug() { return $this->slug; } /** * Set title * * @param string $title * @return Page */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get title * * @return string */ public function getTitle() { return $this->title; } /** * Set title * * @param string $title * @return Page */ public function setImage(UploadedFile $file = null) { $filename = sha1(uniqid(mt_rand(), true)); $filename = $filename.'.'.$file->guessExtension(); $file->move($this->getUploadRootDir(), $filename); $this->image = $filename; return $this; } protected function getUploadRootDir() { // the absolute directory path where uploaded // documents should be saved return __DIR__.'/../../../../web/uploads/pages'; } /** * Get title * * @return string */ public function getImage() { return $this->image; } /** * Set title * * @param string $title * @return Page */ public function setNameInMenu($nameInMenu) { $this->nameInMenu = $nameInMenu; return $this; } /** * Get title * * @return string */ public function getNameInMenu() { return $this->nameInMenu; } /** * Set body * * @param string $body * @return Page */ public function setBody($body) { $this->body = $body; return $this; } /** * Get body * * @return string */ public function getBody() { return $this->body; } /** * Set keywords * * @param string $keywords * @return Page */ public function setKeywords($keywords) { $this->keywords = $keywords; return $this; } /** * Get keywords * * @return string */ public function getKeywords() { return $this->keywords; } /** * Set description * * @param string $description * @return Page */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set createdAt * * @param \DateTime $createdAt * @return Page */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; return $this; } /** * Get createdAt * * @return \DateTime */ public function getCreatedAt() { return $this->createdAt; } /** * Set updatedAt * * @param \DateTime $updatedAt * @return Page */ public function setUpdatedAt($updatedAt) { $this->updatedAt = $updatedAt; return $this; } /** * Get updatedAt * * @return \DateTime */ public function getUpdatedAt() { return $this->updatedAt; } /** * Set deletedAt * * @param \DateTime $deletedAt * @return Page */ public function setDeletedAt($deletedAt) { $this->deletedAt = $deletedAt; return $this; } /** * Get deletedAt * * @return \DateTime */ public function getDeletedAt() { return $this->deletedAt; } /** * Get the image URL * * @return null|string */ public function getWebPath() { return '/uploads/pages/' . $this->getImage(); } }
novikov-anton/kit
src/Kit/SystemBundle/Entity/Page.php
PHP
mit
5,166
<?php namespace PragmaRX\Sdk\Services\FacebookMessenger\Data\Entities; use PragmaRX\Sdk\Core\Database\Eloquent\Model; use PragmaRX\Sdk\Services\Files\Data\Entities\FileName; class FacebookMessengerDocument extends Model { protected $table = 'facebook_messenger_documents'; protected $fillable = [ 'facebook_messenger_file_id', 'file_name_id', 'thumb_id', 'file_name', 'mime_type', 'file_size', ]; public function fileName() { return $this->belongsTo(FileName::class); } public function thumb() { return $this->belongsTo(FacebookMessengerPhoto::class); } }
antonioribeiro/sdk
src/Services/FacebookMessenger/Data/disabled/FacebookMessengerDocument.php
PHP
mit
659
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { URI } from 'vs/base/common/uri'; import { toResource, IEditorCommandsContext, SideBySideEditor } from 'vs/workbench/common/editor'; import { IWindowsService, IWindowService, IURIToOpen, IOpenSettings, INewWindowOptions, isWorkspaceToOpen } from 'vs/platform/windows/common/windows'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { ExplorerFocusCondition, TextFileContentProvider, VIEWLET_ID, IExplorerService } from 'vs/workbench/contrib/files/common/files'; import { ExplorerViewlet } from 'vs/workbench/contrib/files/browser/explorerViewlet'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { ITextFileService, ISaveOptions } from 'vs/workbench/services/textfile/common/textfiles'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { IListService } from 'vs/platform/list/browser/listService'; import { CommandsRegistry } from 'vs/platform/commands/common/commands'; import { RawContextKey, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IResourceInput } from 'vs/platform/editor/common/editor'; import { IFileService } from 'vs/platform/files/common/files'; import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService'; import { IEditorViewState } from 'vs/editor/common/editorCommon'; import { getCodeEditor } from 'vs/editor/browser/editorBrowser'; import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { KeyMod, KeyCode, KeyChord } from 'vs/base/common/keyCodes'; import { isWindows, isMacintosh } from 'vs/base/common/platform'; import { ITextModelService } from 'vs/editor/common/services/resolverService'; import { sequence } from 'vs/base/common/async'; import { getResourceForCommand, getMultiSelectedResources } from 'vs/workbench/contrib/files/browser/files'; import { IWorkspaceEditingService } from 'vs/workbench/services/workspace/common/workspaceEditing'; import { getMultiSelectedEditorContexts } from 'vs/workbench/browser/parts/editor/editorCommands'; import { Schemas } from 'vs/base/common/network'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { IEditorService, SIDE_GROUP } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { ILabelService } from 'vs/platform/label/common/label'; import { onUnexpectedError } from 'vs/base/common/errors'; import { basename, toLocalResource, joinPath } from 'vs/base/common/resources'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { UNTITLED_WORKSPACE_NAME } from 'vs/platform/workspaces/common/workspaces'; import { withUndefinedAsNull } from 'vs/base/common/types'; // Commands export const REVEAL_IN_OS_COMMAND_ID = 'revealFileInOS'; export const REVEAL_IN_OS_LABEL = isWindows ? nls.localize('revealInWindows', "Reveal in Explorer") : isMacintosh ? nls.localize('revealInMac', "Reveal in Finder") : nls.localize('openContainer', "Open Containing Folder"); export const REVEAL_IN_EXPLORER_COMMAND_ID = 'revealInExplorer'; export const REVERT_FILE_COMMAND_ID = 'workbench.action.files.revert'; export const OPEN_TO_SIDE_COMMAND_ID = 'explorer.openToSide'; export const SELECT_FOR_COMPARE_COMMAND_ID = 'selectForCompare'; export const COMPARE_SELECTED_COMMAND_ID = 'compareSelected'; export const COMPARE_RESOURCE_COMMAND_ID = 'compareFiles'; export const COMPARE_WITH_SAVED_COMMAND_ID = 'workbench.files.action.compareWithSaved'; export const COPY_PATH_COMMAND_ID = 'copyFilePath'; export const COPY_RELATIVE_PATH_COMMAND_ID = 'copyRelativeFilePath'; export const SAVE_FILE_AS_COMMAND_ID = 'workbench.action.files.saveAs'; export const SAVE_FILE_AS_LABEL = nls.localize('saveAs', "Save As..."); export const SAVE_FILE_COMMAND_ID = 'workbench.action.files.save'; export const SAVE_FILE_LABEL = nls.localize('save', "Save"); export const SAVE_FILE_WITHOUT_FORMATTING_COMMAND_ID = 'workbench.action.files.saveWithoutFormatting'; export const SAVE_FILE_WITHOUT_FORMATTING_LABEL = nls.localize('saveWithoutFormatting', "Save without Formatting"); export const SAVE_ALL_COMMAND_ID = 'saveAll'; export const SAVE_ALL_LABEL = nls.localize('saveAll', "Save All"); export const SAVE_ALL_IN_GROUP_COMMAND_ID = 'workbench.files.action.saveAllInGroup'; export const SAVE_FILES_COMMAND_ID = 'workbench.action.files.saveFiles'; export const OpenEditorsGroupContext = new RawContextKey<boolean>('groupFocusedInOpenEditors', false); export const DirtyEditorContext = new RawContextKey<boolean>('dirtyEditor', false); export const ResourceSelectedForCompareContext = new RawContextKey<boolean>('resourceSelectedForCompare', false); export const REMOVE_ROOT_FOLDER_COMMAND_ID = 'removeRootFolder'; export const REMOVE_ROOT_FOLDER_LABEL = nls.localize('removeFolderFromWorkspace', "Remove Folder from Workspace"); export const openWindowCommand = (accessor: ServicesAccessor, urisToOpen: IURIToOpen[], options?: IOpenSettings) => { if (Array.isArray(urisToOpen)) { const windowService = accessor.get(IWindowService); const environmentService = accessor.get(IEnvironmentService); // rewrite untitled: workspace URIs to the absolute path on disk urisToOpen = urisToOpen.map(uriToOpen => { if (isWorkspaceToOpen(uriToOpen) && uriToOpen.workspaceUri.scheme === Schemas.untitled) { return { workspaceUri: joinPath(environmentService.untitledWorkspacesHome, uriToOpen.workspaceUri.path, UNTITLED_WORKSPACE_NAME) }; } return uriToOpen; }); windowService.openWindow(urisToOpen, options); } }; export const newWindowCommand = (accessor: ServicesAccessor, options?: INewWindowOptions) => { const windowsService = accessor.get(IWindowsService); windowsService.openNewWindow(options); }; function save( resource: URI | null, isSaveAs: boolean, options: ISaveOptions | undefined, editorService: IEditorService, fileService: IFileService, untitledEditorService: IUntitledEditorService, textFileService: ITextFileService, editorGroupService: IEditorGroupsService, environmentService: IWorkbenchEnvironmentService ): Promise<any> { function ensureForcedSave(options?: ISaveOptions): ISaveOptions { if (!options) { options = { force: true }; } else { options.force = true; } return options; } if (resource && (fileService.canHandleResource(resource) || resource.scheme === Schemas.untitled)) { // Save As (or Save untitled with associated path) if (isSaveAs || resource.scheme === Schemas.untitled) { let encodingOfSource: string | undefined; if (resource.scheme === Schemas.untitled) { encodingOfSource = untitledEditorService.getEncoding(resource); } else if (fileService.canHandleResource(resource)) { const textModel = textFileService.models.get(resource); encodingOfSource = textModel && textModel.getEncoding(); // text model can be null e.g. if this is a binary file! } let viewStateOfSource: IEditorViewState | null; const activeTextEditorWidget = getCodeEditor(editorService.activeTextEditorWidget); if (activeTextEditorWidget) { const activeResource = toResource(editorService.activeEditor, { supportSideBySide: SideBySideEditor.MASTER }); if (activeResource && (fileService.canHandleResource(activeResource) || resource.scheme === Schemas.untitled) && activeResource.toString() === resource.toString()) { viewStateOfSource = activeTextEditorWidget.saveViewState(); } } // Special case: an untitled file with associated path gets saved directly unless "saveAs" is true let savePromise: Promise<URI | undefined>; if (!isSaveAs && resource.scheme === Schemas.untitled && untitledEditorService.hasAssociatedFilePath(resource)) { savePromise = textFileService.save(resource, options).then(result => { if (result) { return toLocalResource(resource, environmentService.configuration.remoteAuthority); } return undefined; }); } // Otherwise, really "Save As..." else { // Force a change to the file to trigger external watchers if any // fixes https://github.com/Microsoft/vscode/issues/59655 options = ensureForcedSave(options); savePromise = textFileService.saveAs(resource, undefined, options); } return savePromise.then(target => { if (!target || target.toString() === resource.toString()) { return false; // save canceled or same resource used } const replacement: IResourceInput = { resource: target, encoding: encodingOfSource, options: { pinned: true, viewState: viewStateOfSource || undefined } }; return Promise.all(editorGroupService.groups.map(g => editorService.replaceEditors([{ editor: { resource }, replacement }], g))).then(() => true); }); } // Pin the active editor if we are saving it const activeControl = editorService.activeControl; const activeEditorResource = activeControl && activeControl.input && activeControl.input.getResource(); if (activeControl && activeEditorResource && activeEditorResource.toString() === resource.toString()) { activeControl.group.pinEditor(activeControl.input); } // Just save (force a change to the file to trigger external watchers if any) options = ensureForcedSave(options); return textFileService.save(resource, options); } return Promise.resolve(false); } function saveAll(saveAllArguments: any, editorService: IEditorService, untitledEditorService: IUntitledEditorService, textFileService: ITextFileService, editorGroupService: IEditorGroupsService): Promise<any> { // Store some properties per untitled file to restore later after save is completed const groupIdToUntitledResourceInput = new Map<number, IResourceInput[]>(); editorGroupService.groups.forEach(g => { const activeEditorResource = g.activeEditor && g.activeEditor.getResource(); g.editors.forEach(e => { const resource = e.getResource(); if (resource && untitledEditorService.isDirty(resource)) { if (!groupIdToUntitledResourceInput.has(g.id)) { groupIdToUntitledResourceInput.set(g.id, []); } groupIdToUntitledResourceInput.get(g.id)!.push({ encoding: untitledEditorService.getEncoding(resource), resource, options: { inactive: activeEditorResource ? activeEditorResource.toString() !== resource.toString() : true, pinned: true, preserveFocus: true, index: g.getIndexOfEditor(e) } }); } }); }); // Save all return textFileService.saveAll(saveAllArguments).then(result => { groupIdToUntitledResourceInput.forEach((inputs, groupId) => { // Update untitled resources to the saved ones, so we open the proper files inputs.forEach(i => { const targetResult = result.results.filter(r => r.success && r.source.toString() === i.resource.toString()).pop(); if (targetResult && targetResult.target) { i.resource = targetResult.target; } }); editorService.openEditors(inputs, groupId); }); }); } // Command registration CommandsRegistry.registerCommand({ id: REVERT_FILE_COMMAND_ID, handler: (accessor, resource: URI | object) => { const editorService = accessor.get(IEditorService); const textFileService = accessor.get(ITextFileService); const notificationService = accessor.get(INotificationService); const resources = getMultiSelectedResources(resource, accessor.get(IListService), editorService) .filter(resource => resource.scheme !== Schemas.untitled); if (resources.length) { return textFileService.revertAll(resources, { force: true }).then(undefined, error => { notificationService.error(nls.localize('genericRevertError', "Failed to revert '{0}': {1}", resources.map(r => basename(r)).join(', '), toErrorMessage(error, false))); }); } return Promise.resolve(true); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ weight: KeybindingWeight.WorkbenchContrib, when: ExplorerFocusCondition, primary: KeyMod.CtrlCmd | KeyCode.Enter, mac: { primary: KeyMod.WinCtrl | KeyCode.Enter }, id: OPEN_TO_SIDE_COMMAND_ID, handler: (accessor, resource: URI | object) => { const editorService = accessor.get(IEditorService); const listService = accessor.get(IListService); const fileService = accessor.get(IFileService); const resources = getMultiSelectedResources(resource, listService, editorService); // Set side input if (resources.length) { return fileService.resolveAll(resources.map(resource => ({ resource }))).then(resolved => { const editors = resolved.filter(r => r.stat && r.success && !r.stat.isDirectory).map(r => ({ resource: r.stat!.resource })); return editorService.openEditors(editors, SIDE_GROUP); }); } return Promise.resolve(true); } }); const COMPARE_WITH_SAVED_SCHEMA = 'showModifications'; let providerDisposables: IDisposable[] = []; KeybindingsRegistry.registerCommandAndKeybindingRule({ id: COMPARE_WITH_SAVED_COMMAND_ID, when: undefined, weight: KeybindingWeight.WorkbenchContrib, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_D), handler: (accessor, resource: URI | object) => { const instantiationService = accessor.get(IInstantiationService); const textModelService = accessor.get(ITextModelService); const editorService = accessor.get(IEditorService); const fileService = accessor.get(IFileService); // Register provider at first as needed let registerEditorListener = false; if (providerDisposables.length === 0) { registerEditorListener = true; const provider = instantiationService.createInstance(TextFileContentProvider); providerDisposables.push(provider); providerDisposables.push(textModelService.registerTextModelContentProvider(COMPARE_WITH_SAVED_SCHEMA, provider)); } // Open editor (only resources that can be handled by file service are supported) const uri = getResourceForCommand(resource, accessor.get(IListService), editorService); if (uri && fileService.canHandleResource(uri)) { const name = basename(uri); const editorLabel = nls.localize('modifiedLabel', "{0} (in file) ↔ {1}", name, name); TextFileContentProvider.open(uri, COMPARE_WITH_SAVED_SCHEMA, editorLabel, editorService).then(() => { // Dispose once no more diff editor is opened with the scheme if (registerEditorListener) { providerDisposables.push(editorService.onDidVisibleEditorsChange(() => { if (!editorService.editors.some(editor => !!toResource(editor, { supportSideBySide: SideBySideEditor.DETAILS, filterByScheme: COMPARE_WITH_SAVED_SCHEMA }))) { providerDisposables = dispose(providerDisposables); } })); } }, error => { providerDisposables = dispose(providerDisposables); }); } return Promise.resolve(true); } }); let globalResourceToCompare: URI | undefined; let resourceSelectedForCompareContext: IContextKey<boolean>; CommandsRegistry.registerCommand({ id: SELECT_FOR_COMPARE_COMMAND_ID, handler: (accessor, resource: URI | object) => { const listService = accessor.get(IListService); globalResourceToCompare = getResourceForCommand(resource, listService, accessor.get(IEditorService)); if (!resourceSelectedForCompareContext) { resourceSelectedForCompareContext = ResourceSelectedForCompareContext.bindTo(accessor.get(IContextKeyService)); } resourceSelectedForCompareContext.set(true); } }); CommandsRegistry.registerCommand({ id: COMPARE_SELECTED_COMMAND_ID, handler: (accessor, resource: URI | object) => { const editorService = accessor.get(IEditorService); const resources = getMultiSelectedResources(resource, accessor.get(IListService), editorService); if (resources.length === 2) { return editorService.openEditor({ leftResource: resources[0], rightResource: resources[1] }); } return Promise.resolve(true); } }); CommandsRegistry.registerCommand({ id: COMPARE_RESOURCE_COMMAND_ID, handler: (accessor, resource: URI | object) => { const editorService = accessor.get(IEditorService); const listService = accessor.get(IListService); const rightResource = getResourceForCommand(resource, listService, editorService); if (globalResourceToCompare && rightResource) { editorService.openEditor({ leftResource: globalResourceToCompare, rightResource }).then(undefined, onUnexpectedError); } } }); function revealResourcesInOS(resources: URI[], windowsService: IWindowsService, notificationService: INotificationService, workspaceContextService: IWorkspaceContextService): void { if (resources.length) { sequence(resources.map(r => () => windowsService.showItemInFolder(r.scheme === Schemas.userData ? r.with({ scheme: Schemas.file }) : r))); } else if (workspaceContextService.getWorkspace().folders.length) { windowsService.showItemInFolder(workspaceContextService.getWorkspace().folders[0].uri); } else { notificationService.info(nls.localize('openFileToReveal', "Open a file first to reveal")); } } KeybindingsRegistry.registerCommandAndKeybindingRule({ id: REVEAL_IN_OS_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: EditorContextKeys.focus.toNegated(), primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_R, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_R }, handler: (accessor: ServicesAccessor, resource: URI | object) => { const resources = getMultiSelectedResources(resource, accessor.get(IListService), accessor.get(IEditorService)); revealResourcesInOS(resources, accessor.get(IWindowsService), accessor.get(INotificationService), accessor.get(IWorkspaceContextService)); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_R), id: 'workbench.action.files.revealActiveFileInWindows', handler: (accessor: ServicesAccessor) => { const editorService = accessor.get(IEditorService); const activeInput = editorService.activeEditor; const resource = activeInput ? activeInput.getResource() : null; const resources = resource ? [resource] : []; revealResourcesInOS(resources, accessor.get(IWindowsService), accessor.get(INotificationService), accessor.get(IWorkspaceContextService)); } }); async function resourcesToClipboard(resources: URI[], relative: boolean, clipboardService: IClipboardService, notificationService: INotificationService, labelService: ILabelService): Promise<void> { if (resources.length) { const lineDelimiter = isWindows ? '\r\n' : '\n'; const text = resources.map(resource => labelService.getUriLabel(resource, { relative, noPrefix: true })) .join(lineDelimiter); await clipboardService.writeText(text); } else { notificationService.info(nls.localize('openFileToCopy', "Open a file first to copy its path")); } } KeybindingsRegistry.registerCommandAndKeybindingRule({ weight: KeybindingWeight.WorkbenchContrib, when: EditorContextKeys.focus.toNegated(), primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C }, id: COPY_PATH_COMMAND_ID, handler: async (accessor, resource: URI | object) => { const resources = getMultiSelectedResources(resource, accessor.get(IListService), accessor.get(IEditorService)); await resourcesToClipboard(resources, false, accessor.get(IClipboardService), accessor.get(INotificationService), accessor.get(ILabelService)); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ weight: KeybindingWeight.WorkbenchContrib, when: EditorContextKeys.focus.toNegated(), primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyMod.Alt | KeyCode.KEY_C, win: { primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_C) }, id: COPY_RELATIVE_PATH_COMMAND_ID, handler: async (accessor, resource: URI | object) => { const resources = getMultiSelectedResources(resource, accessor.get(IListService), accessor.get(IEditorService)); await resourcesToClipboard(resources, true, accessor.get(IClipboardService), accessor.get(INotificationService), accessor.get(ILabelService)); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_P), id: 'workbench.action.files.copyPathOfActiveFile', handler: async (accessor) => { const editorService = accessor.get(IEditorService); const activeInput = editorService.activeEditor; const resource = activeInput ? activeInput.getResource() : null; const resources = resource ? [resource] : []; await resourcesToClipboard(resources, false, accessor.get(IClipboardService), accessor.get(INotificationService), accessor.get(ILabelService)); } }); CommandsRegistry.registerCommand({ id: REVEAL_IN_EXPLORER_COMMAND_ID, handler: (accessor, resource: URI | object) => { const viewletService = accessor.get(IViewletService); const contextService = accessor.get(IWorkspaceContextService); const explorerService = accessor.get(IExplorerService); const uri = getResourceForCommand(resource, accessor.get(IListService), accessor.get(IEditorService)); viewletService.openViewlet(VIEWLET_ID, false).then((viewlet: ExplorerViewlet) => { if (uri && contextService.isInsideWorkspace(uri)) { const explorerView = viewlet.getExplorerView(); if (explorerView) { explorerView.setExpanded(true); explorerService.select(uri, true).then(() => explorerView.focus(), onUnexpectedError); } } else { const openEditorsView = viewlet.getOpenEditorsView(); if (openEditorsView) { openEditorsView.setExpanded(true); openEditorsView.focus(); } } }); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ id: SAVE_FILE_AS_COMMAND_ID, weight: KeybindingWeight.WorkbenchContrib, when: undefined, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_S, handler: (accessor, resourceOrObject: URI | object | { from: string }) => { const editorService = accessor.get(IEditorService); let resource: URI | null = null; if (resourceOrObject && 'from' in resourceOrObject && resourceOrObject.from === 'menu') { resource = withUndefinedAsNull(toResource(editorService.activeEditor)); } else { resource = withUndefinedAsNull(getResourceForCommand(resourceOrObject, accessor.get(IListService), editorService)); } return save(resource, true, undefined, editorService, accessor.get(IFileService), accessor.get(IUntitledEditorService), accessor.get(ITextFileService), accessor.get(IEditorGroupsService), accessor.get(IWorkbenchEnvironmentService)); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ when: undefined, weight: KeybindingWeight.WorkbenchContrib, primary: KeyMod.CtrlCmd | KeyCode.KEY_S, id: SAVE_FILE_COMMAND_ID, handler: (accessor, resource: URI | object) => { const editorService = accessor.get(IEditorService); const resources = getMultiSelectedResources(resource, accessor.get(IListService), editorService); if (resources.length === 1) { // If only one resource is selected explictly call save since the behavior is a bit different than save all #41841 return save(resources[0], false, undefined, editorService, accessor.get(IFileService), accessor.get(IUntitledEditorService), accessor.get(ITextFileService), accessor.get(IEditorGroupsService), accessor.get(IWorkbenchEnvironmentService)); } return saveAll(resources, editorService, accessor.get(IUntitledEditorService), accessor.get(ITextFileService), accessor.get(IEditorGroupsService)); } }); KeybindingsRegistry.registerCommandAndKeybindingRule({ when: undefined, weight: KeybindingWeight.WorkbenchContrib, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyCode.KEY_S), win: { primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_S) }, id: SAVE_FILE_WITHOUT_FORMATTING_COMMAND_ID, handler: accessor => { const editorService = accessor.get(IEditorService); const resource = toResource(editorService.activeEditor, { supportSideBySide: SideBySideEditor.MASTER }); if (resource) { return save(resource, false, { skipSaveParticipants: true }, editorService, accessor.get(IFileService), accessor.get(IUntitledEditorService), accessor.get(ITextFileService), accessor.get(IEditorGroupsService), accessor.get(IWorkbenchEnvironmentService)); } return undefined; } }); CommandsRegistry.registerCommand({ id: SAVE_ALL_COMMAND_ID, handler: (accessor) => { return saveAll(true, accessor.get(IEditorService), accessor.get(IUntitledEditorService), accessor.get(ITextFileService), accessor.get(IEditorGroupsService)); } }); CommandsRegistry.registerCommand({ id: SAVE_ALL_IN_GROUP_COMMAND_ID, handler: (accessor, resource: URI | object, editorContext: IEditorCommandsContext) => { const contexts = getMultiSelectedEditorContexts(editorContext, accessor.get(IListService), accessor.get(IEditorGroupsService)); const editorGroupService = accessor.get(IEditorGroupsService); let saveAllArg: any; if (!contexts.length) { saveAllArg = true; } else { const fileService = accessor.get(IFileService); saveAllArg = []; contexts.forEach(context => { const editorGroup = editorGroupService.getGroup(context.groupId); if (editorGroup) { editorGroup.editors.forEach(editor => { const resource = toResource(editor, { supportSideBySide: SideBySideEditor.MASTER }); if (resource && (resource.scheme === Schemas.untitled || fileService.canHandleResource(resource))) { saveAllArg.push(resource); } }); } }); } return saveAll(saveAllArg, accessor.get(IEditorService), accessor.get(IUntitledEditorService), accessor.get(ITextFileService), accessor.get(IEditorGroupsService)); } }); CommandsRegistry.registerCommand({ id: SAVE_FILES_COMMAND_ID, handler: (accessor) => { return saveAll(false, accessor.get(IEditorService), accessor.get(IUntitledEditorService), accessor.get(ITextFileService), accessor.get(IEditorGroupsService)); } }); CommandsRegistry.registerCommand({ id: REMOVE_ROOT_FOLDER_COMMAND_ID, handler: (accessor, resource: URI | object) => { const workspaceEditingService = accessor.get(IWorkspaceEditingService); const contextService = accessor.get(IWorkspaceContextService); const workspace = contextService.getWorkspace(); const resources = getMultiSelectedResources(resource, accessor.get(IListService), accessor.get(IEditorService)).filter(r => // Need to verify resources are workspaces since multi selection can trigger this command on some non workspace resources workspace.folders.some(f => f.uri.toString() === r.toString()) ); return workspaceEditingService.removeFolders(resources); } });
mjbvz/vscode
src/vs/workbench/contrib/files/browser/fileCommands.ts
TypeScript
mit
27,668
<?php namespace BigD\UsuariosBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * Permiso * * @ORM\Table(name="permiso") * @ORM\Entity * @UniqueEntity("nombre") */ class Permiso { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="nombre", type="string", length=255,unique=true) */ private $nombre; /** * @var string * * @ORM\Column(name="descripcion", type="string", length=255,nullable=true) */ private $descripcion; /** * @var datetime $creado * * @Gedmo\Timestampable(on="create") * @ORM\Column(name="creado", type="datetime") */ private $creado; /** * @var datetime $actualizado * * @Gedmo\Timestampable(on="update") * @ORM\Column(name="actualizado",type="datetime") */ private $actualizado; /** * @var integer $creadoPor * * @Gedmo\Blameable(on="create") * @ORM\ManyToOne(targetEntity="BigD\UsuariosBundle\Entity\Usuario") * @ORM\JoinColumn(name="creado_por", referencedColumnName="id", nullable=true) */ private $creadoPor; /** * @var integer $actualizadoPor * * @Gedmo\Blameable(on="update") * @ORM\ManyToOne(targetEntity="BigD\UsuariosBundle\Entity\Usuario") * @ORM\JoinColumn(name="actualizado_por", referencedColumnName="id", nullable=true) */ private $actualizadoPor; /** * @ORM\OneToMany(targetEntity="PermisoPerfil", mappedBy="permiso") * */ private $permisos; public function __toString() { return $this->nombre; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return Permiso */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set descripcion * * @param string $descripcion * @return Permiso */ public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } /** * Get descripcion * * @return string */ public function getDescripcion() { return $this->descripcion; } /** * Set creado * * @param \DateTime $creado * @return Permiso */ public function setCreado($creado) { $this->creado = $creado; return $this; } /** * Get creado * * @return \DateTime */ public function getCreado() { return $this->creado; } /** * Set actualizado * * @param \DateTime $actualizado * @return Permiso */ public function setActualizado($actualizado) { $this->actualizado = $actualizado; return $this; } /** * Get actualizado * * @return \DateTime */ public function getActualizado() { return $this->actualizado; } /** * Set creadoPor * * @param \BigD\UsuariosBundle\Entity\Usuario $creadoPor * @return Permiso */ public function setCreadoPor(\BigD\UsuariosBundle\Entity\Usuario $creadoPor = null) { $this->creadoPor = $creadoPor; return $this; } /** * Get creadoPor * * @return \BigD\UsuariosBundle\Entity\Usuario */ public function getCreadoPor() { return $this->creadoPor; } /** * Set actualizadoPor * * @param \BigD\UsuariosBundle\Entity\Usuario $actualizadoPor * @return Permiso */ public function setActualizadoPor(\BigD\UsuariosBundle\Entity\Usuario $actualizadoPor = null) { $this->actualizadoPor = $actualizadoPor; return $this; } /** * Get actualizadoPor * * @return \BigD\UsuariosBundle\Entity\Usuario */ public function getActualizadoPor() { return $this->actualizadoPor; } /** * Constructor */ public function __construct() { $this->permisos = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add permisos * * @param \BigD\UsuariosBundle\Entity\PermisoPerfil $permisos * @return Permiso */ public function addPermiso(\BigD\UsuariosBundle\Entity\PermisoPerfil $permisos) { $this->permisos[] = $permisos; return $this; } /** * Remove permisos * * @param \BigD\UsuariosBundle\Entity\PermisoPerfil $permisos */ public function removePermiso(\BigD\UsuariosBundle\Entity\PermisoPerfil $permisos) { $this->permisos->removeElement($permisos); } /** * Get permisos * * @return \Doctrine\Common\Collections\Collection */ public function getPermisos() { return $this->permisos; } }
matudelatower/BigD
src/BigD/UsuariosBundle/Entity/Permiso.php
PHP
mit
5,265
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE namespace vc_attributes { template<> struct appobjectAttribute { }; }; // end namespace vc_attributes END_ATF_NAMESPACE
goodwinxp/Yorozuya
library/ATF/__appobjectAttribute.hpp
C++
mit
337
// @ts-check /*! * V4Fire Client Core * https://github.com/V4Fire/Client * * Released under the MIT license * https://github.com/V4Fire/Client/blob/master/LICENSE */ /** * @typedef {import('playwright').Page} Page */ const h = include('tests/helpers'); /** @param {Page} page */ module.exports = (page) => { beforeEach(async () => { await page.evaluate(() => { globalThis.removeCreatedComponents(); }); }); describe('b-checkbox simple usage', () => { const q = '[data-id="target"]'; it('providing of attributes', async () => { await init({id: 'foo', name: 'bla'}); const input = await page.$('#foo'); expect( await input.evaluate((ctx) => [ ctx.tagName, ctx.type, ctx.name, ctx.checked ]) ).toEqual(['INPUT', 'checkbox', 'bla', false]); }); it('checked checkbox', async () => { const target = await init({checked: true, value: 'bar'}); expect( await target.evaluate((ctx) => ctx.value) ).toBe('bar'); }); it('non-changeable checkbox', async () => { const target = await init({changeable: false}); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); await page.click(q); expect( await target.evaluate((ctx) => ctx.value) ).toBeTrue(); await page.click(q); expect( await target.evaluate((ctx) => ctx.value) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.uncheck()) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); }); it('checking a non-defined value (user actions)', async () => { const target = await init(); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); await page.click(q); expect( await target.evaluate((ctx) => ctx.value) ).toBeTrue(); await page.click(q); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); }); it('checking a predefined value (user actions)', async () => { const target = await init({value: 'bar'}); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); await page.click(q); expect( await target.evaluate((ctx) => ctx.value) ).toBe('bar'); await page.click(q); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); }); it('checking a non-defined value (API)', async () => { const target = await init(); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); expect( await target.evaluate((ctx) => ctx.check()) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.value) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.uncheck()) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); expect( await target.evaluate((ctx) => ctx.toggle()) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.toggle()) ).toBeUndefined(); }); it('checking a predefined value (API)', async () => { const target = await init({value: 'bar'}); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); expect( await target.evaluate((ctx) => ctx.check()) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.value) ).toBe('bar'); expect( await target.evaluate((ctx) => ctx.uncheck()) ).toBeTrue(); expect( await target.evaluate((ctx) => ctx.value) ).toBeUndefined(); expect( await target.evaluate((ctx) => ctx.toggle()) ).toBe('bar'); expect( await target.evaluate((ctx) => ctx.toggle()) ).toBeUndefined(); }); it('checkbox with a `label` prop', async () => { const target = await init({ label: 'Foo' }); expect( await target.evaluate((ctx) => ctx.block.element('label').textContent.trim()) ).toEqual('Foo'); const selector = await target.evaluate( (ctx) => `.${ctx.block.element('label').className.split(' ').join('.')}` ); await page.click(selector); expect( await target.evaluate((ctx) => ctx.value) ).toBeTrue(); }); async function init(attrs = {}) { await page.evaluate((attrs) => { const scheme = [ { attrs: { 'data-id': 'target', ...attrs } } ]; globalThis.renderComponents('b-checkbox', scheme); }, attrs); return h.component.waitForComponent(page, q); } }); };
V4Fire/Client
src/form/b-checkbox/test/runners/simple.js
JavaScript
mit
4,429
module SubDiff # Stores a collection of {Diff} objects for all matches from # a {String#sub_diff} or {String#gsub_diff} replacement. # # It behaves like a {String} that represents the entire # replacement result from {String#sub} or {String#gsub}. # # It also behaves like an {Enumerable} by delegating to # {Collection#diffs} - an {Array} containing each {Diff}. # # @api public class Collection < SimpleDelegator extend Forwardable include Enumerable def_delegators :diffs, :each, :size attr_reader :string, :diffs def initialize(string) @string = string @diffs = [] super(string) end def changed? diffs.any?(&:changed?) end def clear diffs.clear __setobj__('') self end def push(diff) unless diff.empty? diffs << diff __setobj__(diffs.join) end end def reset clear __setobj__(string) yield if block_given? self end end end
shuber/sub_diff
lib/sub_diff/collection.rb
Ruby
mit
1,007
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Base64.h * Author: ckarner * * Created on December 12, 2015, 9:40 PM */ #ifndef BASE64_H #define BASE64_H #include <QString> class Base64 { public: static QString toBase64(QString str); static QString fromBase64(QString str); private: }; #endif /* BASE64_H */
HSHL/mailclient
src/Base64.h
C
mit
483
<!DOCTYPE html> <html class="sidebar_default no-js" lang="en"> <head> <meta charset="utf-8"> <title>Start - Admin Template</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <link rel="shortcut icon" href="css/images/favicon.png"> <!-- Le styles --> <link href="css/twitter/bootstrap.css" rel="stylesheet"> <link href="css/base.css" rel="stylesheet"> <link href="css/twitter/responsive.css" rel="stylesheet"> <link href="css/jquery-ui-1.8.23.custom.css" rel="stylesheet"> <script src="js/plugins/modernizr.custom.32549.js"></script> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div id="loading"><img src="img/ajax-loader.gif"></div> <div id="responsive_part"> <div class="logo"> <a href="index.html"><span>Dashboard</span><span class="icon"></span></a> </div> <ul class="nav responsive"> <li> <button class="btn responsive_menu icon_item" data-toggle="collapse" data-target=".overview"> <i class="icon-reorder"></i> </button> </li> </ul> </div> <!-- Responsive part --> <div id="sidebar" class=""> <div class="scrollbar"> <div class="track"> <div class="thumb"> <div class="end"></div> </div> </div> </div> <div class="viewport "> <div class="overview collapse"> <div class="search row-fluid container"> <h2>Search</h2> <form class="form-search"> <div class="input-append"> <input type="text" class=" search-query" placeholder=""> <button class="btn_search color_4">Search</button> </div> </form> </div> <ul id="sidebar_menu" class="navbar nav nav-list container full"> <li class="accordion-group active color_4"> <a class="dashboard " href="index.html"><img src="img/menu_icons/dashboard.png"><span>Dashboard</span></a> </li> <li class="accordion-group color_7"> <a class="accordion-toggle widgets collapsed " data-toggle="collapse" data-parent="#sidebar_menu" href="#collapse1"> <img src="img/menu_icons/forms.png"><span>Form Elements</span></a> <ul id="collapse1" class="accordion-body collapse"> <li><a href="forms_general.html">General</a></li> <li><a href="forms_wizard.html">Wizards</a></li> <li><a href="forms_validation.html">Validation</a></li> <li><a href="forms_editor.html">Editor</a></li> </ul> </li> <li class="accordion-group color_3"> <a class="accordion-toggle widgets collapsed" data-toggle="collapse" data-parent="#sidebar_menu" href="#collapse2"> <img src="img/menu_icons/widgets.png"><span>UI Widgets</span></a> <ul id="collapse2" class="accordion-body collapse"> <li><a href="ui_buttons.html">Buttons</a></li> <li><a href="ui_dialogs.html">Dialogs</a></li> <li><a href="ui_icons.html">Icons</a></li> <li><a href="ui_tabs.html">Tabs</a></li> <li><a href="ui_accordion.html">Accordion</a></li> </ul> </li> <li class="color_13"> <a class="widgets" href="calendar2.html"> <img src="img/menu_icons/calendar.png"><span>Calendar</span></a> </li> <li class="color_10"> <a class="widgets"data-parent="#sidebar_menu" href="maps.html"> <img src="img/menu_icons/maps.png"><span>Maps</span></a> </li> <li class="accordion-group color_12"> <a class="accordion-toggle widgets collapsed" data-toggle="collapse" data-parent="#sidebar_menu" href="#collapse3"> <img src="img/menu_icons/tables.png"><span>Tables</span></a> <ul id="collapse3" class="accordion-body collapse"> <li><a href="tables_static.html">Static</a></li> <li><a href="tables_dynamic.html">Dynamics</a></li> </ul> </li> <li class="accordion-group color_19"> <a class="accordion-toggle widgets collapsed" data-toggle="collapse" data-parent="#sidebar_menu" href="#collapse4"> <img src="img/menu_icons/statistics.png"><span>Charts</span></a> <ul id="collapse4" class="accordion-body collapse"> <li><a href="statistics.html">Statistics Elements</a></li> <li><a href="charts.html">Charts</a></li> </ul> </li> <li class="color_24"> <a class="widgets"data-parent="#sidebar_menu" href="grid.html"> <img src="img/menu_icons/grid.png"><span>Grid</span></a> </li> <li class="color_8"> <a class="widgets"data-parent="#sidebar_menu" href="media.html"> <img src="img/menu_icons/gallery.png"><span>Media</span></a> </li> <li class="color_4"> <a class="widgets"data-parent="#sidebar_menu" href="file_explorer.html"> <img src="img/menu_icons/explorer.png"><span>File Explorer</span> <!-- --></a> </li> <li class="accordion-group color_25"> <a class="accordion-toggle widgets collapsed" data-toggle="collapse" data-parent="#sidebar_menu" href="#collapse5"> <img src="img/menu_icons/others.png"><span>Specific Pages</span></a> <ul id="collapse5" class="accordion-body collapse"> <li><a href="profile.html">Profile</a></li> <li><a href="search.html">Search</a></li> <li><a href="index2.html">Login</a></li> <li><a href="404.html">404 Error</a></li> <li ><a href="blog.html">Blog</a></li> </ul> </li> </ul> <div class="menu_states row-fluid container "> <h2 class="pull-left">Menu Settings</h2> <div class="options pull-right"> <button id="menu_state_1" class="color_4" rel="tooltip" data-state ="sidebar_icons" data-placement="top" data-original-title="Icon Menu">1</button> <button id="menu_state_2" class="color_4 active" rel="tooltip" data-state ="sidebar_default" data-placement="top" data-original-title="Fixed Menu">2</button> <button id="menu_state_3" class="color_4" rel="tooltip" data-placement="top" data-state ="sidebar_hover" data-original-title="Floating on Hover Menu">3</button> </div> </div> <!-- End sidebar_box --> </div> </div> </div> <div id="main"> <div class="container"> <div class="header row-fluid"> <div class="logo"> <a href="index.html"><span>Sonde de test 1</span><span class="icon"></span></a> </div> <div class="top_right"> <ul class="nav nav_menu"> <li class="dropdown"> <a class="dropdown-toggle administrator" id="dLabel" role="button" data-toggle="dropdown" data-target="#" href="/page.html"> <div class="title"><span class="name">George</span><span class="subtitle">Future Buyer</span></div> <span class="icon"><img src="img/thumbnail_george.jpg"></span></a> <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel"> <li><a href="profile.html"><i class=" icon-user"></i> My Profile</a></li> <li><a href="forms_general.html"><i class=" icon-cog"></i>Settings</a></li> <li><a href="index2.html"><i class=" icon-unlock"></i>Log Out</a></li> <li><a href="search.html"><i class=" icon-flag"></i>Help</a></li> </ul> </li> </ul> </div> <!-- End top-right --> </div> <div id="main_container"> <div class="row-fluid"> <div class="span12 "> <div class="box title_big height_big paint_hover" style="padding:10px;background-color:#222;"> <div id="chart" style="width:98%;height:98%;margin:10px;"></div> </div> </div> </div> </div> <!-- End .row-fluid --> <div class="row-fluid"> <div class="row-fluid box color_2 title_medium height_medium2 bar_stats paint_hover "> <div class="title hidden-phone"> <h5><span>Statistiques</span></h5> </div> <!-- End .title --> <div class="content row-fluid fluid numbers"> <div class="span3 stats hidden-phone"> <div style="width: 100%; height: 65px; margin-top: 7px; padding: 0px; position: relative;" id="placeholder3"><canvas class="base" width="310" height="65"></canvas><canvas class="overlay" width="310" height="65" style="position: absolute; left: 0px; top: 0px;"></canvas></div> </div> <div class="span2 average_ctr"> <h1 class="value">+ 15<span class="percent">%</span></h1> <div class="description mt15">tendance en hausse</div> </div> <div class="span4 shown_left" style="border-right: 1px dashed rgba(0, 0, 0, 0.2);"> <div class="row-fluid fluid"> <div class="span6"> <div class="description">Max</div> <h2 class="value">155 di(s)</h2> <div class="progress small"> <div style="width: 100%;" class="bar white"></div> </div> <div class="description">Valeurs références</div> </div> <div class="span6 full" style="padding-right:10px"> <div class="description text_color_dark">Min</div> <h2 class="value text_color_dark">15 di(s)</h2> <div class="progress small"> <div style="width: 0%;" class="bar "></div> </div> </div> </div> </div> <div class="span2 total_days"> <div class="row-fluid"> <div class="span12 total_clicks" style="text-align:center"> <h1 class="value">103</h1> <div class="description mt15">di(s) sur la période</div> </div> </div> </div> <div class="span1 stick top right result height_medium2"> <img src="img/arrows_up.png"> <div class="description mt15">Good</div> </div> </div> <!-- End .row-fluid --> <!-- End .content --> <a class="change_color_outside"><i class="paint_bucket"></i></a></div> <!-- End .box --> </div> </div> <!-- End .row-fluid --> <div class="row-fluid"> <div class="span6"> <div class="box color_3"> <table class="table table-bordered table-striped" id="sorting-advanced"> <thead> <tr> <th scope="col">Date de la valeur</th> <th scope="col" width="60" class="align-center">Valeur</th> <th scope="col" width="60" class="align-center">Variation</th> <th scope="col" width="60" class="align-center">Tendance</th> <th scope="col" width="150" class="align-center">Status</th> </tr> </thead> <tbody> <tr> <td>05/01/2013</td> <td class="align-center">16 di</td> <td class="align-center">-68%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>04/01/2013</td> <td class="align-center">50 di</td> <td class="align-center">+100%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag orange-bg">Grande variation!</span></td> </tr> <tr> <td>03/01/2013</td> <td class="align-center">25 di</td> <td class="align-center">+0%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-stable.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>02/01/2013</td> <td class="align-center">25 di</td> <td class="align-center">+257%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag orange-bg">Grande variation!</span></td> </tr> <tr> <td>01/01/2013</td> <td class="align-center">7 di</td> <td class="align-center">-46%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>31/12/2012</td> <td class="align-center">13 di</td> <td class="align-center">-7%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>30/12/2012</td> <td class="align-center">14 di</td> <td class="align-center">+27%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>29/12/2012</td> <td class="align-center">11 di</td> <td class="align-center">-62%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>28/12/2012</td> <td class="align-center">29 di</td> <td class="align-center">+4%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>27/12/2012</td> <td class="align-center">28 di</td> <td class="align-center">-10%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> </tbody> </table> </div> </div> <div class="span6"> <div class="box color_3"> <table class="table table-bordered table-striped" id="sorting-advanced"> <thead> <tr> <th scope="col">Date de la valeur</th> <th scope="col" width="60" class="align-center">Valeur</th> <th scope="col" width="60" class="align-center">Variation</th> <th scope="col" width="60" class="align-center">Tendance</th> <th scope="col" width="150" class="align-center">Status</th> </tr> </thead> <tbody> <tr> <td>05/01/2013</td> <td class="align-center">16 di</td> <td class="align-center">-68%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>04/01/2013</td> <td class="align-center">50 di</td> <td class="align-center">+100%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag orange-bg">Grande variation!</span></td> </tr> <tr> <td>03/01/2013</td> <td class="align-center">25 di</td> <td class="align-center">+0%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-stable.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>02/01/2013</td> <td class="align-center">25 di</td> <td class="align-center">+257%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag orange-bg">Grande variation!</span></td> </tr> <tr> <td>01/01/2013</td> <td class="align-center">7 di</td> <td class="align-center">-46%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>31/12/2012</td> <td class="align-center">13 di</td> <td class="align-center">-7%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>30/12/2012</td> <td class="align-center">14 di</td> <td class="align-center">+27%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>29/12/2012</td> <td class="align-center">11 di</td> <td class="align-center">-62%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>28/12/2012</td> <td class="align-center">29 di</td> <td class="align-center">+4%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-up.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> <tr> <td>27/12/2012</td> <td class="align-center">28 di</td> <td class="align-center">-10%</td> <td class="align-center"><img src="/monitoringU/web/img/arrow-down.png" style="height:20px;" align="absmiddle"/></td> <td class="align-center"><span class="tag green-bg">Ok</span></td> </tr> </tbody> </table> </div> </div> </div> <!-- End .row-fluid --> </div> <!-- End #container --> </div> <div id="footer"> <p> &copy; Tellaw.org </p> <span class="company_logo"><a href="http://www.pixelgrade.com"></a></span> </div> </div> <div class="background_changer dropdown"> <div class="dropdown" id="colors_pallete"> <a data-toggle="dropdown" data-target="drop4" class="change_color"></a> <ul class="dropdown-menu pull-left" role="menu" aria-labelledby="drop4"> <li><a data-color="color_0" class="color_0" tabindex="-1">1</a></li> <li><a data-color="color_1" class="color_1" tabindex="-1">1</a></li> <li><a data-color="color_2" class="color_2" tabindex="-1">2</a></li> <li><a data-color="color_3" class="color_3" tabindex="-1">3</a></li> <li><a data-color="color_4" class="color_4" tabindex="-1">4</a></li> <li><a data-color="color_5" class="color_5" tabindex="-1">5</a></li> <li><a data-color="color_6" class="color_6" tabindex="-1">6</a></li> <li><a data-color="color_7" class="color_7" tabindex="-1">7</a></li> <li><a data-color="color_8" class="color_8" tabindex="-1">8</a></li> <li><a data-color="color_9" class="color_9" tabindex="-1">9</a></li> <li><a data-color="color_10" class="color_10" tabindex="-1">10</a></li> <li><a data-color="color_11" class="color_11" tabindex="-1">10</a></li> <li><a data-color="color_12" class="color_12" tabindex="-1">12</a></li> <li><a data-color="color_13" class="color_13" tabindex="-1">13</a></li> <li><a data-color="color_14" class="color_14" tabindex="-1">14</a></li> <li><a data-color="color_15" class="color_15" tabindex="-1">15</a></li> <li><a data-color="color_16" class="color_16" tabindex="-1">16</a></li> <li><a data-color="color_17" class="color_17" tabindex="-1">17</a></li> <li><a data-color="color_18" class="color_18" tabindex="-1">18</a></li> <li><a data-color="color_19" class="color_19" tabindex="-1">19</a></li> <li><a data-color="color_20" class="color_20" tabindex="-1">20</a></li> <li><a data-color="color_21" class="color_21" tabindex="-1">21</a></li> <li><a data-color="color_22" class="color_22" tabindex="-1">22</a></li> <li><a data-color="color_23" class="color_23" tabindex="-1">23</a></li> <li><a data-color="color_24" class="color_24" tabindex="-1">24</a></li> <li><a data-color="color_25" class="color_25" tabindex="-1">25</a></li> </ul> </div> </div> <!-- End .background_changer --> </div> <!-- /container --> <!-- Le javascript ================================================== --> <!-- General scripts --> <script src="js/jquery.js" type="text/javascript"> </script> <!--[if !IE]> --> <!--[if !IE]> --> <script src="js/plugins/enquire.min.js" type="text/javascript"></script> <!-- <![endif]--> <!-- <![endif]--> <!--[if lt IE 7]> <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE7.js"></script> <![endif]--> <script language="javascript" type="text/javascript" src="js/plugins/jquery.sparkline.min.js"></script> <script src="js/plugins/excanvas.compiled.js"></script> <script src="js/bootstrap-transition.js" type="text/javascript"></script> <script src="js/bootstrap-alert.js" type="text/javascript"></script> <script src="js/bootstrap-modal.js" type="text/javascript"></script> <script src="js/bootstrap-dropdown.js" type="text/javascript"></script> <script src="js/bootstrap-scrollspy.js" type="text/javascript"></script> <script src="js/bootstrap-tab.js" type="text/javascript"></script> <script src="js/bootstrap-tooltip.js" type="text/javascript"></script> <script src="js/bootstrap-popover.js" type="text/javascript"></script> <script src="js/bootstrap-button.js" type="text/javascript"></script> <script src="js/bootstrap-collapse.js" type="text/javascript"></script> <script src="js/bootstrap-carousel.js" type="text/javascript"></script> <script src="js/bootstrap-typeahead.js" type="text/javascript"></script> <script src="js/bootstrap-affix.js" type="text/javascript"></script> <script src="js/fileinput.jquery.js" type="text/javascript"></script> <script src="js/jquery-ui-1.8.23.custom.min.js" type="text/javascript"></script> <script src="js/jquery.touchdown.js" type="text/javascript"></script> <script language="javascript" type="text/javascript" src="js/plugins/jquery.uniform.min.js"></script> <script language="javascript" type="text/javascript" src="js/plugins/jquery.tinyscrollbar.min.js"></script> <script language="javascript" type="text/javascript" src="js/jnavigate.jquery.min.js"></script> <script language="javascript" type="text/javascript" src="js/jquery.touchSwipe.min.js"></script> <script language="javascript" type="text/javascript" src="js/plugins/jquery.peity.min.js"></script> <!-- Flot charts --> <script language="javascript" type="text/javascript" src="js/plugins/flot/jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="js/plugins/flot/jquery.flot.resize.js"></script> <!-- Data tables --> <script type="text/javascript" language="javascript" src="js/plugins/datatables/js/jquery.dataTables.js"></script> <!-- Task plugin --> <script language="javascript" type="text/javascript" src="js/plugins/knockout-2.0.0.js"></script> <!-- Custom made scripts for this template --> <script src="js/scripts.js" type="text/javascript"></script> <script> var grahJsonUrl = ""; <!-- Graph JS --> // then fetch the data with jQuery monthNames: ["jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec"]; function onDataReceived(series) { var data = []; var options = { series: { lines: { show: true }, points: { show: true }, }, xaxis : { mode : "time", timeformat: "%d/%m" // Removed %y }, grid: { hoverable: true, clickable: true, color:"#FFF", borderWidth:0 }, legend: { show: true, margin: 10, backgroundOpacity: 0 } }; for(var i=0;i<series.graphics.length;i++) { data.push (series.graphics[i]); } // and plot all we got $.plot( $("#chart"), data, options); } function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #FAA', padding: '2px', 'background-color': '#FFF', 'z-index':'99', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#chart").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); var d = new Date(item.datapoint[0]); showTooltip(item.pageX, item.pageY, item.series.label + "<br/>Date : " + d.getUTCDate() + "/" + (d.getUTCMonth()+1 ) + "<br/>Valeur :" + y); } } else { $("#tooltip").remove(); previousPoint = null; } }); $("#chart").bind("plotclick", function (event, pos, item) { if (item) { $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + "."); plot.highlight(item.series, item.datapoint); } }); $(document).ready( function(){ $.ajax({ url: "/monitoringU/web/app_dev.php/ajax/graph-monitor-json/1", method: 'GET', dataType : 'json', success: onDataReceived }); } ); </script> </body> </html>
tellaw/monitor4u
_template_metro/monitor.html
HTML
mit
26,772
package com.github.felixgail.gplaymusic.exceptions; public class RemoteException extends RuntimeException { public RemoteException(String msg) { super(msg); } public RemoteException(Exception e) { super(e); } }
FelixGail/gplaymusic
src/main/java/com/github/felixgail/gplaymusic/exceptions/RemoteException.java
Java
mit
245
# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = openmmtools SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
choderalab/openmmtools
docs/Makefile
Makefile
mit
608
package de.silef.service.file.tree; import java.io.IOException; /** * Created by sebastian on 17.09.16. */ public class Visitor<T> { public enum VisitorResult { CONTINUE, /** * Skip current node. If returned from preVisitDirectory, postVisitDirectory it not called */ SKIP, /** * Skip following siblings. The walker should walk depth first. So nested directories are walked first. */ SKIP_SIBLINGS, /** * Terminate walk immediately. postVisitDirectory is not called */ TERMINATE } /** * Enter current directory * * @param dir Current directory * @return If SKIP is returned, no further action for this subbranch will be taken * @throws IOException */ public VisitorResult preVisitDirectory(T dir) throws IOException { return VisitorResult.CONTINUE; } public VisitorResult visitFile(T file) throws IOException { return VisitorResult.CONTINUE; } public VisitorResult postVisitDirectory(T dir) throws IOException { return VisitorResult.CONTINUE; } }
xemle/fileindex
src/main/java/de/silef/service/file/tree/Visitor.java
Java
mit
1,155
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; class uzsakymasIdType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('id'); } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'AppBundle\Entity\uzsakymas' )); } }
Padariukas/vezejai
src/AppBundle/Form/uzsakymasIdType.php
PHP
mit
747
.slider { height: 100%; } .slider-slide { padding-top: 80px; color: #000; background-color: #fff; text-align: center; font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: 300; } #logo { margin: 30px 0px; } #list { width: 170px; margin: 30px auto; font-size: 20px; } #list ol { margin-top: 30px; } #list ol li { text-align: left; list-style: decimal; margin: 10px 0px; } .country { fill: #E7E7E7; stroke: none; } .country-boundary { fill: none; stroke: #999; } .region { stroke: none; } .region-boundary { fill: none; stroke: #424242; stroke-dasharray: 2 2; stroke-linejoin: round; opacity: 0.5; } .ukraine-boundary { fill: none; stroke: #333; } .river { fill: none; stroke: #fff; } .lake { fill: #fff; stroke: none; } #map { width: 100%; margin: auto; } .score { position: absolute; top: 1%; right: 1%; } invader { position: absolute; top: 1%; left: 1%; font-size: 14vh; width: 16vh; height: 16vh; text-align: center; margin-top: 1vh; } defender { position: absolute; top: 1%; left: 1%; font-size: 14vh; width: 16vh; height: 16vh; text-align: center; margin-top: 1vh; } #i_example { visibility: hidden; position: absolute; top: 1%; left: 1%; font-size: 8vh; width: 16vh; height: 16vh; text-align: center; margin-top: 1vh; } .circle { width: 16vh; height: 16vh; background: red; -moz-border-radius: 8vh; -webkit-border-radius: 8vh; border-radius: 8vh; } defender .circle { width: 16vh; height: 16vh; background: green; -moz-border-radius: 8vh; -webkit-border-radius: 8vh; border-radius: 8vh; } /* .invader-show-hide { -webkit-transition: all linear 0.5s; transition: all linear 0.5s; } .invader-show-hide.ng-hide { opacity: 0; } .defender-show-hide { -webkit-transition: all linear 0.5s; transition: all linear 0.5s; } .defender-show-hide.ng-hide { opacity: 0; } */ .invader-flag { width: 10vh; height: 6vh; position: absolute; top: 2%; left: 2%; background-image: url(/img/125px-Flag_of_Russia.svg.png); background-size: contain; } .center{ text-align:center; }
tairezzzz/defu-ionic-box
www/css/style.css
CSS
mit
2,396
from django import template from django.utils.encoding import smart_str from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models import get_model from django.db.models.query import QuerySet register = template.Library() class GroupURLNode(template.Node): def __init__(self, view_name, group, kwargs, asvar): self.view_name = view_name self.group = group self.kwargs = kwargs self.asvar = asvar def render(self, context): url = "" group = self.group.resolve(context) kwargs = {} for k, v in self.kwargs.items(): kwargs[smart_str(k, "ascii")] = v.resolve(context) if group: bridge = group.content_bridge try: url = bridge.reverse(self.view_name, group, kwargs=kwargs) except NoReverseMatch: if self.asvar is None: raise else: try: url = reverse(self.view_name, kwargs=kwargs) except NoReverseMatch: if self.asvar is None: raise if self.asvar: context[self.asvar] = url return "" else: return url class ContentObjectsNode(template.Node): def __init__(self, group_var, model_name_var, context_var): self.group_var = template.Variable(group_var) self.model_name_var = template.Variable(model_name_var) self.context_var = context_var def render(self, context): group = self.group_var.resolve(context) model_name = self.model_name_var.resolve(context) if isinstance(model_name, QuerySet): model = model_name else: app_name, model_name = model_name.split(".") model = get_model(app_name, model_name) context[self.context_var] = group.content_objects(model) return "" @register.tag def groupurl(parser, token): bits = token.contents.split() tag_name = bits[0] if len(bits) < 3: raise template.TemplateSyntaxError("'%s' takes at least two arguments" " (path to a view and a group)" % tag_name) view_name = bits[1] group = parser.compile_filter(bits[2]) args = [] kwargs = {} asvar = None if len(bits) > 3: bits = iter(bits[3:]) for bit in bits: if bit == "as": asvar = bits.next() break else: for arg in bit.split(","): if "=" in arg: k, v = arg.split("=", 1) k = k.strip() kwargs[k] = parser.compile_filter(v) elif arg: raise template.TemplateSyntaxError("'%s' does not support non-kwargs arguments." % tag_name) return GroupURLNode(view_name, group, kwargs, asvar) @register.tag def content_objects(parser, token): """ {% content_objects group "tasks.Task" as tasks %} """ bits = token.split_contents() if len(bits) != 5: raise template.TemplateSyntaxError("'%s' requires five arguments." % bits[0]) return ContentObjectsNode(bits[1], bits[2], bits[4])
ericholscher/pinax
pinax/apps/groups/templatetags/group_tags.py
Python
mit
3,311
@if ($errors->any()) @include('_partials._error', ['level' => 'danger', 'title' => Session::get('title'), 'message' => $errors->all(':message')]) @endif @if ($message = Session::get('success')) @include('_partials._error', ['level' => 'success', 'title' => Session::get('title'), 'message' => $message]) @endif @if ($message = Session::get('warning')) @include('_partials._error', ['level' => 'warning', 'title' => Session::get('title'), 'message' => $message]) @endif @if ($message = Session::get('info')) @include('_partials._error', ['level' => 'info', 'title' => Session::get('title'), 'message' => $message]) @endif
Fixhub/Fixhub
resources/views/_partials/errors.blade.php
PHP
mit
623
/*---------------------------------------------------------------- Copyright (C) 2015 Senparc 文件名:RequestMessageLocation.cs 文件功能描述:接收普通地理位置消息 创建标识:Senparc - 20150211 修改标识:Senparc - 20150303 修改描述:整理接口 ----------------------------------------------------------------*/ namespace Senparc.Weixin.MP.Entities { public class RequestMessageLocation : RequestMessageBase, IRequestMessageBase { /// <summary> /// 地理位置纬度 /// </summary> public double Location_X { get; set; } /// <summary> /// 地理位置经度 /// </summary> public double Location_Y { get; set; } /// <summary> /// 地图缩放大小 /// </summary> public int Scale { get; set; } /// <summary> /// 地理位置信息 /// </summary> public string Label { get; set; } public override RequestMsgType MsgType { get { return RequestMsgType.Location; } } } }
timxing1987/git-tutorial
Source/Foundation/Wechat/Senparc.Weixin.MP/Entities/Request/RequestMessageLocation.cs
C#
mit
1,147
<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <style TYPE='text/css'> .highlighter .add { background-color: #7fff7f; } .highlighter .remove { background-color: #ff7f7f; } .highlighter td.modify { background-color: #7f7fff; } .highlighter td.conflict { background-color: #f00; } .highlighter .spec { background-color: #aaa; } .highlighter .move { background-color: #ffa; } .highlighter .null { color: #888; } .highlighter table { border-collapse:collapse; } .highlighter td, .highlighter th { border: 1px solid #2D4068; padding: 3px 7px 2px; } .highlighter th, .highlighter .header, .highlighter .meta { background-color: #aaf; font-weight: bold; padding-bottom: 4px; padding-top: 5px; text-align:left; } .highlighter tr.header th { border-bottom: 2px solid black; } .highlighter tr.index td, .highlighter .index, .highlighter tr.header th.index { background-color: white; border: none; } .highlighter .gap { color: #888; } .highlighter td { empty-cells: show; } </style> </head> <body> <div class='highlighter'> <table> <thead> <tr class="header"><th>@@</th><th>Class</th><th>ID</th><th>Severity</th><th>Ruleset(s)</th><th>Message</th><th>Description</th><th>Guidance</th><th>Context (Xpath)</th><th>...</th></tr> </thead> <tbody> <tr class="modify"><td class="modify">→</td><td>iati</td><td>0.0.1</td><td>Information</td><td>iati</td><td class="modify">Congratulations! This IATI activity file has successfully passed validation with no errors!→Congratulations! This IATI file has successfully passed validation with no errors!</td><td></td><td></td><td>/*</td><td>...</td></tr> <tr><td></td><td>iati</td><td>0.1.1</td><td>Critical</td><td>iati</td><td>The file is not a proper XML file. The raw feedback from xmllint: {unparsed-text("/workspace/tmp/xmltestlog/" || $filename)} (not possible to present, maybe a binary file)</td><td></td><td></td><td>/not-an-xml-file</td><td>...</td></tr> <tr class="gap"><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> <tr><td></td><td>financial</td><td>11.3.1</td><td>Error</td><td>iati</td><td>The budget line value date must be in the budget period.</td><td></td><td>https://drive.google.com/file/d/1mv2Q666tKBOAoiy5JayslmZNetxDM1uu/view</td><td>budget-line/value[@value-date]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>information</td><td>11.4.1</td><td>Error</td><td>iati</td><td>The last-updated-datetime of the organisation must not be in the future.</td><td></td><td class="modify">https://drive.google.com/file/d/1-R-xGMCrAKiadMBIHsNc4Xvl75CB0IV1/view→</td><td>iati-organisation</td><td>...</td></tr> <tr><td></td><td>geo</td><td>12.1.1</td><td>Error</td><td>iati:2.03</td><td>The percentage must be between 0.0 and 100.0 (inclusive).</td><td></td><td>https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view</td><td>(recipient-country|recipient-region)[@percentage]</td><td>...</td></tr> <tr><td></td><td>geo</td><td>12.1.2</td><td>Error</td><td>iati:&lt; 2.03</td><td>The percentage must be 0.0 or positive.</td><td></td><td>https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view</td><td>(recipient-country|recipient-region)[@percentage]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>financial</td><td>12.2.1</td><td>Error</td><td>iati:2.03</td><td>The percentage must be between 0.0 and 100.0 (inclusive).</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/capital-spend/')→{me:iati-url('activity-standard/iati-activities/iati-activity/capital-spend/')}</td><td>(capital-spend|budget-item)[@percentage]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>financial</td><td>12.2.2</td><td>Error</td><td>iati:&lt; 2.03</td><td>The percentage must be 0.0 or positive.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/capital-spend/')→{me:iati-url('activity-standard/iati-activities/iati-activity/capital-spend/')}</td><td>(capital-spend|budget-item)[@percentage]</td><td>...</td></tr> <tr><td></td><td>classifications</td><td>12.3.1</td><td>Error</td><td>iati:2.03</td><td>The percentage must be between 0.0 and 100.0 (inclusive).</td><td></td><td>https://drive.google.com/file/d/1GNnjeqDIyWwuuIkJ8pMjLhE99R_olSJP/view</td><td>sector[@percentage]</td><td>...</td></tr> <tr class="gap"><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> <tr><td></td><td>classifications</td><td>2.1.1</td><td></td><td></td><td>Percentages are missing for one or more sectors, within a vocabulary (e.g. 1 - OECD DAC).</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/1GNnjeqDIyWwuuIkJ8pMjLhE99R_olSJP/view)}</td><td>iati-activity[sector]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>classifications</td><td>2.1.2</td><td></td><td></td><td class="modify">Percentages for sectors, within a vocabulary (e.g. 1 - OECD DAC) must add up to 100%.→Percentages for sectors, within a vocabulary (e.g. 1 - OECD DAC), must add up to 100%.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/1GNnjeqDIyWwuuIkJ8pMjLhE99R_olSJP/view)}</td><td>iati-activity[sector]</td><td>...</td></tr> <tr><td></td><td>classifications</td><td>2.1.4</td><td></td><td></td><td>For a single sector, the percentage must either be omitted, or set to 100.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/1GNnjeqDIyWwuuIkJ8pMjLhE99R_olSJP/view)}</td><td>iati-activity[sector]</td><td>...</td></tr> <tr class="gap"><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> <tr><td></td><td>geo</td><td>3.1.1</td><td></td><td>2.0x</td><td>Percentages are missing for one or more recipient countries.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view)}</td><td>iati-activity[(recipient-country and not(recipient-region))]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>geo</td><td>3.1.2</td><td></td><td>2.0x</td><td class="modify">Percentages for recipient countries must add up to 100%.→Percentages for recipient countries, must add up to 100%.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view)}</td><td>iati-activity[(recipient-country and not(recipient-region))]</td><td>...</td></tr> <tr><td></td><td>geo</td><td>3.1.4</td><td></td><td>2.0x</td><td>For a single recipient country, the percentage must either be omitted, or set to 100.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view)}</td><td>iati-activity[(recipient-country and not(recipient-region))]</td><td>...</td></tr> <tr><td></td><td>geo</td><td>3.4.1</td><td></td><td>2.0x</td><td>Percentages are missing for one or more recipient countries or regions.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view)}</td><td>iati-activity[recipient-region]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>geo</td><td>3.4.2</td><td></td><td>2.0x</td><td class="modify">Percentages for recipient countries or regions must add up to 100%.→Percentages for recipient countries or regions, must add up to 100%.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view)}</td><td>iati-activity[recipient-region]</td><td>...</td></tr> <tr><td></td><td>geo</td><td>3.4.4</td><td></td><td>2.0x</td><td>For a single recipient country or region, the percentage must either be omitted, or set to 100.</td><td></td><td>{me:iati-url(https://drive.google.com/file/d/18P3vSUKK2iWCnXCrORDVAHR8K_EIg8Pp/view)}</td><td>iati-activity[recipient-region]</td><td>...</td></tr> <tr class="gap"><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> <tr><td></td><td>information</td><td>4.1.1</td><td>Error</td><td>iati</td><td>The activity should specify a default language, or the language must be specified for each narrative element.</td><td></td><td>{me:iati-url('codelists/Language/')}</td><td>iati-activity</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>information</td><td>4.3.1</td><td>Error</td><td></td><td>The title has no narrative content.</td><td></td><td class="modify">me:iati-url('{activity-standard/iati-activities/iati-activity/title/}')→{me:iati-url('{activity-standard/iati-activities/iati-activity/title/}')}</td><td>title</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>information</td><td>4.4.1</td><td>Error</td><td></td><td>The description has no narrative content.</td><td></td><td class="modify">me:iati-url('{activity-standard/iati-activities/iati-activity/title/}')→{me:iati-url('{activity-standard/iati-activities/iati-activity/title/}')}</td><td>description</td><td>...</td></tr> <tr><td></td><td>organisation</td><td>4.5.1</td><td>Error</td><td>iati</td><td>The organisation should specify a default language, or the language should be specified for each narrative element.</td><td></td><td>{me:iati-url('codelists/Language/')}</td><td>iati-organisation</td><td>...</td></tr> <tr class="gap"><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> <tr><td></td><td>financial</td><td>7.5.2</td><td>Error</td><td>iati</td><td>Budget Value must include a Value Date.</td><td></td><td>https://drive.google.com/file/d/1vB3vk7gbnADwG1S8A1bRDd8mK-nOfwCh/view?usp=drive_open</td><td>budget</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>financial</td><td>7.5.3</td><td>Error</td><td>iati</td><td>Budget Period must not be longer than one year.</td><td></td><td class="modify">https://drive.google.com/file/d/1vB3vk7gbnADwG1S8A1bRDd8mK-nOfwCh/view?usp=drive_open→https://drive.google.com/file/d/1JhMfO-f3Mldrs15OMlHTAUF9KixTUq5G/view</td><td>budget|total-budget|total-expenditure|recipient-country-budget|recipient-region-budget|recipient-org-budget</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>financial</td><td>7.8.1</td><td>Error</td><td>iati</td><td>The Value must have a specified Currency, or the Activity must have a default Currency.</td><td></td><td class="modify">me:iati-url('codelists/Currency/')→{me:iati-url('codelists/Currency/')}</td><td>value|loan-status|forecast</td><td>...</td></tr> <tr><td></td><td>financial</td><td>7.9.1</td><td></td><td></td><td>Percentages are missing for one or more country budget items, within a vocabulary (e.g. 4 - Reporting Organisation).</td><td></td><td>{me:iati-url(activity-standard/iati-activities/iati-activity/country-budget-items/budget-item/)}</td><td>iati-activity[country-budget-items]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>financial</td><td>7.9.2</td><td></td><td></td><td class="modify">Percentages for country budget items, within a vocabulary (e.g. 4 - Reporting Organisation) must add up to 100%.→Percentages for country budget items, within a vocabulary (e.g. 4 - Reporting Organisation), must add up to 100%.</td><td></td><td>{me:iati-url(activity-standard/iati-activities/iati-activity/country-budget-items/budget-item/)}</td><td>iati-activity[country-budget-items]</td><td>...</td></tr> <tr><td></td><td>financial</td><td>7.9.4</td><td></td><td></td><td>For a single country budget item, the percentage must either be omitted, or set to 100.</td><td></td><td>{me:iati-url(activity-standard/iati-activities/iati-activity/country-budget-items/budget-item/)}</td><td>iati-activity[country-budget-items]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.10.1</td><td>Error</td><td>iati:2.03</td><td>The actual must have a value when indicator measure is unit (1), percentage (2), nominal (3) or ordinal (4).</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/actual/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/actual/')}</td><td>actual[../../@measure=('1', '2', '3', '4')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.10.2</td><td>Warning</td><td>iati:2.03</td><td>The @value should be a valid number for all non-qualitative measures.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/actual/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/actual/')}</td><td>actual[../../@measure=('1', '2', '3', '4')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.10.3</td><td>Warning</td><td>iati:2.03</td><td>The @value should be omitted for qualitative measures.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/actual/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/actual/')}</td><td>actual[../../@measure=('5')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.11.1</td><td>Error</td><td>iati</td><td>If a result has a reference code, the indicator must not have a reference code.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/reference/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/reference/')}</td><td>indicator[reference]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.6.1</td><td>Error</td><td>iati</td><td>The start of the period must be before the end of the period.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/period-start/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/period-start/')}</td><td>period</td><td>...</td></tr> <tr><td></td><td>financial</td><td>8.6.3</td><td>Error</td><td>iati</td><td>The start of the period must be before the end of the period.</td><td></td><td>https://drive.google.com/file/d/1mv2Q666tKBOAoiy5JayslmZNetxDM1uu/view</td><td>budget|total-budget|total-expenditure|recipient-org-budget|recipient-country-budget|recipient-region-budget|planned-disbursement</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.8.1</td><td>Error</td><td>iati:2.03</td><td>The baseline must have a value when indicator measure is unit (1), percentage (2), nominal (3) or ordinal (4).</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/baseline/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/baseline/')}</td><td>baseline[../@measure=('1', '2', '3', '4')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.8.2</td><td>Warning</td><td>iati:2.03</td><td>The @value should be a valid number for all non-qualitative measures.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/baseline/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/baseline/')}</td><td>baseline[../@measure=('1', '2', '3', '4')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.8.3</td><td>Warning</td><td>iati:2.03</td><td>The @value should be omitted for qualitative measures.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/baseline/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/baseline/')}</td><td>baseline[../@measure=('5')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.9.1</td><td>Error</td><td>iati:2.03</td><td>The target must have a value when indicator measure is unit (1), percentage (2), nominal (3) or ordinal (4).</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/target/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/target/')}</td><td>target[../../@measure=('1', '2', '3', '4')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.9.2</td><td>Warning</td><td>iati:2.03</td><td>The @value should be a valid number for all non-qualitative measures.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/target/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/target/')}</td><td>target[../../@measure=('1', '2', '3', '4')]</td><td>...</td></tr> <tr class="modify"><td class="modify">→</td><td>performance</td><td>8.9.3</td><td>Warning</td><td>iati:2.03</td><td>The @value should be omitted for qualitative measures.</td><td></td><td class="modify">me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/target/')→{me:iati-url('activity-standard/iati-activities/iati-activity/result/indicator/period/target/')}</td><td>target[../../@measure=('5')]</td><td>...</td></tr> <tr><td></td><td>iati</td><td>9.1.1</td><td>Error</td><td>iati</td><td>The IATI version of the dataset is not a valid version number.</td><td></td><td>{me:iati-url('codelists/Version/')}</td><td>//iati-activities/@version</td><td>...</td></tr> <tr class="gap"><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> </tbody> </table> </div> </body> </html>
IATI/IATI-Rulesets
docs/updated-rules-1.0-beta-2.html
HTML
mit
17,979
<?php /** * This file is a part of scoringline sendinblue api package * * (c) Scoringline <m.veber@scoringline.com> * * For the full license, take a look to the LICENSE file * on the root directory of this project */ namespace Scoringline\SendinblueApi\Exception; /** * Class EmailSendFailureException * @package Scoringline\SendinblueApi\Exception * @author Joni Rajput <joni@sendinblue.com> */ class EmailSendFailureException extends \Exception { }
ScoringLine/SendinblueApi
src/Scoringline/SendinblueApi/Exception/EmailSendFailureException.php
PHP
mit
465