repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
andyvand/apple-dev
bin/generate_apple_dev_center_config.rb
1777
#!/usr/bin/ruby require 'optparse' require 'ostruct' require 'rubygems' require 'encrypted_strings' require 'yaml' # Set default options. opts = OpenStruct.new opts.login = '' opts.password = '' opts.secret_key = '' opts.teamid = '' opts.teamname = '' # Specify options. options = OptionParser.new do |options| options.banner = "Usage: #{File.basename($0)} [options]\nGenerates a YAML config file for apple_dev_center.rb" options.separator 'Mandatory options:' options.on('-l', '--login LOGIN', 'Login e-mail address') {|l| opts.login = l} options.on('-p', '--password PASS', 'Login password') {|p| opts.password = p} options.separator 'Optional options:' options.on('-t', '--team-id TID', 'Team ID - The team ID from the Multiple Developer Programs') {|t| opts.teamid = t} options.on('-T', '--team-name TEAMNAME', 'Team name - The team name from the Multiple Developer Programs') {|n| opts.teamname = n} options.on('-s', '--secret-key SECRET-KEY', 'Secret key') {|s| opts.secret_key = s} options.separator 'General options:' options.on_tail('-h', '--help', 'Show this message') do puts options exit end end # Show usage if no arguments are given. if ARGV.empty? puts options exit end # Parse options. begin options.parse! rescue puts options exit 1 end crypted_password = opts.password.encrypt(:symmetric, :password => opts.secret_key).to_s data={} data['default'] = opts.login # Force to string encrypted = '' + crypted_password # Remove trailing carriage return characters (\n, \r, and \r\n) encrypted = encrypted.chomp() account = {} account['login'] = opts.login account['password'] = encrypted account['teamid'] = opts.teamid account['teamname'] = opts.teamname data['accounts'] = [account] s = YAML::dump(data) puts s
mit
ringcentral/ringcentral-js-widget
packages/ringcentral-widgets/components/VideoPanel/i18n/en-GB.js
972
export default { schedule: "Schedule", topic: "Topic", date: "Date", startTime: "Start time", duration: "Duration", meetingSettings: "Meeting settings", rcMeetingSettings: "Video Meeting settings", joinBeforeHost: "Allow join before host", muteAudio: "Mute audio for participants", turnOffCamera: "Turn off camera for participants" }; // @key: @#@"schedule"@#@ @source: @#@"Schedule"@#@ // @key: @#@"topic"@#@ @source: @#@"Topic"@#@ // @key: @#@"date"@#@ @source: @#@"Date"@#@ // @key: @#@"startTime"@#@ @source: @#@"Start time"@#@ // @key: @#@"duration"@#@ @source: @#@"Duration"@#@ // @key: @#@"meetingSettings"@#@ @source: @#@"Meeting settings"@#@ // @key: @#@"rcMeetingSettings"@#@ @source: @#@"Video Meeting settings"@#@ // @key: @#@"joinBeforeHost"@#@ @source: @#@"Allow join before host"@#@ // @key: @#@"muteAudio"@#@ @source: @#@"Mute audio for participants"@#@ // @key: @#@"turnOffCamera"@#@ @source: @#@"Turn off camera for participants"@#@
mit
botstory/botstory
botstory/ast/callable.py
2640
from botstory.ast import stack_utils, story_context import logging from .. import matchers logger = logging.getLogger(__name__) @matchers.matcher() class WaitForReturn: type = 'WaitForReturn' def __init__(self): pass def validate(self, message): # return 'return' in message return True class EndOfStory: type = 'EndOfStory' def __init__(self, data={}): self.data = data class CallableNodeWrapper: """ helps start processing callable story """ def __init__(self, ast_node, library, processor): self.library = library self.ast_node = ast_node self.processor = processor async def startpoint(self, *args, **kwargs): if len(args) > 0: parent_ctx = args[0] session = parent_ctx['session'] user = parent_ctx['user'] else: if {'session', 'user'} > set(kwargs): raise AttributeError('Got {} and {}. Should pass session as well'.format(args, kwargs)) session = kwargs.pop('session') user = kwargs.pop('user') # we are going deeper so prepare one more item in stack logger.debug(' action: extend stack by +1') session = { **session, 'data': kwargs, 'stack': session['stack'] + [stack_utils.build_empty_stack_item(self.ast_node.topic)], } ctx = story_context.StoryContext(message={ 'session': session, # TODO: should get user from context 'user': user, }, library=self.library) ctx = await self.processor.process_story(ctx) ctx = story_context.reducers.scope_out(ctx) logger.debug('# result of callable') logger.debug(ctx) if isinstance(ctx.waiting_for, EndOfStory): return ctx.waiting_for.data # because we would like to return to stories from caller # we should return our context to callee return ctx class CallableStoriesAPI: def __init__(self, library, parser_instance, processor_instance): self.library = library self.parser_instance = parser_instance self.processor_instance = processor_instance def callable(self): def fn(callable_story): compiled_story = self.parser_instance.compile( callable_story, ) self.library.add_callable(compiled_story) return CallableNodeWrapper( compiled_story, self.library, self.processor_instance, ).startpoint return fn
mit
sstok/symfony
src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.php
6665
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bridge\Doctrine\Tests\DependencyInjection\CompilerPass; use PHPUnit\Framework\TestCase; use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; class RegisterEventListenersAndSubscribersPassTest extends TestCase { public function testExceptionOnAbstractTaggedSubscriber() { $container = $this->createBuilder(); $abstractDefinition = new Definition('stdClass'); $abstractDefinition->setAbstract(true); $abstractDefinition->addTag('doctrine.event_subscriber'); $container->setDefinition('a', $abstractDefinition); $this->process($container); $this->assertSame(array(), $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()); } public function testAbstractTaggedListenerIsSkipped() { $container = $this->createBuilder(); $abstractDefinition = new Definition('stdClass'); $abstractDefinition->setAbstract(true); $abstractDefinition->addTag('doctrine.event_listener', array('event' => 'test')); $container->setDefinition('a', $abstractDefinition); $this->process($container); $this->assertSame(array(), $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()); } public function testProcessEventListenersWithPriorities() { $container = $this->createBuilder(); $container ->register('a', 'stdClass') ->addTag('doctrine.event_listener', array( 'event' => 'foo', 'priority' => -5, )) ->addTag('doctrine.event_listener', array( 'event' => 'bar', )) ; $container ->register('b', 'stdClass') ->addTag('doctrine.event_listener', array( 'event' => 'foo', )) ; $this->process($container); $this->assertEquals(array('b', 'a'), $this->getServiceOrder($container, 'addEventListener')); $calls = $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls(); $this->assertEquals(array('foo', 'bar'), $calls[1][1][0]); } public function testProcessEventListenersWithMultipleConnections() { $container = $this->createBuilder(true); $container ->register('a', 'stdClass') ->addTag('doctrine.event_listener', array( 'event' => 'onFlush', )) ; $this->process($container); $callsDefault = $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls(); $this->assertEquals('addEventListener', $callsDefault[0][0]); $this->assertEquals(array('onFlush'), $callsDefault[0][1][0]); $callsSecond = $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls(); $this->assertEquals($callsDefault, $callsSecond); } public function testProcessEventSubscribersWithPriorities() { $container = $this->createBuilder(); $container ->register('a', 'stdClass') ->addTag('doctrine.event_subscriber') ; $container ->register('b', 'stdClass') ->addTag('doctrine.event_subscriber', array( 'priority' => 5, )) ; $container ->register('c', 'stdClass') ->addTag('doctrine.event_subscriber', array( 'priority' => 10, )) ; $container ->register('d', 'stdClass') ->addTag('doctrine.event_subscriber', array( 'priority' => 10, )) ; $container ->register('e', 'stdClass') ->addTag('doctrine.event_subscriber', array( 'priority' => 10, )) ; $this->process($container); $serviceOrder = $this->getServiceOrder($container, 'addEventSubscriber'); $unordered = array_splice($serviceOrder, 0, 3); sort($unordered); $this->assertEquals(array('c', 'd', 'e'), $unordered); $this->assertEquals(array('b', 'a'), $serviceOrder); } public function testProcessNoTaggedServices() { $container = $this->createBuilder(true); $this->process($container); $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls()); $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls()); } private function process(ContainerBuilder $container) { $pass = new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'); $pass->process($container); } private function getServiceOrder(ContainerBuilder $container, $method) { $order = array(); foreach ($container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls() as list($name, $arguments)) { if ($method !== $name) { continue; } if ('addEventListener' === $name) { $order[] = (string) $arguments[1]; continue; } $order[] = (string) $arguments[0]; } return $order; } private function createBuilder($multipleConnections = false) { $container = new ContainerBuilder(); $connections = array('default' => 'doctrine.dbal.default_connection'); $container->register('doctrine.dbal.default_connection.event_manager', 'stdClass'); $container->register('doctrine.dbal.default_connection', 'stdClass'); if ($multipleConnections) { $container->register('doctrine.dbal.second_connection.event_manager', 'stdClass'); $container->register('doctrine.dbal.second_connection', 'stdClass'); $connections['second'] = 'doctrine.dbal.second_connection'; } $container->setParameter('doctrine.connections', $connections); return $container; } }
mit
joelesko/tht
tht/lib/core/compiler/symbols/Template.php
104
<?php namespace o; class S_Template extends S_Function { var $type = SymbolType::NEW_TEMPLATE; }
mit
yangdw/PyRepo
src/project/robot/src/message/message_gen.py
4873
#coding:utf-8 """ 根据proto文件自动生成.py文件的脚本 """ import os # 配置区域 register_message = 'from sdk.net.message_table import register_message as register_message' register_message_number = 'from sdk.net.message_table import register_message_number as register_message_number' def read_proto_file(filename): """ 返回值:返回消息列表 读取proto文件,对proto文件有格式要求: 关键字(message,enum)和符号'}'前除了空格不允许有其他的字符串 """ message_name_list = [] nested_layer_count = 0 # 嵌套层数 fi = open(filename) raw_data = fi.readline() while raw_data: data = raw_data.strip() if data == '': raw_data = fi.readline() continue if data.startswith("message") or data.startswith("enum"): nested_layer_count += 1 if nested_layer_count == 1: if data.startswith("message"): # 只处理 message message_name_list.append(format_message_name(data)) elif data.startswith("}"): if nested_layer_count == 0: print 'error!!!!!!', raw_data elif nested_layer_count == 1: nested_layer_count = 0 else: nested_layer_count -= 1 raw_data = fi.readline() fi.close() if len(message_name_list) != 0: return message_name_list else: return None def format_message_name(message): """format message name""" first = message.split(' ')[1] second = first.split('{')[0] return second def gen_py_file_message(filename_base, message_name_list): """ 生成Python文件:注册消息对象 """ filename = filename_base+"_message.py" fi = open(filename, 'w') fi.write('# coding:utf-8\n') fi.write('\n') fi.write('import '+filename_base+'_pb2.py as '+filename_base+'\n') fi.write(register_message+'\n') fi.write('\n') fi.write('\n') for message_name in message_name_list: fi.write('@register_message\n') fi.write('def '+message_name+'():\n') fi.write(" return "+filename_base+"."+message_name+"\n") fi.write('\n') fi.write('\n') fi.close() def gen_py_file_message_number(filename_base, message_name_list): """ 生成Python文件:注册消息号 """ filename = filename_base+"_number.py" fi = open(filename, 'w') fi.write('# coding:utf-8\n') fi.write('\n') fi.write(register_message_number+'\n') fi.write('from message_config import message_number_table\n') fi.write('\n') fi.write('\n') for message_name in message_name_list: fi.write('@register_message_number\n') fi.write('def '+message_name+'():\n') fi.write(" if '"+message_name+"' in message_number_table:\n") fi.write(" return message_number_table['"+message_name+"']\n") fi.write(" return None\n") fi.write('\n') fi.write('\n') fi.close() def gen_py_file_message_config(message_name_list): """ 生成消息配置文件,根据需要一般只生成一次就行 """ try: from message_config import message_number_table except: message_number_table = {} filename = "message_config.py" fi = open(filename, 'w') fi.write('# coding:utf-8\n') fi.write('\n') length = len(message_name_list) if length == 0: return new_message_number_table = {} for item in message_name_list: if item in message_number_table: new_message_number_table[item] = message_number_table[item] else: new_message_number_table[item] = 0 count = 0 message_name = message_name_list[count] message_number = str(new_message_number_table[message_name]) count += 1 if length == 1: fi.write("message_number_table = {'"+message_name+"': "+message_number+"}\n") else: fi.write("message_number_table = {'"+message_name+"': "+message_number+",\n") while count < length-1: message_name = message_name_list[count] message_number = str(new_message_number_table[message_name]) count += 1 fi.write(" '"+message_name+"': "+message_number+",\n") message_name = message_name_list[count] message_number = str(new_message_number_table[message_name]) fi.write(" '"+message_name+"': "+message_number+"}\n") fi.close() if __name__ == "__main__": data = read_proto_file("./proto/HallMessage.proto") print data gen_py_file_message_number("HallMessage", data) #os.system("protoc --python_out=. HallMessage.proto") # 生成消息号配置文件 #gen_py_file_message_config(data)
mit
guotao2000/ecmall
temp/caches/0322/3822d88a4c85483a042f40425fe2e9e5.cache.php
220
<?php /** * @Created By ECMall PhpCacheServer * @Time:2015-01-26 16:09:55 */ if(filemtime(__FILE__) + 600 < time())return false; return array ( 'inbox' => '0', 'outbox' => '0', 'total' => 0, ); ?>
mit
halilagin/linguistics
kurjmorph/src/python/build/lib/kurdish/kurmanji/verb/inp/KJVPretaggerRunner.py
1004
#!/usr/bin/python import csv import sys import kurdish.kurmanji.verb.inp.KJVPretagger as KJVPretagger def run(cutoff_=10): tagnames=["VWishPresent","VWishPast","VImperative","VPresent","VFuture","VPast","VInfinitive"] for i in range(7): idx_=i tagname_=tagnames[i] kjvpretagger = KJVPretagger.KJVPretagger( indice=idx_, cutoff=cutoff_, tagname=tagname_, inputfile="/home/halil/root/linguistics/linguistics/kurjmorph/resources/python.data/kurmanji.verbs.csv", outputdir="/home/halil/root/linguistics/linguistics/kurjmorph/src/foma/fsts" ) kjvpretagger.dotag() def runPastTenseFomaGenerator(cutoff_=10,fileName="standartfile.txt"): kjvpretagger = KJVPretagger.KJVPretagger( indice=5, cutoff=cutoff_, tagname="", inputfile="/home/halil/root/linguistics/linguistics/kurjmorph/resources/python.data/kurmanji.verbs.csv", outputdir="/home/halil/root/linguistics/linguistics/kurjmorph/src/foma/fsts" ) kjvpretagger.doPastTenseVerbFoma(fileName)
mit
OceanDev/metrics
db/migrate/20151121085838_add_state_transition_reason.rb
388
class AddStateTransitionReason < ActiveRecord::Migration def change add_column :instances, :state_transition_reason, :string add_column :instances, :vpc_id, :string add_column :instances, :public_ip_address, :string add_column :instances, :security_groups, :text add_column :instances, :state_reason_message, :string end end
mit
comp523-w4g/vue-twitter-stream
src/js/services/helpers.js
887
export function debounce(func, wait, immediate) { let timeout return function(force) { let context = this let args = arguments let later = function() { timeout = null if (!immediate) { func.apply(context, args) } } let callNow = force || (immediate && !timeout) clearTimeout(timeout) if (callNow) { func.apply(context, args) } else { timeout = setTimeout(later, wait) } } } export function interval(func, wait) { let timeout return { start: function() { let context = this let args = arguments let later = function() { clearTimeout(timeout) func.apply(context, args) timeout = setTimeout(later, wait) } clearTimeout(timeout) timeout = setTimeout(later, wait) }, stop: function() { clearTimeout(timeout) } } }
mit
jenkinsci/jenkins
core/src/main/java/hudson/util/UnbufferedBase64InputStream.java
1972
package hudson.util; import java.io.DataInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Base64; /** * Filter InputStream that decodes base64 without doing any buffering. * * <p> * This is slower implementation, but it won't consume unnecessary bytes from the underlying {@link InputStream}, * allowing the reader to switch between the unencoded bytes and base64 bytes. * * @author Kohsuke Kawaguchi * @since 1.349 * @deprecated Use {@link java.util.Base64.Decoder#wrap}. */ @Deprecated public class UnbufferedBase64InputStream extends FilterInputStream { private byte[] encoded = new byte[4]; private byte[] decoded; private int pos; private final DataInputStream din; private static final Base64.Decoder decoder = Base64.getDecoder(); public UnbufferedBase64InputStream(InputStream in) { super(in); din = new DataInputStream(in); // initial placement to force the decoding in the next read() pos = 4; decoded = encoded; } @Override public int read() throws IOException { if (decoded.length == 0) return -1; // EOF if (pos == decoded.length) { din.readFully(encoded); decoded = decoder.decode(encoded); if (decoded.length == 0) return -1; // EOF pos = 0; } return decoded[pos++] & 0xFF; } @Override public int read(byte[] b, int off, int len) throws IOException { int i; for (i = 0; i < len; i++) { int ch = read(); if (ch < 0) break; b[off + i] = (byte) ch; } return i == 0 ? -1 : i; } @Override public long skip(long n) throws IOException { long r = 0; while (n > 0) { int ch = read(); if (ch < 0) break; n--; r++; } return r; } }
mit
microlv/vscode
src/vs/workbench/parts/experiments/test/electron-browser/experimentalPrompts.test.ts
6999
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { Emitter } from 'vs/base/common/event'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryService } from 'vs/platform/telemetry/common/telemetryUtils'; import { ExperimentalPrompts } from 'vs/workbench/parts/experiments/electron-browser/experimentalPrompt'; import { ExperimentActionType, ExperimentState, IExperiment, IExperimentActionPromptProperties, IExperimentService } from 'vs/workbench/parts/experiments/node/experimentService'; import { TestExperimentService } from 'vs/workbench/parts/experiments/test/electron-browser/experimentService.test'; import { TestLifecycleService } from 'vs/workbench/test/workbenchTestServices'; suite('Experimental Prompts', () => { let instantiationService: TestInstantiationService; let experimentService: TestExperimentService; let experimentalPrompt: ExperimentalPrompts; let onExperimentEnabledEvent: Emitter<IExperiment>; let storageData = {}; const promptText = 'Hello there! Can you see this?'; const experiment: IExperiment = { id: 'experiment1', enabled: true, state: ExperimentState.Run, action: { type: ExperimentActionType.Prompt, properties: { promptText, commands: [ { text: 'Yes', externalLink: 'https://code.visualstudio.com' }, { text: 'No' } ] } } }; suiteSetup(() => { instantiationService = new TestInstantiationService(); instantiationService.stub(ILifecycleService, new TestLifecycleService()); instantiationService.stub(ITelemetryService, NullTelemetryService); onExperimentEnabledEvent = new Emitter<IExperiment>(); }); setup(() => { storageData = {}; instantiationService.stub(IStorageService, { get: (a, b, c) => a === 'experiments.experiment1' ? JSON.stringify(storageData) : c, store: (a, b, c) => { if (a === 'experiments.experiment1') { storageData = JSON.parse(b); } } }); instantiationService.stub(INotificationService, new TestNotificationService()); experimentService = instantiationService.createInstance(TestExperimentService); experimentService.onExperimentEnabled = onExperimentEnabledEvent.event; instantiationService.stub(IExperimentService, experimentService); }); teardown(() => { if (experimentService) { experimentService.dispose(); } if (experimentalPrompt) { experimentalPrompt.dispose(); } }); test('Show experimental prompt if experiment should be run. Choosing option with link should mark experiment as complete', () => { storageData = { enabled: true, state: ExperimentState.Run }; instantiationService.stub(INotificationService, { prompt: (a: Severity, b: string, c: IPromptChoice[], options) => { assert.equal(b, promptText); assert.equal(c.length, 2); c[0].run(); } }); experimentalPrompt = instantiationService.createInstance(ExperimentalPrompts); onExperimentEnabledEvent.fire(experiment); return Promise.resolve(null).then(result => { assert.equal(storageData['state'], ExperimentState.Complete); }); }); test('Show experimental prompt if experiment should be run. Choosing negative option should mark experiment as complete', () => { storageData = { enabled: true, state: ExperimentState.Run }; instantiationService.stub(INotificationService, { prompt: (a: Severity, b: string, c: IPromptChoice[], options) => { assert.equal(b, promptText); assert.equal(c.length, 2); c[1].run(); } }); experimentalPrompt = instantiationService.createInstance(ExperimentalPrompts); onExperimentEnabledEvent.fire(experiment); return Promise.resolve(null).then(result => { assert.equal(storageData['state'], ExperimentState.Complete); }); }); test('Show experimental prompt if experiment should be run. Cancelling should mark experiment as complete', () => { storageData = { enabled: true, state: ExperimentState.Run }; instantiationService.stub(INotificationService, { prompt: (a: Severity, b: string, c: IPromptChoice[], options) => { assert.equal(b, promptText); assert.equal(c.length, 2); options.onCancel(); } }); experimentalPrompt = instantiationService.createInstance(ExperimentalPrompts); onExperimentEnabledEvent.fire(experiment); return Promise.resolve(null).then(result => { assert.equal(storageData['state'], ExperimentState.Complete); }); }); test('Test getPromptText', () => { const simpleTextCase: IExperimentActionPromptProperties = { promptText: 'My simple prompt', commands: [] }; const multipleLocaleCase: IExperimentActionPromptProperties = { promptText: { en: 'My simple prompt for en', de: 'My simple prompt for de', 'en-au': 'My simple prompt for Austrailian English', 'en-us': 'My simple prompt for US English' }, commands: [] }; const englishUSTextCase: IExperimentActionPromptProperties = { promptText: { 'en-us': 'My simple prompt for en' }, commands: [] }; const noEnglishTextCase: IExperimentActionPromptProperties = { promptText: { 'de-de': 'My simple prompt for German' }, commands: [] }; assert.equal(ExperimentalPrompts.getLocalizedText(simpleTextCase.promptText, 'any-language'), simpleTextCase.promptText); assert.equal(ExperimentalPrompts.getLocalizedText(multipleLocaleCase.promptText, 'en'), multipleLocaleCase.promptText['en']); assert.equal(ExperimentalPrompts.getLocalizedText(multipleLocaleCase.promptText, 'de'), multipleLocaleCase.promptText['de']); assert.equal(ExperimentalPrompts.getLocalizedText(multipleLocaleCase.promptText, 'en-au'), multipleLocaleCase.promptText['en-au']); assert.equal(ExperimentalPrompts.getLocalizedText(multipleLocaleCase.promptText, 'en-gb'), multipleLocaleCase.promptText['en']); assert.equal(ExperimentalPrompts.getLocalizedText(multipleLocaleCase.promptText, 'fr'), multipleLocaleCase.promptText['en']); assert.equal(ExperimentalPrompts.getLocalizedText(englishUSTextCase.promptText, 'fr'), englishUSTextCase.promptText['en-us']); assert.equal(!!ExperimentalPrompts.getLocalizedText(noEnglishTextCase.promptText, 'fr'), false); }); });
mit
hufeng/plume2
packages/plume2/cli/template/view-action/index.ts
87
import { ViewAction } from 'plume2'; export class AppViewAction extends ViewAction {}
mit
ifrsrg/apl
site/modules/admin/views/newsletter/news.php
5246
<table cellpadding="0" cellspacing="0" border="0" width="510" align="center"> <tr><td valign="top" style="font-size:0pt;"> <a href="{server_path}/" target="_blank"> <img src="{server_path}/media/newsletter/header2.jpg" width="601" border="0"> </a></td></tr> <tr><td valign="top" style="font-size:0pt;"> <a href="{server_path}/noticias" target="_blank"> <img src="{server_path}/media/newsletter/next-news.jpg" border="0"> </a> </td></tr> <!-- BEGIN NOTICIA --> <tr> <td valign="top" style="font-size:0pt;" align="center"> <table cellpadding="0" cellspacing="0" border="0" width="440" align="center"> <tr> <td valign="top" style="font-size:0pt;"> <a href="{server_path}/noticias/acao/detalhe/id/{noticia_id}" target="_blank" style="text-decoration:none;color:#000;"> <img src="{noticia_img}"> </a> </td> <td valign="top" style="font-size:0pt;"><img src="{server_path}/media/newsletter/pixel.gif" width="15"></td> <td valign="top" style="font-size:0pt;"> <table cellpadding="0" cellspacing="0" border="0" width="283" align="left"> <tr><td valign="top" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 16px; font-weight:bold" align="left"> <a href="{server_path}/noticias/acao/detalhe/id/{noticia_id}" target="_blank" style="text-decoration:none;color:#000;"> <b>{noticia_titulo}</b> </a> </td></tr> <tr><td valign="top" style="font-family: Arial, Helvetica, sans-serif; color: #934c20; font-size: 15px; font-weight:bold" align="left" height="28"><b>{noticia_data}</b></td></tr> <tr><td valign="top" style="font-family: Arial, Helvetica, sans-serif; color: #999999; font-size: 15px; " align="left">{noticia_texto}</td></tr> </table> </td> </tr> <!-- BEGIN NOTICIA_BREAK --> <tr><td valign="top" colspan="3" style="font-size:0pt;"><img src="{server_path}/media/newsletter/divisor.gif"></td></tr> <!-- END NOTICIA_BREAK --> </table> </td> </tr> <!-- END NOTICIA --> <tr><td valign="top" style="font-size:0pt;"><img src="{server_path}/media/newsletter/pixel.gif" height="59"></td></tr> <tr><td valign="top" style="font-size:0pt;"><a href="{server_path}/noticias" target="_blank"><img src="{server_path}/media/newsletter/bt-news.jpg" border="0"></a></td></tr> <tr><td valign="top" style="font-size:0pt;"><img src="{server_path}/media/newsletter/pixel.gif" height="59"></td></tr> <tr><td valign="top" style="font-size:0pt;"><a href="{server_path}/eventos" target="_blank"><img src="{server_path}/media/newsletter/next-events.jpg"></a></td></tr> <!-- BEGIN EVENTO --> <tr> <td valign="top" style="font-size:0pt;" align="center"> <table cellpadding="0" cellspacing="0" border="0" width="440" align="center"> <tr> <td valign="top" style="font-size:0pt;"> <a href="{server_path}/eventos/acao/detalhe/id/{evento_id}" target="_blank" style="text-decoration:none;color:#000;"> <img src="{evento_img}"> </a></td> <td valign="top" style="font-size:0pt;"><img src="{server_path}/media/newsletter/pixel.gif" width="15"></td> <td valign="top" style="font-size:0pt;"> <table cellpadding="0" cellspacing="0" border="0" width="283" align="left"> <tr><td valign="top" style="font-family: Arial, Helvetica, sans-serif; color: #000000; font-size: 16px; font-weight:bold" align="left"> <a href="{server_path}/eventos/acao/detalhe/id/{evento_id}" target="_blank" style="text-decoration:none;color:#000;"><b>{evento_titulo}</b></a></td></tr> <tr><td valign="top" style="font-family: Arial, Helvetica, sans-serif; color: #934c20; font-size: 15px; font-weight:bold" height="28" align="left"><b>{evento_data}</b></td></tr> <tr><td valign="top" style="font-family: Arial, Helvetica, sans-serif; color: #999999; font-size: 15px; " align="left">{evento_texto}</td></tr> </table> </td> </tr> <!-- BEGIN EVENTO_BREAK --> <tr><td valign="top" colspan="3" style="font-size:0pt;"><img src="{server_path}/media/newsletter/divisor.gif"></td></tr> <!-- END EVENTO_BREAK --> </table> </td> </tr> <!-- END EVENTO --> <tr><td valign="top" style="font-size:0pt;"><img src="{server_path}/media/newsletter/pixel.gif" height="59"></td></tr> <tr><td valign="top" style="font-size:0pt;"><a href="{server_path}/eventos" target="_blank"><img src="{server_path}/media/newsletter/bt-events.jpg" border="0"></a></td></tr> <tr><td valign="top" style="font-size:0pt;"><img src="{server_path}/media/newsletter/pixel.gif" height="59"></td></tr> <tr> <td valign="top" style="font-size:0pt;"> <table cellpadding="0" cellspacing="0" border="0" width="260" align="center"> <tr><td valign="top" style="font-family: Arial, Helvetica, sans-serif; color: #999999; font-size: 13px;" align="center"> </td></tr> </table> </td> </tr> <tr><td valign="top" style="font-size:0pt;"> <a href="http://www.furg.br/" target="_blank"> <img src="{server_path}/media/newsletter/furg.jpg" border="0"> </a> </td></tr> </table>
mit
aalhour/C-Sharp-Algorithms
Algorithms/Trees/BinaryTreeIterativeWalker.cs
592
namespace Algorithms.Trees { /// <summary> /// Simple Iterative Tree Traversal and Search Algorithms. /// </summary> public static class BinaryTreeIterativeWalker { /// <summary> /// Specifies the mode of travelling through the tree. /// </summary> public enum TraversalMode { InOrder = 0, PreOrder = 1, PostOrder = 2 } /************************************************************************************ * PRIVATE HELPERS SECTION * */ } }
mit
tsauerwein/mapfish-print
core/src/main/java/org/mapfish/print/output/JasperReportImageOutputFormat.java
3617
/* * Copyright (C) 2014 Camptocamp * * This file is part of MapFish Print * * MapFish Print is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MapFish Print is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MapFish Print. If not, see <http://www.gnu.org/licenses/>. */ package org.mapfish.print.output; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.export.JRGraphics2DExporter; import net.sf.jasperreports.engine.export.JRGraphics2DExporterParameter; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; /** * An PDF output format that uses Jasper reports to generate the result. * * @author Jesse * @author sbrunner */ public final class JasperReportImageOutputFormat extends AbstractJasperReportOutputFormat implements OutputFormat { private int imageType = BufferedImage.TYPE_INT_ARGB; private String fileSuffix; @Override public String getContentType() { return "image/" + this.fileSuffix; } public void setFileSuffix(final String fileSuffix) { this.fileSuffix = fileSuffix; } @Override public String getFileSuffix() { return this.fileSuffix; } @Override protected void doExport(final OutputStream outputStream, final Print print) throws JRException, IOException { JasperPrint jasperPrint = print.print; final int numPages = jasperPrint.getPages().size(); final double dpiRatio = print.dpi / print.requestorDpi; final int pageHeightOnImage = (int) ((jasperPrint.getPageHeight() + 1) * dpiRatio); final int pageWidthOnImage = (int) ((jasperPrint.getPageWidth() + 1) * dpiRatio); BufferedImage pageImage = new BufferedImage(pageWidthOnImage, numPages * pageHeightOnImage, this.imageType); Graphics2D graphics2D = pageImage.createGraphics(); graphics2D.scale(dpiRatio, dpiRatio); try { JRGraphics2DExporter exporter = new JRGraphics2DExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, graphics2D); for (int pageIndex = 0; pageIndex < numPages; pageIndex++) { exporter.setParameter(JRExporterParameter.PAGE_INDEX, pageIndex); exporter.exportReport(); graphics2D.setColor(Color.black); graphics2D.drawLine(0, pageHeightOnImage, pageWidthOnImage, pageHeightOnImage); graphics2D.translate(0, pageHeightOnImage); } } finally { graphics2D.dispose(); } ImageIO.write(pageImage, getFileSuffix(), outputStream); } /** * One of {@link java.awt.image.BufferedImage} TYPE_ values. * * @param imageType the buffered image type to create. */ public void setImageType(final int imageType) { this.imageType = imageType; } }
mit
anhstudios/swganh
data/scripts/templates/object/tangible/wearables/ithorian/shared_ith_jacket_s10.py
466
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/wearables/ithorian/shared_ith_jacket_s10.iff" result.attribute_template_id = 11 result.stfName("wearables_name","ith_jacket_s10") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
mit
tuka217/Sylius
src/Sylius/Bundle/SearchBundle/spec/Listener/OrmListenerSpec.php
1258
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\SearchBundle\Listener; use Doctrine\ORM\Event\LifecycleEventArgs; use PhpSpec\ObjectBehavior; use Sylius\Bundle\SearchBundle\Indexer\OrmIndexer; /** * @author Argyrios Gounaris <agounaris@gmail.com> */ final class OrmListenerSpec extends ObjectBehavior { function let(OrmIndexer $ormIndexer) { $this->beConstructedWith($ormIndexer); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\SearchBundle\Listener\OrmListener'); } function it_populates_the_insertion_array(LifecycleEventArgs $args) { $this->postPersist($args); $this->scheduledForInsertion->shouldBeArray(); } function it_populates_the_update_array(LifecycleEventArgs $args) { $this->postUpdate($args); $this->scheduledForInsertion->shouldBeArray(); } function it_populates_the_delete_array(LifecycleEventArgs $args) { $this->preRemove($args); $this->scheduledForDeletion->shouldBeArray(); } }
mit
azat-co/react-quickly
spare-parts/ch06-es5/add-sub/js/radio.js
1892
var Radio = React.createClass({ displayName: 'Radio', getInitialState() { let order = this.props.order; let i = 1; return { outerStyle: this.getStyle(4, i), innerStyle: this.getStyle(1, i), selectedStyle: this.getStyle(2, i), taggerStyle: { top: order * 20, width: 25, height: 25 } }; }, getStyle(i, m) { let value = i * m; return { top: value, bottom: value, left: value, right: value }; }, componentDidMount: function () { window.addEventListener('resize', this.handleResize); }, componentWillUnmount: function () { window.removeEventListener('resize', this.handleResize); }, handleResize: function (e) { let w = 1 + Math.round(window.innerWidth / 300); this.setState({ taggerStyle: { top: this.props.order * w * 10, width: w * 10, height: w * 10 }, textStyle: { left: w * 13, fontSize: 7 * w } }); }, render: function () { return React.createElement( 'div', null, React.createElement( 'div', { className: 'radio-tagger', style: this.state.taggerStyle }, React.createElement('input', { type: 'radio', name: this.props.name, id: this.props.id }), React.createElement( 'label', { htmlFor: this.props.id }, React.createElement( 'div', { className: 'radio-text', style: this.state.textStyle }, this.props.label ), React.createElement( 'div', { className: 'radio-outer', style: this.state.outerStyle }, React.createElement( 'div', { className: 'radio-inner', style: this.state.innerStyle }, React.createElement('div', { className: 'radio-selected', style: this.state.selectedStyle }) ) ) ) ) ); } });
mit
groupdocsconversion/GroupDocs_Conversion_NET
Examples/GroupDocs.Conversion.Examples.CSharp/BasicUsage/ConvertToPdf/ConvertVdxToPdf.cs
1181
using System; using System.IO; using GroupDocs.Conversion.Options.Convert; namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage { /// <summary> /// This example demonstrates how to convert VDX file into PDF format. /// For more details about Microsoft Visio XML Drawing File Format (.vdx) to Portable Document (.pdf) conversion please check this documentation article /// https://docs.groupdocs.com/conversion/net/convert-vdx-to-pdf /// </summary> internal static class ConvertVdxToPdf { public static void Run() { string outputFolder = Constants.GetOutputDirectoryPath(); string outputFile = Path.Combine(outputFolder, "vdx-converted-to.pdf"); // Load the source VDX file using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_VDX)) { var options = new PdfConvertOptions(); // Save converted PDF file converter.Convert(outputFile, options); } Console.WriteLine("\nConversion to pdf completed successfully. \nCheck output in {0}", outputFolder); } } }
mit
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Leaf/LookHeadBackType.php
812
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Leaf; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class LookHeadBackType extends AbstractTag { protected $Id = 'LookHead_back_type'; protected $Name = 'LookHeadBackType'; protected $FullName = 'Leaf::LookHeader'; protected $GroupName = 'Leaf'; protected $g0 = 'Leaf'; protected $g1 = 'Leaf'; protected $g2 = 'Other'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Look Head Back Type'; }
mit
mfe-/Prism.Validation
Example/UwpApp1/MainPageViewModel.cs
873
using Model; using Prism.Validation; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UwpApp1 { public class MainPageViewModel : ValidatableBindableBase { public MainPageViewModel() { } public ObservableCollection<Car> CarList { get; set; } = new ObservableCollection<Car>() { new Car() { Name = "a" }, new Car() { Name = "ab" }, new Car() { Name = "abc" }, new Car() { Name = "abcd" }, }; private Car _SelectedCar; [Required] public Car SelectedCar { get { return _SelectedCar; } set { SetProperty(ref _SelectedCar, value); } } } }
mit
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.2.0/datasource/datasource-jsonschema-debug.js
129
version https://git-lfs.github.com/spec/v1 oid sha256:6dabb4b180683191298af88dc5f9d2e5a076055aa491c9289275cdcfddd938ce size 2874
mit
quasarframework/quasar
app/templates/entry/ssr-pwa.js
192
/** * THIS FILE IS GENERATED AUTOMATICALLY. * DO NOT EDIT. **/ export const isRunningOnPWA = typeof window !== 'undefined' && document.body.getAttribute('data-server-rendered') === null
mit
eamonwoortman/django-unity3d-example
Unity/Assets/Scripts/JsonDotNet/Source/Utilities/ValidationUtils.cs
6135
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // 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. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Globalization; namespace Newtonsoft.Json.Utilities { internal static class ValidationUtils { public const string EmailAddressRegex = @"^([a-zA-Z0-9_'+*$%\^&!\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9:]{2,4})+$"; public const string CurrencyRegex = @"(^\$?(?!0,?\d)\d{1,3}(,?\d{3})*(\.\d\d)?)$"; public const string DateRegex = @"^(((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}|\d))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00|[048])))$"; public const string NumericRegex = @"\d*"; public static void ArgumentNotNullOrEmpty(string value, string parameterName) { if (value == null) throw new ArgumentNullException(parameterName); if (value.Length == 0) throw new ArgumentException("'{0}' cannot be empty.".FormatWith(CultureInfo.InvariantCulture, parameterName), parameterName); } public static void ArgumentNotNullOrEmptyOrWhitespace(string value, string parameterName) { ArgumentNotNullOrEmpty(value, parameterName); if (StringUtils.IsWhiteSpace(value)) throw new ArgumentException("'{0}' cannot only be whitespace.".FormatWith(CultureInfo.InvariantCulture, parameterName), parameterName); } public static void ArgumentTypeIsEnum(Type enumType, string parameterName) { ArgumentNotNull(enumType, "enumType"); if (!enumType.IsEnum) throw new ArgumentException("Type {0} is not an Enum.".FormatWith(CultureInfo.InvariantCulture, enumType), parameterName); } public static void ArgumentNotNullOrEmpty<T>(ICollection<T> collection, string parameterName) { ArgumentNotNullOrEmpty<T>(collection, parameterName, "Collection '{0}' cannot be empty.".FormatWith(CultureInfo.InvariantCulture, parameterName)); } public static void ArgumentNotNullOrEmpty<T>(ICollection<T> collection, string parameterName, string message) { if (collection == null) throw new ArgumentNullException(parameterName); if (collection.Count == 0) throw new ArgumentException(message, parameterName); } public static void ArgumentNotNullOrEmpty(ICollection collection, string parameterName) { ArgumentNotNullOrEmpty(collection, parameterName, "Collection '{0}' cannot be empty.".FormatWith(CultureInfo.InvariantCulture, parameterName)); } public static void ArgumentNotNullOrEmpty(ICollection collection, string parameterName, string message) { if (collection == null) throw new ArgumentNullException(parameterName); if (collection.Count == 0) throw new ArgumentException(message, parameterName); } public static void ArgumentNotNull(object value, string parameterName) { if (value == null) throw new ArgumentNullException(parameterName); } public static void ArgumentNotNegative(int value, string parameterName) { if (value <= 0) throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, "Argument cannot be negative."); } public static void ArgumentNotNegative(int value, string parameterName, string message) { if (value <= 0) throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, message); } public static void ArgumentNotZero(int value, string parameterName) { if (value == 0) throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, "Argument cannot be zero."); } public static void ArgumentNotZero(int value, string parameterName, string message) { if (value == 0) throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, message); } public static void ArgumentIsPositive<T>(T value, string parameterName) where T : struct, IComparable<T> { if (value.CompareTo(default(T)) != 1) throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, "Positive number required."); } public static void ArgumentIsPositive(int value, string parameterName, string message) { if (value > 0) throw MiscellaneousUtils.CreateArgumentOutOfRangeException(parameterName, value, message); } public static void ObjectNotDisposed(bool disposed, Type objectType) { if (disposed) throw new ObjectDisposedException(objectType.Name); } public static void ArgumentConditionTrue(bool condition, string parameterName, string message) { if (!condition) throw new ArgumentException(message, parameterName); } } } #endif
mit
phpManufaktur/kfContact
Library/libphonenumber/src/libphonenumber/data/ShortNumberMetadata_IT.php
3474
<?php /** * This file is automatically @generated by {@link BuildMetadataPHPFromXml}. * Please don't modify it directly. */ return array ( 'generalDesc' => array ( 'NationalNumberPattern' => '[14]\\d{2,6}', 'PossibleNumberPattern' => '\\d{3,7}', ), 'fixedLine' => array ( 'NationalNumberPattern' => '[14]\\d{2,6}', 'PossibleNumberPattern' => '\\d{3,7}', ), 'mobile' => array ( 'NationalNumberPattern' => '[14]\\d{2,6}', 'PossibleNumberPattern' => '\\d{3,7}', ), 'tollFree' => array ( 'NationalNumberPattern' => ' 1(?: 16\\d{3}| 87 ) ', 'PossibleNumberPattern' => '\\d{3,6}', 'ExampleNumber' => '187', ), 'premiumRate' => array ( 'NationalNumberPattern' => ' (?: 12| 4(?: [478]\\d{3,5}| 55 ) )\\d{2} ', 'PossibleNumberPattern' => '\\d{4,7}', 'ExampleNumber' => '1254', ), 'sharedCost' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'personalNumber' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'voip' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'pager' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'uan' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'emergency' => array ( 'NationalNumberPattern' => '11[2358]', 'PossibleNumberPattern' => '\\d{3}', 'ExampleNumber' => '112', ), 'voicemail' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'shortCode' => array ( 'NationalNumberPattern' => ' 1(?: 0\\d{2,3}| 1(?: [2-5789]| 6000 )| 2\\d{2}| 3[39]| 4(?: 82| 9\\d{1,3} )| 5(?: 00| 1[58]| 2[25]| 3[03]| 44| [59] )| 60| 8[67]| 9(?: [01]| 2(?: [01]\\d{2}| [2-9] )| 4\\d| 696 ) )| 4(?: 2323| 3(?: [01]| [45]\\d{2} )\\d{2}| [478](?: [0-4]| [5-9]\\d{2} )\\d{2}| 5(?: 045| 5\\d{2} ) ) ', 'PossibleNumberPattern' => '\\d{3,7}', 'ExampleNumber' => '114', ), 'standardRate' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'carrierSpecific' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'noInternationalDialling' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'id' => 'IT', 'countryCode' => 0, 'internationalPrefix' => '', 'sameMobileAndFixedLinePattern' => true, 'numberFormat' => array ( ), 'intlNumberFormat' => array ( ), 'mainCountryForCode' => false, 'leadingZeroPossible' => false, 'mobileNumberPortableRegion' => false, ); /* EOF */
mit
jenkinsci/jenkins
core/src/main/java/jenkins/security/AcegiSecurityExceptionFilter.java
3354
/* * The MIT License * * Copyright 2020 CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jenkins.security; import edu.umd.cs.findbugs.annotations.CheckForNull; import hudson.security.UnwrapSecurityExceptionFilter; import java.io.IOException; import java.util.function.Function; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.acegisecurity.AcegiSecurityException; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.springframework.security.web.access.ExceptionTranslationFilter; /** * Translates {@link AcegiSecurityException}s to Spring Security equivalents. * Used by other filters like {@link UnwrapSecurityExceptionFilter} and {@link ExceptionTranslationFilter}. */ @Restricted(NoExternalUse.class) public class AcegiSecurityExceptionFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); } catch (IOException x) { throw translate(x, IOException::new); } catch (ServletException x) { throw translate(x, ServletException::new); } catch (RuntimeException x) { throw translate(x, RuntimeException::new); } } private static <T extends Throwable> T translate(T t, Function<Throwable, T> ctor) { RuntimeException cause = convertedCause(t); if (cause != null) { T t2 = ctor.apply(cause); t2.addSuppressed(t); return t2; } else { return t; } } private static @CheckForNull RuntimeException convertedCause(@CheckForNull Throwable t) { if (t instanceof AcegiSecurityException) { return ((AcegiSecurityException) t).toSpring(); } else if (t != null) { return convertedCause(t.getCause()); } else { return null; } } @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void destroy() {} }
mit
jpasosa/asturiana
lib/form/doctrine/apostropheBlogPlugin/base/BaseaBlogCategoryForm.class.php
5468
<?php /** * aBlogCategory form base class. * * @method aBlogCategory getObject() Returns the current form's model object * * @package asturiana * @subpackage form * @author Your name here * @version SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $ */ abstract class BaseaBlogCategoryForm extends BaseFormDoctrine { public function setup() { $this->setWidgets(array( 'id' => new sfWidgetFormInputHidden(), 'name' => new sfWidgetFormInputText(), 'description' => new sfWidgetFormTextarea(), 'posts' => new sfWidgetFormInputCheckbox(), 'events' => new sfWidgetFormInputCheckbox(), 'users_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardUser')), 'blog_items_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'aBlogItem')), 'pages_list' => new sfWidgetFormDoctrineChoice(array('multiple' => true, 'model' => 'aPage')), )); $this->setValidators(array( 'id' => new sfValidatorChoice(array('choices' => array($this->getObject()->get('id')), 'empty_value' => $this->getObject()->get('id'), 'required' => false)), 'name' => new sfValidatorString(array('max_length' => 255, 'required' => false)), 'description' => new sfValidatorString(array('required' => false)), 'posts' => new sfValidatorBoolean(array('required' => false)), 'events' => new sfValidatorBoolean(array('required' => false)), 'users_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'sfGuardUser', 'required' => false)), 'blog_items_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'aBlogItem', 'required' => false)), 'pages_list' => new sfValidatorDoctrineChoice(array('multiple' => true, 'model' => 'aPage', 'required' => false)), )); $this->validatorSchema->setPostValidator( new sfValidatorDoctrineUnique(array('model' => 'aBlogCategory', 'column' => array('name'))) ); $this->widgetSchema->setNameFormat('a_blog_category[%s]'); $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema); $this->setupInheritance(); parent::setup(); } public function getModelName() { return 'aBlogCategory'; } public function updateDefaultsFromObject() { parent::updateDefaultsFromObject(); if (isset($this->widgetSchema['users_list'])) { $this->setDefault('users_list', $this->object->Users->getPrimaryKeys()); } if (isset($this->widgetSchema['blog_items_list'])) { $this->setDefault('blog_items_list', $this->object->BlogItems->getPrimaryKeys()); } if (isset($this->widgetSchema['pages_list'])) { $this->setDefault('pages_list', $this->object->Pages->getPrimaryKeys()); } } protected function doSave($con = null) { $this->saveUsersList($con); $this->saveBlogItemsList($con); $this->savePagesList($con); parent::doSave($con); } public function saveUsersList($con = null) { if (!$this->isValid()) { throw $this->getErrorSchema(); } if (!isset($this->widgetSchema['users_list'])) { // somebody has unset this widget return; } if (null === $con) { $con = $this->getConnection(); } $existing = $this->object->Users->getPrimaryKeys(); $values = $this->getValue('users_list'); if (!is_array($values)) { $values = array(); } $unlink = array_diff($existing, $values); if (count($unlink)) { $this->object->unlink('Users', array_values($unlink)); } $link = array_diff($values, $existing); if (count($link)) { $this->object->link('Users', array_values($link)); } } public function saveBlogItemsList($con = null) { if (!$this->isValid()) { throw $this->getErrorSchema(); } if (!isset($this->widgetSchema['blog_items_list'])) { // somebody has unset this widget return; } if (null === $con) { $con = $this->getConnection(); } $existing = $this->object->BlogItems->getPrimaryKeys(); $values = $this->getValue('blog_items_list'); if (!is_array($values)) { $values = array(); } $unlink = array_diff($existing, $values); if (count($unlink)) { $this->object->unlink('BlogItems', array_values($unlink)); } $link = array_diff($values, $existing); if (count($link)) { $this->object->link('BlogItems', array_values($link)); } } public function savePagesList($con = null) { if (!$this->isValid()) { throw $this->getErrorSchema(); } if (!isset($this->widgetSchema['pages_list'])) { // somebody has unset this widget return; } if (null === $con) { $con = $this->getConnection(); } $existing = $this->object->Pages->getPrimaryKeys(); $values = $this->getValue('pages_list'); if (!is_array($values)) { $values = array(); } $unlink = array_diff($existing, $values); if (count($unlink)) { $this->object->unlink('Pages', array_values($unlink)); } $link = array_diff($values, $existing); if (count($link)) { $this->object->link('Pages', array_values($link)); } } }
mit
radiumsoftware/iridium
test/rack_test.rb
937
require 'test_helper' class RackTest < MiniTest::Unit::TestCase def app Iridium.application end def proxies config.proxies end def setup super proxies.clear end def teardown proxies.clear super end def config Iridium.application.config end def test_middleware_config_is_exposed assert_kind_of Iridium::Rack::MiddlewareStack, config.middleware end def test_proxy_config_is_exposed assert_kind_of Hash, config.proxies end def test_proxy app.configure do proxy '/api', 'foo.com' end assert_equal "foo.com", config.proxies['/api'] end def test_proxy_allows_overwriting app.configure do proxy '/api', 'foo.com' end assert_equal 'foo.com', config.proxies['/api'] app.configure do proxy '/api', 'bar.com' end assert_equal 1, config.proxies.size assert_equal 'bar.com', config.proxies['/api'] end end
mit
ronaldahmed/robot-navigation
neural-navigation-with-lstm/MARCO/plastk/rl/queue.py
5256
""" Thread-safe queues for communicating with agents/environments in other threads. actionQ and observationQ are each a Queue.Queue to allow threadsafe communication between the agent and environment. $Id: queue.py,v 1.8 2006/03/24 23:52:33 adastra Exp $ """ import plastk.rl as rl import time class QueueAgentProxy(rl.Agent): """ Act like an rl agent, but forward everything over threading queues. """ def __init__(self,actionQ,observationQ,**args): super(QueueAgentProxy,self).__init__(**args) self.actionQueue = actionQ self.observationQueue = observationQ def __call__(self,sensation,reward=None): self.observationQueue.put((sensation,reward)) return self.actionQueue.get() class QueueEnvironmentProxy(rl.Environment): """ Act like an rl environment, but forward everything over threading queues. """ def __init__(self,actionQ,observationQ,**args): super(QueueEnvironmentProxy,self).__init__(**args) self.actionQueue = actionQ self.observationQueue = observationQ def __call__(self,action=None): self.actionQueue.put((action,time.localtime())) return self.observationQueue.get() class QueuePOMDPProxy(object): """ Act like a POMDP from the robot's POV, but forward everything over threading queues. """ def __init__(self,actionQ,observationQ,str2meaning,invert_reward=True): self.actionQueue = actionQ self.observationQueue = observationQ self.observe_wait = False self.str2meaning = str2meaning self.state = None self.pomdp_state = None self.invert_reward = invert_reward def setPOMDP(self,pomdp): self.name = pomdp.env + str(pomdp.PosSet) self.NumPoses = pomdp.NumPoses self.NumPlaces = pomdp.NumPlaces self.Positions = pomdp.Positions def setRoute(self,Start,Dest): print 'QueuePOMDPProxy.setRoute',(Start,Dest),time.localtime() while not self.actionQueue.empty(): self.actionQueue.get() while not self.observationQueue.empty(): print 'QueuePOMDPProxy.setRoute: flushing',self.observationQueue.get() self.observed = self.reward = None self.actionQueue.put((('Route',(Start,Dest)),time.localtime())) def set(self,state): print 'QueuePOMDPProxy.set',(state),time.localtime() while not self.observationQueue.empty(): print 'QueuePOMDPProxy.set: flushing',self.observationQueue.get() self.observed = self.reward = None self.state = state self.pomdp_state = None self.observe_wait = 'State' self.actionQueue.put((('State',state),time.localtime())) def is_state(self,observed): return (type(observed) == tuple and len(observed) == 2 and type(observed[0]) == int and type(observed[0]) == int) def observe(self): if self.actionQueue.empty() and not self.observe_wait: print 'perform:obs', 'Observe', time.localtime() self.observe_wait = 'Active Observe' self.actionQueue.put(('Observe', time.localtime())) observed,reward = self.observationQueue.get() # Catch State change report if reward == None: # End of episode self.observed = self.reward = None print 'Queue.observe() => observed', observed, 'reward', reward,self.observe_wait if self.observe_wait not in ('Active Observe', ): self.observe_wait = False if rl.is_terminal(observed): print 'Queue.observe() observed is terminal:', observed,self.observe_wait self.observed,self.reward = [],reward observed = None if self.observe_wait not in ('Active Observe','State'): self.observe_wait = 'Terminal' if not self.actionQueue.full(): time.sleep(0.1) print 'perform:obs', 'Observe', time.localtime() self.actionQueue.put(('Observe', time.localtime())) if type(observed) == str: observed = self.str2meaning(observed) if self.is_state(observed): self.pomdp_state = observed print 'Queue.observe() observed is a state:', observed,self.observe_wait observed = None if self.observe_wait in ('State','Terminal'): self.observe_wait = False while not observed: observed = self.observe() self.observe_wait = False self.observed,self.reward = observed,reward if not self.reward: self.reward = 0 return self.observed def perform(self,action): if action == None: while not self.observationQueue.empty(): self.observationQueue.get() while not self.actionQueue.empty(): self.actionQueue.get() if self.actionQueue.full(): while not self.observationQueue.empty(): self.observationQueue.get() print 'perform',action,time.localtime() self.observe_wait = 'Action' self.actionQueue.put((action,time.localtime())) self.observe() if self.invert_reward: self.reward *= -1 return self.reward,self.observed
mit
besongsamuel/eapp
vendor/twilio/sdk/Twilio/Rest/Preview/Understand/Assistant/ModelBuildOptions.php
3391
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Rest\Preview\Understand\Assistant; use Twilio\Options; use Twilio\Values; /** * PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. */ abstract class ModelBuildOptions { /** * @param string $statusCallback The status_callback * @param string $uniqueName The unique_name * @return CreateModelBuildOptions Options builder */ public static function create($statusCallback = Values::NONE, $uniqueName = Values::NONE) { return new CreateModelBuildOptions($statusCallback, $uniqueName); } /** * @param string $uniqueName The unique_name * @return UpdateModelBuildOptions Options builder */ public static function update($uniqueName = Values::NONE) { return new UpdateModelBuildOptions($uniqueName); } } class CreateModelBuildOptions extends Options { /** * @param string $statusCallback The status_callback * @param string $uniqueName The unique_name */ public function __construct($statusCallback = Values::NONE, $uniqueName = Values::NONE) { $this->options['statusCallback'] = $statusCallback; $this->options['uniqueName'] = $uniqueName; } /** * The status_callback * * @param string $statusCallback The status_callback * @return $this Fluent Builder */ public function setStatusCallback($statusCallback) { $this->options['statusCallback'] = $statusCallback; return $this; } /** * The unique_name * * @param string $uniqueName The unique_name * @return $this Fluent Builder */ public function setUniqueName($uniqueName) { $this->options['uniqueName'] = $uniqueName; return $this; } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { $options = array(); foreach ($this->options as $key => $value) { if ($value != Values::NONE) { $options[] = "$key=$value"; } } return '[Twilio.Preview.Understand.CreateModelBuildOptions ' . implode(' ', $options) . ']'; } } class UpdateModelBuildOptions extends Options { /** * @param string $uniqueName The unique_name */ public function __construct($uniqueName = Values::NONE) { $this->options['uniqueName'] = $uniqueName; } /** * The unique_name * * @param string $uniqueName The unique_name * @return $this Fluent Builder */ public function setUniqueName($uniqueName) { $this->options['uniqueName'] = $uniqueName; return $this; } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString() { $options = array(); foreach ($this->options as $key => $value) { if ($value != Values::NONE) { $options[] = "$key=$value"; } } return '[Twilio.Preview.Understand.UpdateModelBuildOptions ' . implode(' ', $options) . ']'; } }
mit
berndhahnebach/IfcPlusPlus
external/Coin3D/src/foreignfiles/steel-wrapper.cpp
1867
/**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef HAVE_NODEKITS #include "steel.cpp" #endif // HAVE_NODEKITS
mit
Aldorus/UtopicVillage
app/cache/prod/annotations/Exod-Bundle-UtopicVillageBundle-Entity-User$salt.cache.php
279
<?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":10:{s:4:"type";s:6:"string";s:6:"length";i:100;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:4:"name";s:4:"salt";s:7:"options";a:0:{}s:16:"columnDefinition";N;s:5:"value";N;}}');
mit
jrgleason/routes
dynamic/src/viewport/trans.component.ts
302
import {Component} from '@angular/core' @Component({ selector: 'jg-transclude', template: ` <div style="display:'flex';"> <ng-content select="[left-side]"></ng-content> <ng-content select="[right-side]"></ng-content> </div> `, }) export class TranscludeComponent { }
mit
bengimbel/Solstice-React-Contacts-Project
node_modules/react-icons/lib/fa/floppy-o.js
1529
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var FaFloppyO = function FaFloppyO(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm11.6 34.3h17.1v-8.6h-17.1v8.6z m20 0h2.8v-20q0-0.3-0.2-0.9t-0.4-0.7l-6.3-6.3q-0.2-0.2-0.8-0.5t-0.8-0.2v9.3q0 0.9-0.7 1.5t-1.5 0.6h-12.8q-0.9 0-1.6-0.6t-0.6-1.5v-9.3h-2.8v28.6h2.8v-9.3q0-0.9 0.6-1.5t1.6-0.6h18.5q0.9 0 1.5 0.6t0.7 1.5v9.3z m-8.6-20.7v-7.2q0-0.3-0.2-0.5t-0.5-0.2h-4.3q-0.3 0-0.5 0.2t-0.2 0.5v7.2q0 0.3 0.2 0.5t0.5 0.2h4.3q0.3 0 0.5-0.2t0.2-0.5z m14.3 0.7v20.7q0 0.9-0.6 1.5t-1.6 0.6h-30q-0.8 0-1.5-0.6t-0.6-1.5v-30q0-0.9 0.6-1.5t1.5-0.6h20.8q0.9 0 1.9 0.4t1.7 1.1l6.3 6.2q0.6 0.6 1 1.7t0.5 2z' }) ) ); }; exports.default = FaFloppyO; module.exports = exports['default'];
mit
crysfel/fundamentos-extjs
extjs-4.1.0/examples/calendar/src/form/EventWindow.js
10609
/** * @class Ext.calendar.form.EventWindow * @extends Ext.Window * <p>A custom window containing a basic edit form used for quick editing of events.</p> * <p>This window also provides custom events specific to the calendar so that other calendar components can be easily * notified when an event has been edited via this component.</p> * @constructor * @param {Object} config The config object */ Ext.define('Ext.calendar.form.EventWindow', { extend: 'Ext.window.Window', alias: 'widget.eventeditwindow', requires: [ 'Ext.form.Panel', 'Ext.calendar.data.EventModel', 'Ext.calendar.data.EventMappings' ], constructor: function(config) { var formPanelCfg = { xtype: 'form', fieldDefaults: { msgTarget: 'side', labelWidth: 65 }, frame: false, bodyStyle: 'background:transparent;padding:5px 10px 10px;', bodyBorder: false, border: false, items: [{ itemId: 'title', name: Ext.calendar.data.EventMappings.Title.name, fieldLabel: 'Title', xtype: 'textfield', anchor: '100%' }, { xtype: 'daterangefield', itemId: 'date-range', name: 'dates', anchor: '100%', fieldLabel: 'When' }] }; if (config.calendarStore) { this.calendarStore = config.calendarStore; delete config.calendarStore; formPanelCfg.items.push({ xtype: 'calendarpicker', itemId: 'calendar', name: Ext.calendar.data.EventMappings.CalendarId.name, anchor: '100%', store: this.calendarStore }); } this.callParent([Ext.apply({ titleTextAdd: 'Add Event', titleTextEdit: 'Edit Event', width: 600, autocreate: true, border: true, closeAction: 'hide', modal: false, resizable: false, buttonAlign: 'left', savingMessage: 'Saving changes...', deletingMessage: 'Deleting event...', layout: 'fit', fbar: [{ xtype: 'tbtext', text: '<a href="#" id="tblink">Edit Details...</a>' }, '->', { itemId: 'delete-btn', text: 'Delete Event', disabled: false, handler: this.onDelete, scope: this, minWidth: 150, hideMode: 'offsets' }, { text: 'Save', disabled: false, handler: this.onSave, scope: this }, { text: 'Cancel', disabled: false, handler: this.onCancel, scope: this }], items: formPanelCfg }, config)]); }, // private newId: 10000, // private initComponent: function() { this.callParent(); this.formPanel = this.items.items[0]; this.addEvents({ /** * @event eventadd * Fires after a new event is added * @param {Ext.calendar.form.EventWindow} this * @param {Ext.calendar.EventRecord} rec The new {@link Ext.calendar.EventRecord record} that was added */ eventadd: true, /** * @event eventupdate * Fires after an existing event is updated * @param {Ext.calendar.form.EventWindow} this * @param {Ext.calendar.EventRecord} rec The new {@link Ext.calendar.EventRecord record} that was updated */ eventupdate: true, /** * @event eventdelete * Fires after an event is deleted * @param {Ext.calendar.form.EventWindow} this * @param {Ext.calendar.EventRecord} rec The new {@link Ext.calendar.EventRecord record} that was deleted */ eventdelete: true, /** * @event eventcancel * Fires after an event add/edit operation is canceled by the user and no store update took place * @param {Ext.calendar.form.EventWindow} this * @param {Ext.calendar.EventRecord} rec The new {@link Ext.calendar.EventRecord record} that was canceled */ eventcancel: true, /** * @event editdetails * Fires when the user selects the option in this window to continue editing in the detailed edit form * (by default, an instance of {@link Ext.calendar.EventEditForm}. Handling code should hide this window * and transfer the current event record to the appropriate instance of the detailed form by showing it * and calling {@link Ext.calendar.EventEditForm#loadRecord loadRecord}. * @param {Ext.calendar.form.EventWindow} this * @param {Ext.calendar.EventRecord} rec The {@link Ext.calendar.EventRecord record} that is currently being edited */ editdetails: true }); }, // private afterRender: function() { this.callParent(); this.el.addCls('ext-cal-event-win'); Ext.get('tblink').on('click', this.onEditDetailsClick, this); this.titleField = this.down('#title'); this.dateRangeField = this.down('#date-range'); this.calendarField = this.down('#calendar'); this.deleteButton = this.down('#delete-btn'); this.titleField.isValid = function() { var valid = this.getValue().length > 0; if (!valid) { this.focus(); } return valid; }; }, // private onEditDetailsClick: function(e){ e.stopEvent(); this.updateRecord(this.activeRecord, true); this.fireEvent('editdetails', this, this.activeRecord, this.animateTarget); }, /** * Shows the window, rendering it first if necessary, or activates it and brings it to front if hidden. * @param {Ext.data.Record/Object} o Either a {@link Ext.data.Record} if showing the form * for an existing event in edit mode, or a plain object containing a StartDate property (and * optionally an EndDate property) for showing the form in add mode. * @param {String/Element} animateTarget (optional) The target element or id from which the window should * animate while opening (defaults to null with no animation) * @return {Ext.Window} this */ show: function(o, animateTarget) { // Work around the CSS day cell height hack needed for initial render in IE8/strict: var me = this, anim = (Ext.isIE8 && Ext.isStrict) ? null: animateTarget, M = Ext.calendar.data.EventMappings; this.callParent([anim, function(){ me.titleField.focus(true, 100); }]); this.deleteButton[o.data && o.data[M.EventId.name] ? 'show': 'hide'](); var rec, f = this.formPanel.form; if (o.data) { rec = o; this.setTitle(rec.phantom ? this.titleTextAdd : this.titleTextEdit); f.loadRecord(rec); } else { this.setTitle(this.titleTextAdd); var start = o[M.StartDate.name], end = o[M.EndDate.name] || Ext.calendar.util.Date.add(start, {hours: 1}); rec = Ext.create('Ext.calendar.data.EventModel'); rec.data[M.StartDate.name] = start; rec.data[M.EndDate.name] = end; rec.data[M.IsAllDay.name] = !!o[M.IsAllDay.name] || start.getDate() != Ext.calendar.util.Date.add(end, {millis: 1}).getDate(); f.reset(); f.loadRecord(rec); } if (this.calendarStore) { this.calendarField.setValue(rec.data[M.CalendarId.name]); } this.dateRangeField.setValue(rec.data); this.activeRecord = rec; return this; }, // private roundTime: function(dt, incr) { incr = incr || 15; var m = parseInt(dt.getMinutes(), 10); return dt.add('mi', incr - (m % incr)); }, // private onCancel: function() { this.cleanup(true); this.fireEvent('eventcancel', this); }, // private cleanup: function(hide) { if (this.activeRecord && this.activeRecord.dirty) { this.activeRecord.reject(); } delete this.activeRecord; if (hide === true) { // Work around the CSS day cell height hack needed for initial render in IE8/strict: //var anim = afterDelete || (Ext.isIE8 && Ext.isStrict) ? null : this.animateTarget; this.hide(); } }, // private updateRecord: function(record, keepEditing) { var fields = record.fields, values = this.formPanel.getForm().getValues(), name, M = Ext.calendar.data.EventMappings, obj = {}; fields.each(function(f) { name = f.name; if (name in values) { obj[name] = values[name]; } }); var dates = this.dateRangeField.getValue(); obj[M.StartDate.name] = dates[0]; obj[M.EndDate.name] = dates[1]; obj[M.IsAllDay.name] = dates[2]; record.beginEdit(); record.set(obj); if (!keepEditing) { record.endEdit(); } return this; }, // private onSave: function(){ if(!this.formPanel.form.isValid()){ return; } if(!this.updateRecord(this.activeRecord)){ this.onCancel(); return; } this.fireEvent(this.activeRecord.phantom ? 'eventadd' : 'eventupdate', this, this.activeRecord, this.animateTarget); // Clear phantom and modified states. this.activeRecord.commit(); }, // private onDelete: function(){ this.fireEvent('eventdelete', this, this.activeRecord, this.animateTarget); } });
mit
NateBrady23/faithwraps
application/config/form_validation.php
1849
<?php $config = array( "login" => array( array( 'field' => 'email', 'label' => 'E-Mail', 'rules' => 'required|trim|valid_email|max_length[255]' ), array( 'field' => 'password', 'label' => 'Password', 'rules' => 'required|trim|min_length[8]|max_length[255]' ) ), "register" => array( array( 'field' => 'email', 'label' => 'E-Mail', 'rules' => 'required|trim|valid_email|max_length[255]|is_unique[users.email]' ), array( 'field' => 'password', 'label' => 'Password', 'rules' => 'required|trim|min_length[8]|max_length[255]' ), array( 'field' => 'confirm_password', 'label' => 'Password Confirmation', 'rules' => 'required|trim|min_length[8]|max_length[255]|matches[password]' ) ), 'password_reset' => array( array( 'field' => 'email', 'label' => 'Account Email', 'rules' => 'required|trim|valid_email' ) ), 'product' => array( array( 'field' => 'product_style', 'label' => 'Product Style', 'rules' => 'required|trim|integer|greater_than[0]' ), array( 'field' => 'product_qty', 'label' => 'Quantity', 'rules' => 'required|trim|integer|greater_than[0]' ) ), 'newsletter' => array( array( 'field' => 'email', 'label' => 'E-Mail', 'rules' => 'required|trim|valid_email|is_unique[newsletters.email]' ) ), 'billing' => array( array( 'field' => 'name', 'label' => 'Name on Card', 'rules' => 'required|trim' ), array( 'field' => 'address', 'label' => 'Billing Address Line 1', 'rules' => 'required|trim' ), array( 'field' => 'city', 'label' => 'City', 'rules' => 'required|trim' ), array( 'field' => 'state', 'label' => 'State', 'rules' => 'required|trim' ), array( 'field' => 'zip_code', 'label' => 'Zip Code', 'rules' => 'required|trim|integer' ) ) );
mit
cokejcm/spring-boot-arch
base-arch/src/main/java/com/demo/app/domain/security/Rol.java
93
package com.demo.app.domain.security; public enum Rol { APP_ROLE, ADMIN_ROLE, BASIC_ROLE }
mit
crmouli/crmouli.github.io
js/libs/oj/v3.0.0/debug/ojkoshared.js
2034
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ "use strict"; define(['ojs/ojcore', 'knockout'], function(oj, ko) { /** * @ignore * @constructor */ function _KoCustomBindingProvider() { this.install = function() { var provider = ko.bindingProvider; var instance_name = "instance"; var wrapped = provider[instance_name]; var getAccessors = 'getBindingAccessors'; if (!wrapped[getAccessors]) { oj.Logger.error("JET's Knockout bindings are not compatible with the current binding provider since it does " + "not implement getBindingAccessors()"); return this; } var custom = provider[instance_name] = {}; var methodsToWrap = []; methodsToWrap.push(getAccessors, "nodeHasBindings", "getBindings", "preprocessNode"); methodsToWrap.forEach( function(name) { _wrap(wrapped, custom, name); } ); return this; }; this.addPostprocessor = function(postprocessor) { var keys = Object.keys(postprocessor); keys.forEach( function(key) { _postprocessors[key] = _postprocessors[key] || []; _postprocessors[key].push(postprocessor[key]); } ); } var _postprocessors = {}; function _wrap(wrapped, target, name) { var delegate = wrapped[name]; target[name] = function() { var ret = delegate ? delegate.apply(wrapped, arguments) : null; var postprocessHandlers = _postprocessors[name]; if (postprocessHandlers != null) { var originalArgs = arguments; postprocessHandlers.forEach( function(handler) { var args = Array.prototype.slice.call(originalArgs); args.push(ret, wrapped); ret = handler.apply(null, args); } ); } return ret; } } } /** * @ignore */ oj.__KO_CUSTOM_BINDING_PROVIDER_INSTANCE = new _KoCustomBindingProvider().install(); });
mit
darrelljefferson/themcset.com
bin/test/i/c.php
35
<?php namespace test\i; class c { }
mit
coreinfrastructure/best-practices-badge
test/unit/lib/rake_task_test.rb
456
# frozen_string_literal: true # Copyright 2015-2017, the Linux Foundation, IDA, and the # CII Best Practices badge contributors # SPDX-License-Identifier: MIT require 'test_helper' class RakeTaskTest < ActiveSupport::TestCase test 'regression test for rake reminders' do assert_equal 1, Project.projects_to_remind.size result = system 'rake reminders >/dev/null' assert result assert_equal 0, Project.projects_to_remind.size end end
mit
thomaslevesque/AlphaFS
AlphaFS/Filesystem/BackupFileStream.cs
38825
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32.Security; using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using SecurityNativeMethods = Alphaleonis.Win32.Security.NativeMethods; namespace Alphaleonis.Win32.Filesystem { /// <summary>The <see cref="BackupFileStream"/> provides access to data associated with a specific file or directory, including security information and alternative data streams, for backup and restore operations.</summary> /// <remarks>This class uses the <see href="http://msdn.microsoft.com/en-us/library/aa362509(VS.85).aspx">BackupRead</see>, /// <see href="http://msdn.microsoft.com/en-us/library/aa362510(VS.85).aspx">BackupSeek</see> and /// <see href="http://msdn.microsoft.com/en-us/library/aa362511(VS.85).aspx">BackupWrite</see> functions from the Win32 API to provide access to the file or directory. /// </remarks> public sealed class BackupFileStream : Stream { #region Private Fields private readonly bool _canRead; private readonly bool _canWrite; private readonly bool _processSecurity; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _context = IntPtr.Zero; #endregion // Private Fields #region Construction and Destruction /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path and creation mode.</summary> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <remarks>The file will be opened for exclusive access for both reading and writing.</remarks> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode) : this(File.CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, mode, FileSystemRights.Read | FileSystemRights.Write, FileShare.None, true, PathFormat.RelativePath), FileSystemRights.Read | FileSystemRights.Write) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode and access rights.</summary> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <remarks>The file will be opened for exclusive access.</remarks> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access) : this(File.CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, mode, access, FileShare.None, true, PathFormat.RelativePath), access) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode, access rights and sharing permission.</summary> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <param name="share">A <see cref="FileShare"/> constant that determines how the file will be shared by processes.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share) : this(File.CreateFileCore(null, path, ExtendedFileAttributes.Normal, null, mode, access, share, true, PathFormat.RelativePath), access) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode, access rights and sharing permission, and additional file attributes.</summary> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <param name="share">A <see cref="FileShare"/> constant that determines how the file will be shared by processes.</param> /// <param name="attributes">A <see cref="ExtendedFileAttributes"/> constant that specifies additional file attributes.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes) : this(File.CreateFileCore(null, path, attributes, null, mode, access, share, true, PathFormat.RelativePath), access) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode, access rights and sharing permission, additional file attributes, access control and audit security.</summary> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <param name="share">A <see cref="FileShare"/> constant that determines how the file will be shared by processes.</param> /// <param name="attributes">A <see cref="ExtendedFileAttributes"/> constant that specifies additional file attributes.</param> /// <param name="security">A <see cref="FileSecurity"/> constant that determines the access control and audit security for the file. This parameter This parameter may be <see langword="null"/>.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes, FileSecurity security) : this(File.CreateFileCore(null, path, attributes, security, mode, access, share, true, PathFormat.RelativePath), access) { } #region Transactional /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path and creation mode.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <remarks>The file will be opened for exclusive access for both reading and writing.</remarks> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode) : this(File.CreateFileCore(transaction, path, ExtendedFileAttributes.Normal, null, mode, FileSystemRights.Read | FileSystemRights.Write, FileShare.None, true, PathFormat.RelativePath), FileSystemRights.Read | FileSystemRights.Write) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode and access rights.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <remarks>The file will be opened for exclusive access.</remarks> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access) : this(File.CreateFileCore(transaction, path, ExtendedFileAttributes.Normal, null, mode, access, FileShare.None, true, PathFormat.RelativePath), access) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode, access rights and sharing permission.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <param name="share">A <see cref="FileShare"/> constant that determines how the file will be shared by processes.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share) : this(File.CreateFileCore(transaction, path, ExtendedFileAttributes.Normal, null, mode, access, share, true, PathFormat.RelativePath), access) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode, access rights and sharing permission, and additional file attributes.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <param name="share">A <see cref="FileShare"/> constant that determines how the file will be shared by processes.</param> /// <param name="attributes">A <see cref="ExtendedFileAttributes"/> constant that specifies additional file attributes.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes) : this(File.CreateFileCore(transaction, path, attributes, null, mode, access, share, true, PathFormat.RelativePath), access) { } /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class with the specified path, creation mode, access rights and sharing permission, additional file attributes, access control and audit security.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">A relative or absolute path for the file that the current <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="mode">A <see cref="FileMode"/> constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that determines the access rights to use when creating access and audit rules for the file.</param> /// <param name="share">A <see cref="FileShare"/> constant that determines how the file will be shared by processes.</param> /// <param name="attributes">A <see cref="ExtendedFileAttributes"/> constant that specifies additional file attributes.</param> /// <param name="security">A <see cref="FileSecurity"/> constant that determines the access control and audit security for the file. This parameter This parameter may be <see langword="null"/>.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SecurityCritical] public BackupFileStream(KernelTransaction transaction, string path, FileMode mode, FileSystemRights access, FileShare share, ExtendedFileAttributes attributes, FileSecurity security) : this(File.CreateFileCore(transaction, path, attributes, security, mode, access, share, true, PathFormat.RelativePath), access) { } #endregion // Transacted #region Stream /// <summary>Initializes a new instance of the <see cref="BackupFileStream"/> class for the specified file handle, with the specified read/write permission.</summary> /// <param name="handle">A file handle for the file that this <see cref="BackupFileStream"/> object will encapsulate.</param> /// <param name="access">A <see cref="FileSystemRights"/> constant that gets the <see cref="CanRead"/> and <see cref="CanWrite"/> properties of the <see cref="BackupFileStream"/> object.</param> [SecurityCritical] public BackupFileStream(SafeFileHandle handle, FileSystemRights access) { if (handle == null) throw new ArgumentNullException("handle", Resources.Handle_Is_Invalid); if (handle.IsInvalid) { handle.Close(); throw new ArgumentException(Resources.Handle_Is_Invalid); } if (handle.IsClosed) throw new ArgumentException(Resources.Handle_Is_Closed); SafeFileHandle = handle; _canRead = (access & FileSystemRights.ReadData) != 0; _canWrite = (access & FileSystemRights.WriteData) != 0; _processSecurity = true; } #endregion // Stream #endregion // Construction and Destruction #region NotSupportedException /// <summary>When overridden in a derived class, gets the length in bytes of the stream.</summary> /// <value>This method always throws an exception.</value> /// <exception cref="NotSupportedException"/> public override long Length { get { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } } /// <summary>When overridden in a derived class, gets or sets the position within the current stream.</summary> /// <value>This method always throws an exception.</value> /// <exception cref="NotSupportedException"/> public override long Position { get { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } set { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } } /// <summary>When overridden in a derived class, sets the position within the current stream.</summary> /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param> /// <param name="origin">A value of type <see cref="System.IO.SeekOrigin"/> indicating the reference point used to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> /// <remarks><para><note><para>This stream does not support seeking using this method, and calling this method will always throw <see cref="NotSupportedException"/>. See <see cref="Skip"/> for an alternative way of seeking forward.</para></note></para></remarks> /// <exception cref="NotSupportedException"/> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } /// <summary>When overridden in a derived class, sets the length of the current stream.</summary> /// <param name="value">The desired length of the current stream in bytes.</param> /// <remarks>This method is not supported by the <see cref="BackupFileStream"/> class, and calling it will always generate a <see cref="NotSupportedException"/>.</remarks> /// <exception cref="NotSupportedException"/> public override void SetLength(long value) { throw new NotSupportedException(Resources.No_Stream_Seeking_Support); } #endregion // NotSupportedException #region Properties /// <summary>Gets a value indicating whether the current stream supports reading.</summary> /// <returns><see langword="true"/> if the stream supports reading, <see langword="false"/> otherwise.</returns> public override bool CanRead { get { return _canRead; } } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <returns>This method always returns <see langword="false"/>.</returns> public override bool CanSeek { get { return false; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> /// <returns><see langword="true"/> if the stream supports writing, <see langword="false"/> otherwise.</returns> public override bool CanWrite { get { return _canWrite; } } /// <summary>Gets a <see cref="SafeFileHandle"/> object that represents the operating system file handle for the file that the current <see cref="BackupFileStream"/> object encapsulates.</summary> /// <value>A <see cref="SafeFileHandle"/> object that represents the operating system file handle for the file that /// the current <see cref="BackupFileStream"/> object encapsulates.</value> private SafeFileHandle SafeFileHandle { get; set; } #endregion // Properties #region Methods /// <summary>Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.</summary> /// <remarks>This method will not backup the access-control list (ACL) data for the file or directory.</remarks> /// <param name="buffer"> /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between /// <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the /// current source. /// </param> /// <param name="offset"> /// The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream. /// </param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not /// currently available, or zero (0) if the end of the stream has been reached. /// </returns> /// /// <exception cref="System.ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="System.ArgumentOutOfRangeException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="ObjectDisposedException"/> public override int Read(byte[] buffer, int offset, int count) { return Read(buffer, offset, count, false); } /// <summary>When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.</summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values /// between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <param name="processSecurity">Indicates whether the function will backup the access-control list (ACL) data for the file or directory.</param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not /// currently available, or zero (0) if the end of the stream has been reached. /// </returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="ObjectDisposedException"/> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] [SecurityCritical] public int Read(byte[] buffer, int offset, int count, bool processSecurity) { if (buffer == null) throw new ArgumentNullException("buffer"); if (!CanRead) throw new NotSupportedException("Stream does not support reading"); if (offset + count > buffer.Length) throw new ArgumentException("The sum of offset and count is larger than the size of the buffer."); if (offset < 0) throw new ArgumentOutOfRangeException("offset", offset, Resources.Negative_Offset); if (count < 0) throw new ArgumentOutOfRangeException("count", count, Resources.Negative_Count); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(count)) { uint numberOfBytesRead; if (!NativeMethods.BackupRead(SafeFileHandle, safeBuffer, (uint)safeBuffer.Capacity, out numberOfBytesRead, false, processSecurity, ref _context)) NativeError.ThrowException(Marshal.GetLastWin32Error()); // See File.GetAccessControlCore(): .CopyTo() does not work there? safeBuffer.CopyTo(buffer, offset, count); return (int)numberOfBytesRead; } } /// <summary>Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.</summary> /// <overloads> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </overloads> /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <exception cref="ArgumentException"/> /// <exception cref="System.ArgumentNullException"/> /// <exception cref="System.ArgumentOutOfRangeException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="ObjectDisposedException"/> /// <remarks>This method will not process the access-control list (ACL) data for the file or directory.</remarks> public override void Write(byte[] buffer, int offset, int count) { Write(buffer, offset, count, false); } /// <summary>When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.</summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> /// <param name="processSecurity">Specifies whether the function will restore the access-control list (ACL) data for the file or directory. /// If this is <see langword="true"/> you need to specify <see cref="FileSystemRights.TakeOwnership"/> and <see cref="FileSystemRights.ChangePermissions"/> access when /// opening the file or directory handle. If the handle does not have those access rights, the operating system denies /// access to the ACL data, and ACL data restoration will not occur.</param> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="System.ArgumentOutOfRangeException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="ObjectDisposedException"/> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] [SecurityCritical] public void Write(byte[] buffer, int offset, int count, bool processSecurity) { if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", offset, Resources.Negative_Offset); if (count < 0) throw new ArgumentOutOfRangeException("count", count, Resources.Negative_Count); if (offset + count > buffer.Length) throw new ArgumentException(Resources.Buffer_Not_Large_Enough); using (var safeBuffer = new SafeGlobalMemoryBufferHandle(count)) { safeBuffer.CopyFrom(buffer, offset, count); uint bytesWritten; if (!NativeMethods.BackupWrite(SafeFileHandle, safeBuffer, (uint)safeBuffer.Capacity, out bytesWritten, false, processSecurity, ref _context)) NativeError.ThrowException(Marshal.GetLastWin32Error()); } } /// <summary>Clears all buffers for this stream and causes any buffered data to be written to the underlying device.</summary> public override void Flush() { if (!NativeMethods.FlushFileBuffers(SafeFileHandle)) NativeError.ThrowException(Marshal.GetLastWin32Error()); } /// <summary>Skips ahead the specified number of bytes from the current stream.</summary> /// <remarks><para>This method represents the Win32 API implementation of <see href="http://msdn.microsoft.com/en-us/library/aa362509(VS.85).aspx">BackupSeek</see>.</para> /// <para> /// Applications use the <see cref="Skip"/> method to skip portions of a data stream that cause errors. This function does not /// seek across stream headers. For example, this function cannot be used to skip the stream name. If an application /// attempts to seek past the end of a substream, the function fails, the return value indicates the actual number of bytes /// the function seeks, and the file position is placed at the start of the next stream header. /// </para> /// </remarks> /// <param name="bytes">The number of bytes to skip.</param> /// <returns>The number of bytes actually skipped.</returns> [SecurityCritical] public long Skip(long bytes) { uint lowSought, highSought; if (!NativeMethods.BackupSeek(SafeFileHandle, NativeMethods.GetLowOrderDword(bytes), NativeMethods.GetHighOrderDword(bytes), out lowSought, out highSought, ref _context)) { int lastError = Marshal.GetLastWin32Error(); // Error Code 25 indicates a seek error, we just skip that here. if (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_SEEK) NativeError.ThrowException(lastError); } return NativeMethods.ToLong(highSought, lowSought); } /// <summary>Gets a <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for the file described by the current <see cref="BackupFileStream"/> object.</summary> /// <exception cref="IOException"/> /// <returns> /// A <see cref="FileSecurity"/> object that encapsulates the access control list (ACL) entries for the file described by the current /// <see cref="BackupFileStream"/> object. /// </returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SecurityCritical] public FileSecurity GetAccessControl() { IntPtr pSidOwner, pSidGroup, pDacl, pSacl; SafeGlobalMemoryBufferHandle pSecurityDescriptor; uint lastError = SecurityNativeMethods.GetSecurityInfo(SafeFileHandle, ObjectType.FileObject, SecurityInformation.Group | SecurityInformation.Owner | SecurityInformation.Label | SecurityInformation.Dacl | SecurityInformation.Sacl, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor); try { if (lastError != Win32Errors.ERROR_SUCCESS) NativeError.ThrowException((int)lastError); if (pSecurityDescriptor != null && pSecurityDescriptor.IsInvalid) { pSecurityDescriptor.Close(); throw new IOException(Resources.Returned_Invalid_Security_Descriptor); } uint length = SecurityNativeMethods.GetSecurityDescriptorLength(pSecurityDescriptor); byte[] managedBuffer = new byte[length]; // .CopyTo() does not work there? if (pSecurityDescriptor != null) pSecurityDescriptor.CopyTo(managedBuffer, 0, (int) length); var fs = new FileSecurity(); fs.SetSecurityDescriptorBinaryForm(managedBuffer); return fs; } finally { if (pSecurityDescriptor != null) pSecurityDescriptor.Close(); } } /// <summary>Applies access control list (ACL) entries described by a <see cref="FileSecurity"/> object to the file described by the current <see cref="BackupFileStream"/> object.</summary> /// <param name="fileSecurity">A <see cref="FileSecurity"/> object that describes an ACL entry to apply to the current file.</param> [SecurityCritical] public void SetAccessControl(ObjectSecurity fileSecurity) { File.SetAccessControlCore(null, SafeFileHandle, fileSecurity, AccessControlSections.All, PathFormat.LongFullPath); } /// <summary>Prevents other processes from changing the <see cref="BackupFileStream"/> while permitting read access.</summary> /// <param name="position">The beginning of the range to lock. The value of this parameter must be equal to or greater than zero (0).</param> /// <param name="length">The range to be locked.</param> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="ObjectDisposedException"/> [SecurityCritical] public void Lock(long position, long length) { if (position < 0) throw new ArgumentOutOfRangeException("position", position, Resources.Unlock_Position_Negative); if (length < 0) throw new ArgumentOutOfRangeException("length", length, Resources.Negative_Lock_Length); if (!NativeMethods.LockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length))) NativeError.ThrowException(Marshal.GetLastWin32Error()); } /// <summary>Allows access by other processes to all or part of a file that was previously locked.</summary> /// <param name="position">The beginning of the range to unlock.</param> /// <param name="length">The range to be unlocked.</param> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="ArgumentOutOfRangeException"/> /// <exception cref="ObjectDisposedException"/> [SecurityCritical] public void Unlock(long position, long length) { if (position < 0) throw new ArgumentOutOfRangeException("position", position, Resources.Unlock_Position_Negative); if (length < 0) throw new ArgumentOutOfRangeException("length", length, Resources.Negative_Lock_Length); if (!NativeMethods.UnlockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length))) NativeError.ThrowException(Marshal.GetLastWin32Error()); } /// <summary>Reads a stream header from the current <see cref="BackupFileStream"/>.</summary> /// <returns>The stream header read from the current <see cref="BackupFileStream"/>, or <see langword="null"/> if the end-of-file /// was reached before the required number of bytes of a header could be read.</returns> /// <exception cref="IOException"/> /// <remarks>The stream must be positioned at where an actual header starts for the returned object to represent valid /// information.</remarks> [SecurityCritical] public BackupStreamInfo ReadStreamInfo() { var sizeOf = Marshal.SizeOf(typeof(NativeMethods.WIN32_STREAM_ID)); using (var hBuf = new SafeGlobalMemoryBufferHandle(sizeOf)) { uint numberOfBytesRead; if (!NativeMethods.BackupRead(SafeFileHandle, hBuf, (uint) sizeOf, out numberOfBytesRead, false, _processSecurity, ref _context)) NativeError.ThrowException(); if (numberOfBytesRead == 0) return null; if (numberOfBytesRead < sizeOf) throw new IOException(Resources.Read_Incomplete_Header); var streamID = hBuf.PtrToStructure<NativeMethods.WIN32_STREAM_ID>(0); uint nameLength = (uint) Math.Min(streamID.dwStreamNameSize, hBuf.Capacity); if (!NativeMethods.BackupRead(SafeFileHandle, hBuf, nameLength, out numberOfBytesRead, false, _processSecurity, ref _context)) NativeError.ThrowException(); string name = hBuf.PtrToStringUni(0, (int) nameLength/2); return new BackupStreamInfo(streamID, name); } } #endregion // Methods #region Disposable Members /// <summary>Releases the unmanaged resources used by the <see cref="System.IO.Stream"/> and optionally releases the managed resources.</summary> /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] protected override void Dispose(bool disposing) { // If one of the constructors previously threw an exception, // than the object hasn't been initialized properly and call from finalize will fail. if (SafeFileHandle != null && !SafeFileHandle.IsInvalid) { if (_context != IntPtr.Zero) { try { uint temp; // MSDN: To release the memory used by the data structure, call BackupRead with the bAbort parameter set to TRUE when the backup operation is complete. if (!NativeMethods.BackupRead(SafeFileHandle, new SafeGlobalMemoryBufferHandle(), 0, out temp, true, false, ref _context)) NativeError.ThrowException(Marshal.GetLastWin32Error()); } finally { _context = IntPtr.Zero; SafeFileHandle.Close(); } } } base.Dispose(disposing); } /// <summary>Releases unmanaged resources and performs other cleanup operations before the <see cref="BackupFileStream"/> is reclaimed by garbage collection.</summary> ~BackupFileStream() { Dispose(false); } #endregion // Disposable Members } }
mit
oliviertassinari/material-ui
packages/mui-icons-material/lib/PhonelinkSetupTwoTone.js
1252
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M7 3v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2H9c-1.1 0-2 .9-2 2zm2.5 12.5c.29-.12.55-.29.8-.48l-.02.03 1.01.39c.23.09.49 0 .61-.22l.84-1.46c.12-.21.07-.49-.12-.64l-.85-.68-.02.03c.02-.16.05-.32.05-.48s-.03-.32-.05-.48l.02.03.85-.68c.19-.15.24-.43.12-.64l-.84-1.46c-.12-.21-.38-.31-.61-.22l-1.01.39.02.03c-.25-.17-.51-.34-.8-.46l-.17-1.08C9.3 7.18 9.09 7 8.84 7H7.16c-.25 0-.46.18-.49.42L6.5 8.5c-.29.12-.55.29-.8.48l.02-.03-1.02-.39c-.23-.09-.49 0-.61.22l-.84 1.46c-.12.21-.07.49.12.64l.85.68.02-.03c-.02.15-.05.31-.05.47s.03.32.05.48l-.02-.03-.85.68c-.19.15-.24.43-.12.64l.84 1.46c.12.21.38.31.61.22l1.01-.39-.01-.04c.25.19.51.36.8.48l.17 1.07c.03.25.24.43.49.43h1.68c.25 0 .46-.18.49-.42l.17-1.08zM6 12c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2z" }), 'PhonelinkSetupTwoTone'); exports.default = _default;
mit
ups216/vscode
src/vs/platform/environment/node/environmentService.ts
1325
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import * as paths from 'vs/base/node/paths'; import product from 'vs/platform/product'; import pkg from 'vs/platform/package'; import * as os from 'os'; import * as path from 'path'; import { parseArgs } from 'vs/code/node/argv'; export class EnvironmentService implements IEnvironmentService { serviceId = IEnvironmentService; private _userDataPath: string; get userDataPath(): string { return this._userDataPath; } private _extensionsPath: string; get extensionsPath(): string { return this._extensionsPath; } constructor() { const argv = parseArgs(process.argv); this._userDataPath = paths.getUserDataPath(process.platform, pkg.name, process.argv); const userHome = path.join(os.homedir(), product.dataFolderName); this._extensionsPath = argv.extensionHomePath || path.join(userHome, 'extensions'); this._extensionsPath = path.normalize(this._extensionsPath); } }
mit
tinymighty/booty
layouts/default/Template.php
408
<?php /** * @todo document * @ingroup Skins */ class BootyDefaultTemplate extends BootyTemplate { protected $_default_defaults = array( 'show title'=> true ); public function __construct( $options=array() ){ //merge in the default settings $this->setDefaults( $this->_default_defaults ); parent::__construct( $options ); //$this->addTemplatePath( dirname(__FILE__).'/templates' ); } }
mit
ensemblr/llvm-project-boilerplate
include/llvm/lib/IR/DIBuilder.cpp
38815
//===--- DIBuilder.cpp - Debug Information Builder ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the DIBuilder. // //===----------------------------------------------------------------------===// #include "llvm/IR/DIBuilder.h" #include "llvm/ADT/STLExtras.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Dwarf.h" #include "LLVMContextImpl.h" using namespace llvm; using namespace llvm::dwarf; DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes) : M(m), VMContext(M.getContext()), CUNode(nullptr), DeclareFn(nullptr), ValueFn(nullptr), AllowUnresolvedNodes(AllowUnresolvedNodes) {} void DIBuilder::trackIfUnresolved(MDNode *N) { if (!N) return; if (N->isResolved()) return; assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes"); UnresolvedNodes.emplace_back(N); } void DIBuilder::finalize() { if (!CUNode) { assert(!AllowUnresolvedNodes && "creating type nodes without a CU is not supported"); return; } CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes)); SmallVector<Metadata *, 16> RetainValues; // Declarations and definitions of the same type may be retained. Some // clients RAUW these pairs, leaving duplicates in the retained types // list. Use a set to remove the duplicates while we transform the // TrackingVHs back into Values. SmallPtrSet<Metadata *, 16> RetainSet; for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++) if (RetainSet.insert(AllRetainTypes[I]).second) RetainValues.push_back(AllRetainTypes[I]); if (!RetainValues.empty()) CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues)); DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms); auto resolveVariables = [&](DISubprogram *SP) { MDTuple *Temp = SP->getVariables().get(); if (!Temp) return; SmallVector<Metadata *, 4> Variables; auto PV = PreservedVariables.find(SP); if (PV != PreservedVariables.end()) Variables.append(PV->second.begin(), PV->second.end()); DINodeArray AV = getOrCreateArray(Variables); TempMDTuple(Temp)->replaceAllUsesWith(AV.get()); }; for (auto *SP : SPs) resolveVariables(SP); for (auto *N : RetainValues) if (auto *SP = dyn_cast<DISubprogram>(N)) resolveVariables(SP); if (!AllGVs.empty()) CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs)); if (!AllImportedModules.empty()) CUNode->replaceImportedEntities(MDTuple::get( VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(), AllImportedModules.end()))); for (const auto &I : AllMacrosPerParent) { // DIMacroNode's with nullptr parent are DICompileUnit direct children. if (!I.first) { CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef())); continue; } // Otherwise, it must be a temporary DIMacroFile that need to be resolved. auto *TMF = cast<DIMacroFile>(I.first); auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file, TMF->getLine(), TMF->getFile(), getOrCreateMacroArray(I.second.getArrayRef())); replaceTemporary(llvm::TempDIMacroNode(TMF), MF); } // Now that all temp nodes have been replaced or deleted, resolve remaining // cycles. for (const auto &N : UnresolvedNodes) if (N && !N->isResolved()) N->resolveCycles(); UnresolvedNodes.clear(); // Can't handle unresolved nodes anymore. AllowUnresolvedNodes = false; } /// If N is compile unit return NULL otherwise return N. static DIScope *getNonCompileUnitScope(DIScope *N) { if (!N || isa<DICompileUnit>(N)) return nullptr; return cast<DIScope>(N); } DICompileUnit *DIBuilder::createCompileUnit( unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId, bool SplitDebugInlining) { assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && "Invalid Language tag"); assert(!CUNode && "Can only make one compile unit per DIBuilder instance"); CUNode = DICompileUnit::getDistinct( VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId, SplitDebugInlining); // Create a named metadata so that it is easier to find cu in a module. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->addOperand(CUNode); trackIfUnresolved(CUNode); return CUNode; } static DIImportedEntity * createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context, Metadata *NS, unsigned Line, StringRef Name, SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) { unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size(); auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name); if (EntitiesCount < C.pImpl->DIImportedEntitys.size()) // A new Imported Entity was just added to the context. // Add it to the Imported Modules list. AllImportedModules.emplace_back(M); return M; } DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DINamespace *NS, unsigned Line) { return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, Context, NS, Line, StringRef(), AllImportedModules); } DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIImportedEntity *NS, unsigned Line) { return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, Context, NS, Line, StringRef(), AllImportedModules); } DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M, unsigned Line) { return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module, Context, M, Line, StringRef(), AllImportedModules); } DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context, DINode *Decl, unsigned Line, StringRef Name) { // Make sure to use the unique identifier based metadata reference for // types that have one. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration, Context, Decl, Line, Name, AllImportedModules); } DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory, DIFile::ChecksumKind CSKind, StringRef Checksum) { return DIFile::get(VMContext, Filename, Directory, CSKind, Checksum); } DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber, unsigned MacroType, StringRef Name, StringRef Value) { assert(!Name.empty() && "Unable to create macro without name"); assert((MacroType == dwarf::DW_MACINFO_undef || MacroType == dwarf::DW_MACINFO_define) && "Unexpected macro type"); auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value); AllMacrosPerParent[Parent].insert(M); return M; } DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent, unsigned LineNumber, DIFile *File) { auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file, LineNumber, File, DIMacroNodeArray()) .release(); AllMacrosPerParent[Parent].insert(MF); // Add the new temporary DIMacroFile to the macro per parent map as a parent. // This is needed to assure DIMacroFile with no children to have an entry in // the map. Otherwise, it will not be resolved in DIBuilder::finalize(). AllMacrosPerParent.insert({MF, {}}); return MF; } DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) { assert(!Name.empty() && "Unable to create enumerator without name"); return DIEnumerator::get(VMContext, Val, Name); } DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) { assert(!Name.empty() && "Unable to create type without name"); return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name); } DIBasicType *DIBuilder::createNullPtrType() { return createUnspecifiedType("decltype(nullptr)"); } DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits, unsigned Encoding) { assert(!Name.empty() && "Unable to create type without name"); return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits, 0, Encoding); } DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) { return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0, 0, 0, DINode::FlagZero); } DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy, uint64_t SizeInBits, uint32_t AlignInBits, StringRef Name) { // FIXME: Why is there a name here? return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name, nullptr, 0, nullptr, PointeeTy, SizeInBits, AlignInBits, 0, DINode::FlagZero); } DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy, DIType *Base, uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags) { return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "", nullptr, 0, nullptr, PointeeTy, SizeInBits, AlignInBits, 0, Flags, Base); } DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy, uint64_t SizeInBits, uint32_t AlignInBits) { assert(RTy && "Unable to create reference type"); return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy, SizeInBits, AlignInBits, 0, DINode::FlagZero); } DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name, DIFile *File, unsigned LineNo, DIScope *Context) { return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File, LineNo, getNonCompileUnitScope(Context), Ty, 0, 0, 0, DINode::FlagZero); } DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) { assert(Ty && "Invalid type!"); assert(FriendTy && "Invalid friend type!"); return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty, FriendTy, 0, 0, 0, DINode::FlagZero); } DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy, uint64_t BaseOffset, DINode::DIFlags Flags) { assert(Ty && "Unable to create inheritance"); return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr, 0, Ty, BaseTy, 0, 0, BaseOffset, Flags); } DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DINode::DIFlags Flags, DIType *Ty) { return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, getNonCompileUnitScope(Scope), Ty, SizeInBits, AlignInBits, OffsetInBits, Flags); } static ConstantAsMetadata *getConstantOrNull(Constant *C) { if (C) return ConstantAsMetadata::get(C); return nullptr; } DIDerivedType *DIBuilder::createBitFieldMemberType( DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits, DINode::DIFlags Flags, DIType *Ty) { Flags |= DINode::FlagBitField; return DIDerivedType::get( VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0, OffsetInBits, Flags, ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64), StorageOffsetInBits))); } DIDerivedType * DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, DIType *Ty, DINode::DIFlags Flags, llvm::Constant *Val, uint32_t AlignInBits) { Flags |= DINode::FlagStaticMember; return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, getNonCompileUnitScope(Scope), Ty, 0, AlignInBits, 0, Flags, getConstantOrNull(Val)); } DIDerivedType * DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DINode::DIFlags Flags, DIType *Ty, MDNode *PropertyNode) { return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File, LineNumber, getNonCompileUnitScope(File), Ty, SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode); } DIObjCProperty * DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber, StringRef GetterName, StringRef SetterName, unsigned PropertyAttributes, DIType *Ty) { return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName, SetterName, PropertyAttributes, Ty); } DITemplateTypeParameter * DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name, DIType *Ty) { assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); return DITemplateTypeParameter::get(VMContext, Name, Ty); } static DITemplateValueParameter * createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag, DIScope *Context, StringRef Name, DIType *Ty, Metadata *MD) { assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit"); return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD); } DITemplateValueParameter * DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name, DIType *Ty, Constant *Val) { return createTemplateValueParameterHelper( VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty, getConstantOrNull(Val)); } DITemplateValueParameter * DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name, DIType *Ty, StringRef Val) { return createTemplateValueParameterHelper( VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty, MDString::get(VMContext, Val)); } DITemplateValueParameter * DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name, DIType *Ty, DINodeArray Val) { return createTemplateValueParameterHelper( VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty, Val.get()); } DICompositeType *DIBuilder::createClassType( DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits, DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) { assert((!Context || isa<DIScope>(Context)) && "createClassType should be called with a valid Context"); auto *R = DICompositeType::get( VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, 0, VTableHolder, cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier); trackIfUnresolved(R); return R; } DICompositeType *DIBuilder::createStructType( DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang, DIType *VTableHolder, StringRef UniqueIdentifier) { auto *R = DICompositeType::get( VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber, getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0, Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier); trackIfUnresolved(R); return R; } DICompositeType *DIBuilder::createUnionType( DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) { auto *R = DICompositeType::get( VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber, getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier); trackIfUnresolved(R); return R; } DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes, DINode::DIFlags Flags, unsigned CC) { return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes); } DICompositeType *DIBuilder::createExternalTypeRef(unsigned Tag, DIFile *File, StringRef UniqueIdentifier) { assert(!UniqueIdentifier.empty() && "external type ref without uid"); return DICompositeType::get(VMContext, Tag, "", nullptr, 0, nullptr, nullptr, 0, 0, 0, DINode::FlagExternalTypeRef, nullptr, 0, nullptr, nullptr, UniqueIdentifier); } DICompositeType *DIBuilder::createEnumerationType( DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber, uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements, DIType *UnderlyingType, StringRef UniqueIdentifier) { auto *CTy = DICompositeType::get( VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber, getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0, DINode::FlagZero, Elements, 0, nullptr, nullptr, UniqueIdentifier); AllEnumTypes.push_back(CTy); trackIfUnresolved(CTy); return CTy; } DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint32_t AlignInBits, DIType *Ty, DINodeArray Subscripts) { auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, nullptr, Ty, Size, AlignInBits, 0, DINode::FlagZero, Subscripts, 0, nullptr); trackIfUnresolved(R); return R; } DICompositeType *DIBuilder::createVectorType(uint64_t Size, uint32_t AlignInBits, DIType *Ty, DINodeArray Subscripts) { auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, nullptr, Ty, Size, AlignInBits, 0, DINode::FlagVector, Subscripts, 0, nullptr); trackIfUnresolved(R); return R; } static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty, DINode::DIFlags FlagsToSet) { auto NewTy = Ty->clone(); NewTy->setFlags(NewTy->getFlags() | FlagsToSet); return MDNode::replaceWithUniqued(std::move(NewTy)); } DIType *DIBuilder::createArtificialType(DIType *Ty) { // FIXME: Restrict this to the nodes where it's valid. if (Ty->isArtificial()) return Ty; return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial); } DIType *DIBuilder::createObjectPointerType(DIType *Ty) { // FIXME: Restrict this to the nodes where it's valid. if (Ty->isObjectPointer()) return Ty; DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial; return createTypeWithFlags(VMContext, Ty, Flags); } void DIBuilder::retainType(DIScope *T) { assert(T && "Expected non-null type"); assert((isa<DIType>(T) || (isa<DISubprogram>(T) && cast<DISubprogram>(T)->isDefinition() == false)) && "Expected type or subprogram declaration"); AllRetainTypes.emplace_back(T); } DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; } DICompositeType * DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, StringRef UniqueIdentifier) { // FIXME: Define in terms of createReplaceableForwardDecl() by calling // replaceWithUniqued(). auto *RetTy = DICompositeType::get( VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr, nullptr, UniqueIdentifier); trackIfUnresolved(RetTy); return RetTy; } DICompositeType *DIBuilder::createReplaceableCompositeType( unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags, StringRef UniqueIdentifier) { auto *RetTy = DICompositeType::getTemporary( VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr, nullptr, UniqueIdentifier) .release(); trackIfUnresolved(RetTy); return RetTy; } DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) { return MDTuple::get(VMContext, Elements); } DIMacroNodeArray DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) { return MDTuple::get(VMContext, Elements); } DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) { SmallVector<llvm::Metadata *, 16> Elts; for (unsigned i = 0, e = Elements.size(); i != e; ++i) { if (Elements[i] && isa<MDNode>(Elements[i])) Elts.push_back(cast<DIType>(Elements[i])); else Elts.push_back(Elements[i]); } return DITypeRefArray(MDNode::get(VMContext, Elts)); } DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) { return DISubrange::get(VMContext, Count, Lo); } static void checkGlobalVariableScope(DIScope *Context) { #ifndef NDEBUG if (auto *CT = dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context))) assert(CT->getIdentifier().empty() && "Context of a global variable should not be a type with identifier"); #endif } DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression( DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, unsigned LineNumber, DIType *Ty, bool isLocalToUnit, DIExpression *Expr, MDNode *Decl, uint32_t AlignInBits) { checkGlobalVariableScope(Context); auto *GV = DIGlobalVariable::getDistinct( VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, LineNumber, Ty, isLocalToUnit, true, cast_or_null<DIDerivedType>(Decl), AlignInBits); auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr); AllGVs.push_back(N); return N; } DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl( DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, unsigned LineNumber, DIType *Ty, bool isLocalToUnit, MDNode *Decl, uint32_t AlignInBits) { checkGlobalVariableScope(Context); return DIGlobalVariable::getTemporary( VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F, LineNumber, Ty, isLocalToUnit, false, cast_or_null<DIDerivedType>(Decl), AlignInBits) .release(); } static DILocalVariable *createLocalVariable( LLVMContext &VMContext, DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables, DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags, uint32_t AlignInBits) { // FIXME: Why getNonCompileUnitScope()? // FIXME: Why is "!Context" okay here? // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT // the only valid scopes)? DIScope *Context = getNonCompileUnitScope(Scope); auto *Node = DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name, File, LineNo, Ty, ArgNo, Flags, AlignInBits); if (AlwaysPreserve) { // The optimizer may remove local variables. If there is an interest // to preserve variable info in such situation then stash it in a // named mdnode. DISubprogram *Fn = getDISubprogram(Scope); assert(Fn && "Missing subprogram for local variable"); PreservedVariables[Fn].emplace_back(Node); } return Node; } DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags, uint32_t AlignInBits) { return createLocalVariable(VMContext, PreservedVariables, Scope, Name, /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve, Flags, AlignInBits); } DILocalVariable *DIBuilder::createParameterVariable( DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File, unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) { assert(ArgNo && "Expected non-zero argument number for parameter"); return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo, File, LineNo, Ty, AlwaysPreserve, Flags, /* AlignInBits */0); } DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) { return DIExpression::get(VMContext, Addr); } DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) { // TODO: Remove the callers of this signed version and delete. SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end()); return createExpression(Addr); } DIExpression *DIBuilder::createFragmentExpression(unsigned OffsetInBytes, unsigned SizeInBytes) { uint64_t Addr[] = {dwarf::DW_OP_LLVM_fragment, OffsetInBytes, SizeInBytes}; return DIExpression::get(VMContext, Addr); } template <class... Ts> static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) { if (IsDistinct) return DISubprogram::getDistinct(std::forward<Ts>(Args)...); return DISubprogram::get(std::forward<Ts>(Args)...); } DISubprogram *DIBuilder::createFunction( DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags, bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl) { auto *Node = getSubprogram( /* IsDistinct = */ isDefinition, VMContext, getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl, MDTuple::getTemporary(VMContext, None).release()); if (isDefinition) AllSubprograms.push_back(Node); trackIfUnresolved(Node); return Node; } DISubprogram *DIBuilder::createTempFunctionFwdDecl( DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File, unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags, bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl) { return DISubprogram::getTemporary( VMContext, getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl, nullptr) .release(); } DISubprogram *DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F, unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit, bool isDefinition, unsigned VK, unsigned VIndex, int ThisAdjustment, DIType *VTableHolder, DINode::DIFlags Flags, bool isOptimized, DITemplateParameterArray TParams) { assert(getNonCompileUnitScope(Context) && "Methods should have both a Context and a context that isn't " "the compile unit."); // FIXME: Do we want to use different scope/lines? auto *SP = getSubprogram( /* IsDistinct = */ isDefinition, VMContext, cast<DIScope>(Context), Name, LinkageName, F, LineNo, Ty, isLocalToUnit, isDefinition, LineNo, VTableHolder, VK, VIndex, ThisAdjustment, Flags, isOptimized, isDefinition ? CUNode : nullptr, TParams, nullptr, nullptr); if (isDefinition) AllSubprograms.push_back(SP); trackIfUnresolved(SP); return SP; } DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo, bool ExportSymbols) { return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name, LineNo, ExportSymbols); } DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name, StringRef ConfigurationMacros, StringRef IncludePath, StringRef ISysRoot) { return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name, ConfigurationMacros, IncludePath, ISysRoot); } DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope, DIFile *File, unsigned Discriminator) { return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator); } DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File, unsigned Line, unsigned Col) { // Make these distinct, to avoid merging two lexical blocks on the same // file/line/column. return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope), File, Line, Col); } static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) { assert(V && "no value passed to dbg intrinsic"); return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V)); } static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) { I->setDebugLoc(const_cast<DILocation *>(DL)); return I; } Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, Instruction *InsertBefore) { assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); assert(DL && "Expected debug loc"); assert(DL->getScope()->getSubprogram() == VarInfo->getScope()->getSubprogram() && "Expected matching subprograms"); if (!DeclareFn) DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); trackIfUnresolved(VarInfo); trackIfUnresolved(Expr); Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), MetadataAsValue::get(VMContext, VarInfo), MetadataAsValue::get(VMContext, Expr)}; return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL); } Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, BasicBlock *InsertAtEnd) { assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare"); assert(DL && "Expected debug loc"); assert(DL->getScope()->getSubprogram() == VarInfo->getScope()->getSubprogram() && "Expected matching subprograms"); if (!DeclareFn) DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare); trackIfUnresolved(VarInfo); trackIfUnresolved(Expr); Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage), MetadataAsValue::get(VMContext, VarInfo), MetadataAsValue::get(VMContext, Expr)}; // If this block already has a terminator then insert this intrinsic // before the terminator. if (TerminatorInst *T = InsertAtEnd->getTerminator()) return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL); return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL); } Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, Instruction *InsertBefore) { assert(V && "no value passed to dbg.value"); assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); assert(DL && "Expected debug loc"); assert(DL->getScope()->getSubprogram() == VarInfo->getScope()->getSubprogram() && "Expected matching subprograms"); if (!ValueFn) ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); trackIfUnresolved(VarInfo); trackIfUnresolved(Expr); Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), ConstantInt::get(Type::getInt64Ty(VMContext), Offset), MetadataAsValue::get(VMContext, VarInfo), MetadataAsValue::get(VMContext, Expr)}; return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL); } Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset, DILocalVariable *VarInfo, DIExpression *Expr, const DILocation *DL, BasicBlock *InsertAtEnd) { assert(V && "no value passed to dbg.value"); assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value"); assert(DL && "Expected debug loc"); assert(DL->getScope()->getSubprogram() == VarInfo->getScope()->getSubprogram() && "Expected matching subprograms"); if (!ValueFn) ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value); trackIfUnresolved(VarInfo); trackIfUnresolved(Expr); Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V), ConstantInt::get(Type::getInt64Ty(VMContext), Offset), MetadataAsValue::get(VMContext, VarInfo), MetadataAsValue::get(VMContext, Expr)}; return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL); } void DIBuilder::replaceVTableHolder(DICompositeType *&T, DICompositeType *VTableHolder) { { TypedTrackingMDRef<DICompositeType> N(T); N->replaceVTableHolder(VTableHolder); T = N.get(); } // If this didn't create a self-reference, just return. if (T != VTableHolder) return; // Look for unresolved operands. T will drop RAUW support, orphaning any // cycles underneath it. if (T->isResolved()) for (const MDOperand &O : T->operands()) if (auto *N = dyn_cast_or_null<MDNode>(O)) trackIfUnresolved(N); } void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements, DINodeArray TParams) { { TypedTrackingMDRef<DICompositeType> N(T); if (Elements) N->replaceElements(Elements); if (TParams) N->replaceTemplateParams(DITemplateParameterArray(TParams)); T = N.get(); } // If T isn't resolved, there's no problem. if (!T->isResolved()) return; // If T is resolved, it may be due to a self-reference cycle. Track the // arrays explicitly if they're unresolved, or else the cycles will be // orphaned. if (Elements) trackIfUnresolved(Elements.get()); if (TParams) trackIfUnresolved(TParams.get()); }
mit
dreampet/gitlab
spec/requests/projects/cycle_analytics_events_spec.rb
4538
require 'spec_helper' describe 'cycle analytics events' do let(:user) { create(:user) } let(:project) { create(:project, :repository, public_builds: false) } let(:issue) { create(:issue, project: project, created_at: 2.days.ago) } describe 'GET /:namespace/:project/cycle_analytics/events/issues' do before do project.add_developer(user) 3.times do |count| Timecop.freeze(Time.now + count.days) do create_cycle end end deploy_master(user, project) login_as(user) end it 'lists the issue events' do get project_cycle_analytics_issue_path(project, format: :json) first_issue_iid = project.issues.sort_by_attribute(:created_desc).pluck(:iid).first.to_s expect(json_response['events']).not_to be_empty expect(json_response['events'].first['iid']).to eq(first_issue_iid) end it 'lists the plan events' do get project_cycle_analytics_plan_path(project, format: :json) first_mr_short_sha = project.merge_requests.sort_by_attribute(:created_asc).first.commits.first.short_id expect(json_response['events']).not_to be_empty expect(json_response['events'].first['short_sha']).to eq(first_mr_short_sha) end it 'lists the code events' do get project_cycle_analytics_code_path(project, format: :json) expect(json_response['events']).not_to be_empty first_mr_iid = project.merge_requests.sort_by_attribute(:created_desc).pluck(:iid).first.to_s expect(json_response['events'].first['iid']).to eq(first_mr_iid) end it 'lists the test events' do get project_cycle_analytics_test_path(project, format: :json) expect(json_response['events']).not_to be_empty expect(json_response['events'].first['date']).not_to be_empty end it 'lists the review events' do get project_cycle_analytics_review_path(project, format: :json) first_mr_iid = project.merge_requests.sort_by_attribute(:created_desc).pluck(:iid).first.to_s expect(json_response['events']).not_to be_empty expect(json_response['events'].first['iid']).to eq(first_mr_iid) end it 'lists the staging events' do get project_cycle_analytics_staging_path(project, format: :json) expect(json_response['events']).not_to be_empty expect(json_response['events'].first['date']).not_to be_empty end it 'lists the production events' do get project_cycle_analytics_production_path(project, format: :json) first_issue_iid = project.issues.sort_by_attribute(:created_desc).pluck(:iid).first.to_s expect(json_response['events']).not_to be_empty expect(json_response['events'].first['iid']).to eq(first_issue_iid) end context 'specific branch' do it 'lists the test events' do branch = project.merge_requests.first.source_branch get project_cycle_analytics_test_path(project, format: :json, branch: branch) expect(json_response['events']).not_to be_empty expect(json_response['events'].first['date']).not_to be_empty end end context 'with private project and builds' do before do project.members.last.update(access_level: Gitlab::Access::GUEST) end it 'does not list the test events' do get project_cycle_analytics_test_path(project, format: :json) expect(response).to have_gitlab_http_status(:not_found) end it 'does not list the staging events' do get project_cycle_analytics_staging_path(project, format: :json) expect(response).to have_gitlab_http_status(:not_found) end it 'lists the issue events' do get project_cycle_analytics_issue_path(project, format: :json) expect(response).to have_gitlab_http_status(:ok) end end end def create_cycle milestone = create(:milestone, project: project) issue.update(milestone: milestone) mr = create_merge_request_closing_issue(user, project, issue, commit_message: "References #{issue.to_reference}") pipeline = create(:ci_empty_pipeline, status: 'created', project: project, ref: mr.source_branch, sha: mr.source_branch_sha, head_pipeline_of: mr) pipeline.run create(:ci_build, pipeline: pipeline, status: :success, author: user) create(:ci_build, pipeline: pipeline, status: :success, author: user) merge_merge_requests_closing_issue(user, project, issue) ProcessCommitWorker.new.perform(project.id, user.id, mr.commits.last.to_hash) end end
mit
lightscript/babylon-lightscript
test/fixtures/lightscript/index-dot-access/decimal-method/actual.js
15
0.0.toString()
mit
airgames/vuforia-gamekit-integration
Gamekit/Engine/LogicBricks/gkExpressionController.cpp
2970
/* ------------------------------------------------------------------------------- This file is part of OgreKit. http://gamekit.googlecode.com/ Copyright (c) 2006-2010 harkon.kr. Contributor(s): none yet. ------------------------------------------------------------------------------- This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------- */ #include "gkCommon.h" #ifdef OGREKIT_USE_LUA #include "gkExpressionController.h" #include "gkLogicManager.h" #include "gkTextManager.h" #include "gkTextFile.h" #include "gkUtils.h" #include "Script/Lua/gkLuaManager.h" #include "Script/Lua/gkLuaUtils.h" gkExpressionController::gkExpressionController(gkGameObject* object, gkLogicLink* link, const gkString& name) : gkLogicController(object, link, name), m_script(0), m_error(false), m_isModule(false) { } gkExpressionController::~gkExpressionController() { if (m_script) { //gkLuaManager::getSingleton().destroy(m_script); //TODO:use shared ptr destroy m_script = 0; } } gkLogicBrick* gkExpressionController::clone(gkLogicLink* link, gkGameObject* dest) { gkExpressionController* cont = new gkExpressionController(*this); cont->cloneImpl(link, dest); return cont; } void gkExpressionController::setExpression(const gkString& str) { gkString expr = "return " + str + "\n"; gkLuaScript* scrpt = gkLuaManager::getSingleton().createFromText( gkResourceName(gkUtils::getUniqueName(m_name), getObjectGroupName()), expr); if (scrpt) m_script = scrpt; } void gkExpressionController::execute(void) { if (m_error || m_sensors.empty()) return; // Main script, can be null. if (m_script != 0) { m_error = !m_script->execute(); if (!m_error && !m_actuators.empty()) { bool ret = m_script->getReturnBoolValue(); gkLogicManager& mgr = gkLogicManager::getSingleton(); gkActuatorIterator it(m_actuators); while (it.hasMoreElements()) { gkLogicActuator* act = it.getNext(); mgr.push(this, act, ret); } } } } #endif //OGREKIT_USE_LUA
mit
okulbilisim/ojs
src/Vipa/JournalBundle/Entity/ArticleSubmissionFileRepository.php
292
<?php namespace Vipa\JournalBundle\Entity; use Doctrine\ORM\EntityRepository; /** * ArticleSubmissionFileRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ArticleSubmissionFileRepository extends EntityRepository { }
mit
demarius/xy
lib/old2d.js
2257
function Point(x, y) { // :: Int -> Int -> Int -> Point if (x instanceof Array) { this.init(x[0], x[1]) } else { this.init(x, y) } this.init = function (x, y) { this.x = Math.round(x) || 0 this.y = Math.round(y) || 0 } } Point.prototype.rotate2d = function (n, xbit, ybit) { // : Int -> Int -> Int -> Point var rotate = rotate2d(n, this.x, this.y, xbit, ybit) this.x = rotate[0], this.y = rotate[1] } function convert2dPointToDistance (p, height) { // :: Int -> Int -> Int -> Int if (p instanceof Array) p = new Point(p) var xbit, ybit, level, d = 0 var forHeight = p.x > p.y ? p.x : p.y // needs some tests to make sure height is compatible // What keeps the user from putting 54 down as the height while (forHeight >= height) { height *=2 } // For each Hilbert level, we want to add an amount to // `d` based on which region we are in for (level = height / 2; level > 0; level = Math.floor(level / 2)) { // Determine what region we're in xbit = (p.x & level) > 0 ybit = (p.y & level) > 0 // increase distance based on region d += level * level * ((3 * xbit) ^ ybit) // rotate so that we'll be in sync with the next // region. p.rotate2d(level, xbit, ybit) } return d } function convertDistanceTo2dPoint (distance, height) { // :: Int -> Int -> [Int, Int] distance = Math.floor(distance) var xbit, ybit, level, p = new Point(0, 0) if (height <= Math.sqrt(distance)) { height = 2 while (height <= Math.sqrt(distance)) { height *=2 } } for (level = 1; level < height; level *= 2) { xbit = 1 & (distance / 2) ybit = 1 & (distance ^ xbit) p.rotate2d(level, xbit, ybit) p.x += level * xbit p.y += level * ybit distance = Math.floor(distance / 4) } return [p.x, p.y] } function rotate2d (n, x, y, xbit, ybit) { // :: Int -> Int -> Int -> Int -> Int -> [Int, Int] if (ybit == 0 ) { if (xbit == 1) { x = n - 1 - x y = n - 1 - y } var temp = x x = y y = temp } return [x, y] }
mit
openva/richmondsunlight.com
htdocs/includes/class.User.php
12678
<?php class User { /* * A wrapper around get_user(), in functions.inc.php. */ public function get() { $this->data = get_user(); if ($this->data == FALSE) { return FALSE; } return TRUE; } /* * A reimplementation logged_in() function, in functions.inc.php, but that returns not just * TRUE or FALSE, but also whether the user is registered. */ public function logged_in($check_if_registered = '') { /* * If there's no session ID, they can't be registered. */ if (empty($_SESSION['id'])) { return FALSE; } /* * If this session ID is stored in Memcached, then we don't need to query the database. */ if (MEMCACHED_SERVER != '') { $mc = new Memcached(); $mc->addServer(MEMCACHED_SERVER, MEMCACHED_PORT); $result = $mc->get('user-session-' . $_SESSION['id']); if ($mc->getResultCode() === 0) { /* * Indicate whether this is a registered user -- that is, somebody who has actually * created an account. (That's the value of "user-session-[id]" -- true or false.) */ $this->registered = $result; /* * Report that this is a user. */ return TRUE; } } $database = new Database; $database->connect_mysqli(); $sql = 'SELECT id, password FROM users WHERE cookie_hash="' . mysqli_real_escape_string($GLOBALS['db'], $_SESSION['id']) . '"'; $result = mysqli_query($GLOBALS['db'], $sql); if (mysqli_num_rows($result) == 1) { $registered = mysqli_fetch_assoc($result); /* * The presence of a password indicates that it's a user who has created an account. */ if (!empty($registered['password'])) { $this->registered = TRUE; } else { $this->registered = FALSE; } /* * Store this session in Memcached for the next 30 minutes. */ if (MEMCACHED_SERVER != '') { $mc->set('user-session-' . $_SESSION['id'], $this->registered, (60 * 30)); } return TRUE; } return FALSE; } public function views_cloud() { # The user must be logged in. if (logged_in() !== TRUE) { return FALSE; } $database = new Database; $database->connect_mysqli(); # Get the user's account data. $user = get_user(); # Select the user's personal tag cloud. We don't want a crazy number of tags, so cap it # at 100. $sql = 'SELECT COUNT(*) AS count, tags.tag FROM bills_views LEFT JOIN tags ON bills_views.bill_id = tags.bill_id WHERE bills_views.user_id = ' . $user['id'] . ' AND tag IS NOT NULL GROUP BY tags.tag ORDER BY count DESC LIMIT 100'; $result = mysqli_query($GLOBALS['db'], $sql); # Unless we have ten tags, we just don't have enough data to continue. if (mysqli_num_rows($result) < 10) { return FALSE; } # Build up an array of tags, with the key being the tag and the value being the count. while ($tag = mysqli_fetch_array($result)) { $tag = array_map('stripslashes', $tag); $tags[$tag{'tag'}] = $tag['count']; } # Sort the tags in reverse order by key (their count), shave off the top 30, and then # resort alphabetically. arsort($tags); $tags = array_slice($tags, 0, 30, true); $tag_data['biggest'] = max(array_values($tags)); $tag_data['smallest'] = min(array_values($tags)); ksort($tags); return $tags; } # Provide a listing of bills that this bill has not seen, but would probably be interested # in. This works by getting tag cloud data for this user's bill views, using that raw data # to query a list of bills that he's liable to be interestd in, and then substracting out a # list of every bill that he's already seen. public function recommended_bills() { # Get the user's account data. $user = get_user(); /* * Connect to Memcached. */ if (MEMCACHED_SERVER != '') { $mc = new Memcached(); $mc->addServer(MEMCACHED_SERVER, MEMCACHED_PORT); # Get a list of recommended bills for this user. $result = $mc->get('recommendations-' . $user['id']); if ($mc->getResultCode() === 0) { $bills = unserialize($result); if ($bills !== FALSE) { return $bills; } } } $tags = User::views_cloud(); if ($tags === FALSE) { return FALSE; } $database = new Database; $database->connect_mysqli(); # Get a list of every bill that this user has looked at. $sql = 'SELECT DISTINCT bills_views.bill_id AS id FROM bills_views LEFT JOIN bills ON bills_views.bill_id = bills.id WHERE bills.session_id = ' . SESSION_ID . ' AND user_id = ' . $user['id']; $result = mysqli_query($GLOBALS['db'], $sql); if (mysqli_num_rows($result) > 0) { $bills_seen = array(); while ($bill = mysqli_fetch_assoc($result)) { $bills_seen[$bill{'id'}] = true; } } # Now get a list of every bill that this user is liable to be interested in, including ones # that he's seen before. $sql = 'SELECT DISTINCT bills.id, bills.number, bills.catch_line, DATE_FORMAT(bills.date_introduced, "%M %d, %Y") AS date_introduced, committees.name, sessions.year, ( SELECT translation FROM bills_status WHERE bill_id=bills.id AND translation IS NOT NULL ORDER BY date DESC, id DESC LIMIT 1 ) AS status, ( SELECT COUNT(*) FROM bills AS bills2 LEFT JOIN tags AS tags2 ON bills2.id=tags2.bill_id WHERE ('; # Using an array of tags established above, when listing the bill's tags, iterate # through them to create the SQL. The actual tag SQL is built up and then reused, # though slightly differently, later on in the SQL query, hence the str_replace. $tags_sql = ''; foreach ($tags as $tag=>$tmp) { $tags_sql .= 'tags2.tag = "' . $tag . '" OR '; } # Hack off the final " OR " $tags_sql = mb_substr($tags_sql, 0, -4); $sql .= $tags_sql; $tags_sql = str_replace('tags2', 'tags', $tags_sql); $sql .= ') AND bills2.id = bills.id ) AS count FROM bills LEFT JOIN tags ON bills.id=tags.bill_id LEFT JOIN sessions ON bills.session_id=sessions.id LEFT JOIN committees ON bills.last_committee_id = committees.id WHERE (' . $tags_sql . ') AND bills.session_id = ' . SESSION_ID . ' HAVING count > 2 ORDER BY count DESC LIMIT 100'; $result = mysqli_query($GLOBALS['db'], $sql); if (mysqli_num_rows($result) == 0) { return FALSE; } else { while ($bill = mysqli_fetch_assoc($result)) { $bill = array_map('stripslashes', $bill); if (!isset($bills_seen[$bill{'id'}])) { $bills[] = $bill; } } } # Now hack off the top 10 bills. $bills = array_slice($bills, 0, 10); # Store this user's recommendations in Memcached for the next half-hour. We keep it brief # because user sessions are unlikely to last longer than this and to allow their # recommendations to be updated as new bills are filed, as they view their recommended # bills, and as they view bills that cause their recommendations to change. if (MEMCACHED_SERVER != '') { $mc->set('recommendations-' . $user['id'], serialize($bills), (60 * 30)); } return $bills; } # List legislation in the current session that cite places physically near to the user. This is # based on the most ghetto possible geolocation comparison -- choosing bills with a latitude # and longitude that are within a fraction of a degree of the user's location and ordering the # resulting list by the size of the difference between the two. I'm not proud, but it's a great # deal easier than installing spatial extensions to MySQL. public function nearby_bills() { # Get the user's account data. $user = get_user(); if (!isset($user['latitude']) || !isset($user['longitude'])) { return FALSE; } $database = new Database; $database->connect_mysqli(); $sql = 'SELECT bills.id, bills.number, bills.catch_line, sessions.year, bills_places.placename, bills_places.latitude, bills_places.longitude, (' . $user['latitude'] . ' - bills_places.latitude) AS lat_diff, (' . $user['longitude'] . ' - bills_places.longitude) AS lon_diff FROM bills_places LEFT JOIN bills ON bills_places.bill_id = bills.id LEFT JOIN sessions ON bills.session_id=sessions.id WHERE (latitude >= ' . (round($user['latitude'], 1)-.25) . ' AND latitude <=' . (round($user['latitude'], 1)+.25) . ') AND (longitude <= ' . (round($user['longitude'], 1)+.25) . ' AND longitude >= ' . (round($user['longitude'], 1)-.25) . ') AND bills.session_id = ' . SESSION_ID . ' ORDER BY ( lat_diff + lon_diff ) DESC'; $result = mysqli_query($GLOBALS['db'], $sql); if (mysqli_num_rows($result) == 0) { return FALSE; } $bills = array(); while ($bill = mysqli_fetch_array($result)) { $bills[] = array_map('stripslashes', $bill); } return $bills; } # Provide some statistics about this user's tagging habits. public function tagging_stats() { # The user must be logged in. if (logged_in() !== TRUE) { return FALSE; } # Get the user's account data. $user = get_user(); $database = new Database; $database->connect_mysqli(); $sql = 'SELECT (SELECT COUNT(*) FROM tags WHERE user_id=' . $user['id'] . ') AS tags, (SELECT COUNT(DISTINCT(bill_id)) FROM tags WHERE user_id=' . $user['id'] . ') AS bills'; $result = mysqli_query($GLOBALS['db'], $sql); if (mysqli_num_rows($result) == 0) { return FALSE; } $stats = mysqli_fetch_object($result); return $stats; } # Get a listing of the comments by this user. public function list_comments() { # The user must be logged in. if (logged_in() !== TRUE) { return FALSE; } # Get the user's account data. $user = get_user(); $database = new Database; $database->connect_mysqli(); $sql = 'SELECT sessions.year AS bill_year, bills.number AS bill_number, bills.catch_line, DATE_FORMAT(comments.date_created, "%m/%d/%Y") AS date, comments.comment FROM comments LEFT JOIN bills ON comments.bill_id = bills.id LEFT JOIN sessions ON bills.session_id = sessions.id WHERE comments.user_id =' . $user['id'] . ' AND comments.status = "published" ORDER BY comments.date_created DESC LIMIT 10'; $result = mysqli_query($GLOBALS['db'], $sql); if (mysqli_num_rows($result) == 0) { return FALSE; } while ($comment = mysqli_fetch_assoc($result)) { $comments[] = $comment; } return $comments; } /** * Delete a user. **/ public function delete() { if (!isset($this->id)) { return FALSE; } $sql = 'DELETE FROM users WHERE id=' . $this->id; $result = mysqli_query($GLOBALS['db'], $sql); if ($result != TRUE) { return FALSE; } return TRUE; } }
mit
sashamitrovich/markscript-todo
server/node_modules/typescript-schema/lib/factoryToSerial.d.ts
201
import { ModelElementTemplate } from './model'; import * as f from './factories'; export declare function factoryToSerializable(): <U extends ModelElementTemplate>(factory: f.Factory<U>) => (() => U);
mit
smwa/storeman
build/api/models/Session.php
1679
<?php class Session extends MysqlActiveRecord { protected function getPrimaryKey() { return "id"; } protected function getTableName() { return "sessions"; } protected function getRelations() { return array( "User" => array( "relation" => self::belongsTo, "model" => "User", "localkey" => "userid", "foreignkey" => "id" ), ); } public $id, $userid, $sessionid, $lastactiontime; function __construct() { $this->sessionid = self::generateId(); $this->lastactiontime = date("Y-m-d H:i:s"); parent::__construct(); } public static function generateId() { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $string = ''; for ($i = 0; $i < 64; $i++) { $string .= $characters[mt_rand(0, strlen($characters) - 1)]; } return $string; } private static function clearOldSessions() { $sessions = self::find(array("lastactiontime" => "< ".date("Y-m-d H:i:s", strtotime("-24 hours")))); foreach ((array)$sessions as $session) { $session->delete(); } } public static function getUserIDBySessionID($sid) { self::clearOldSessions(); $user = self::findOne(array("sessionid" => $sid)); if ($user) { $user->lastactiontime = date("Y-m-d H:i:s"); $user->save(); return $user->userid; } return 0; } }
mit
space-wizards/space-station-14
Content.Server/AI/WorldState/States/Utility/LastUtilityScoreState.cs
559
using JetBrains.Annotations; namespace Content.Server.AI.WorldState.States.Utility { /// <summary> /// Used for the utility AI; sets the threshold score we need to beat /// </summary> [UsedImplicitly] public class LastUtilityScoreState : StateData<float> { public override string Name => "LastBonus"; private float _value = 0.0f; public void SetValue(float value) { _value = value; } public override float GetValue() { return _value; } } }
mit
ojengwa/cakephp-api-utils
app/Plugin/OAuth2/Vendor/OAuth2ServerPHP/src/OAuth2/GrantType/JWTBearer.php
9700
<?php /** * The JWT bearer authorization grant implements JWT (JSON Web Tokens) as a grant type per the IETF draft. * @see http://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-04#section-4 */ class OAuth2_GrantType_JWTBearer implements OAuth2_GrantTypeInterface, OAuth2_Response_ProviderInterface, OAuth2_ClientAssertionTypeInterface { private $storage; private $response; private $audience = null; private $jwt = null; private $undecodedJWT = null; private $jwtUtil; /** * Creates an instance of the JWT bearer grant type. * * @param OAuth2_Storage_JWTBearerInterface $storage * A valid storage interface that implements storage hooks for the JWT bearer grant type. * @param string $audience * The audience to validate the token against. This is usually the full URI of the OAuth grant requests endpoint. * @param OAuth2_Encryption_JWT OPTIONAL $jwtUtil * The class used to decode, encode and verify JWTs. */ public function __construct(OAuth2_Storage_JWTBearerInterface $storage, $audience, OAuth2_Encryption_JWT $jwtUtil = null) { $this->storage = $storage; $this->audience = $audience; if (is_null($jwtUtil)) { $jwtUtil = new OAuth2_Encryption_JWT(); } $this->jwtUtil = $jwtUtil; } /** * Returns the grant_type get parameter to identify the grant type request as JWT bearer authorization grant. * @return The string identifier for grant_type. * @see OAuth2_GrantTypeInterface::getQuerystringIdentifier() */ public function getQuerystringIdentifier() { return 'urn:ietf:params:oauth:grant-type:jwt-bearer'; } /** * Validates the request by making share all GET parameters exists. * @return TRUE if the request is valid, otherwise FALSE. * @see OAuth2_GrantTypeInterface::validateRequest() */ public function validateRequest($request) { if (!$request->request("assertion")) { $this->response = new OAuth2_Response_Error(400, 'invalid_request', 'Missing parameters: "assertion" required'); return false; } return true; } /** * Gets the data from the decoded JWT. * @return Array containing the token data if the JWT can be decoded. Otherwise, NULL is returned. * @see OAuth2_GrantTypeInterface::getTokenDataFromRequest() */ public function getTokenDataFromRequest($request) { if (!$request->request("assertion")) { $this->response = new OAuth2_Response_Error(400, 'invalid_request', 'Missing parameters: "assertion" required'); return null; } //Store the undecoded JWT for later use $this->undecodedJWT = $request->request('assertion'); //Decode the JWT $jwt = $this->jwtUtil->decode($request->request('assertion'), null, false); if (!$jwt) { $this->response = new OAuth2_Response_Error(400, 'invalid_request', "JWT is malformed"); return null; } $this->jwt = $jwt; $tokenData = array(); $tokenData['scope'] = $this->getJWTParameter('scope'); $tokenData['iss'] = $this->getJWTParameter('iss'); $tokenData['sub'] = $this->getJWTParameter('sub'); $tokenData['aud'] = $this->getJWTParameter('aud'); $tokenData['exp'] = $this->getJWTParameter('exp'); $tokenData['nbf'] = $this->getJWTParameter('nbf'); $tokenData['iat'] = $this->getJWTParameter('iat'); $tokenData['jti'] = $this->getJWTParameter('jti'); $tokenData['typ'] = $this->getJWTParameter('typ'); //Other token data in the claim foreach ($this->jwt as $key => $value) { if (!array_key_exists($key, $tokenData)) { $tokenData[$key] = $value; } } return $tokenData; } /** * Helper function to make it easier to return a JWT parameter. * @param string $parameter * The JWT parameter to get. * @param mixed $default * The value to return if the JWT parameter does not exist. * @return mixed * The JWT parameter. */ private function getJWTParameter($parameter, $default = null) { return isset($this->jwt->$parameter) ? $this->jwt->$parameter : null; } /** * Return the data used to verify the request. For JWT bearer authorization grants, the 'iss' is synonymous to the 'client_id'. * The subject is 'sub' and the 'client_secret' is the key to decode the JWT. * @return array An array of the client data containing the client_id. * @see OAuth2_ClientAssertionTypeInterface::getClientDataFromRequest() */ public function getClientDataFromRequest(OAuth2_RequestInterface $request) { $tokenData = $this->getTokenDataFromRequest($request); if (!$tokenData) { return null; } if (!isset($tokenData['iss'])) { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "Invalid issuer (iss) provided"); return null; } //Get the iss's public key (http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-06#section-4.1.1) $key = $this->storage->getClientKey($tokenData['iss'], $tokenData['sub']); if (!$key) { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "Invalid issuer (iss) or subject (sub) provided"); return null; } return array('client_id' => $tokenData['iss'], 'subject' => $tokenData['sub'], 'client_secret' => $key); } /** * Validates the client data by checking if the client_id exists in storage. It also checks to see if the client_id is associated with a key to decode the JWT. * @see OAuth2_ClientAssertionTypeInterface::validateClientData() */ public function validateClientData(array $clientData, $grantTypeIdentifier) { //Check that all array keys exist $diff = array_diff(array_keys($clientData), array('client_id', 'subject', 'client_secret')); if (!empty($diff)) { throw new DomainException('The clientData array is missing one or more of the following: client_id, subject, client_secret'); return false; } foreach ($clientData as $key => $value) { if (in_array($key, array('client_id', 'client_secret'))) { if (!isset($value)) { throw new LogicException('client_id and client_secret in the clientData array may not be null'); return false; } } } return true; } /** * Validates the token data using the rules in the IETF draft. * @see http://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-04#section-3 * @see OAuth2_GrantTypeInterface::validateTokenData() */ public function validateTokenData($tokenData, array $clientData) { // Note: Scope is validated in the client class //Check the expiry time $expiration = $tokenData['exp']; if (ctype_digit($expiration)) { if ($expiration <= time()) { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "JWT has expired"); return false; } } elseif (!$expiration) { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "Expiration (exp) time must be present"); return false; } else { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "Expiration (exp) time must be a unix time stamp"); return false; } //Check the not before time if ($notBefore = $tokenData['nbf']) { if (ctype_digit($notBefore)) { if ($notBefore > time()) { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "JWT cannot be used before the Not Before (nbf) time"); return false; } } else { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "Not Before (nbf) time must be a unix time stamp"); return false; } } //Check the audience if required to match $aud = $tokenData['aud']; if (!isset($aud) || ($aud != $this->audience)) { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "Invalid audience (aud)"); return false; } //Verify the JWT $jwt = $this->jwtUtil->decode($this->undecodedJWT, $clientData['client_secret'], true); if (!$jwt) { $this->response = new OAuth2_Response_Error(400, 'invalid_grant', "JWT failed signature verification"); return null; } return true; } /** * Creates an access token that is NOT associated with a refresh token. * If a subject (sub) the name of the user/account we are accessing data on behalf of. * @see OAuth2_GrantTypeInterface::createAccessToken() */ public function createAccessToken(OAuth2_ResponseType_AccessTokenInterface $accessToken, array $clientData, array $tokenData) { $includeRefreshToken = false; return $accessToken->createAccessToken($clientData['client_id'], $tokenData['sub'], $tokenData['scope'], $includeRefreshToken); } /** * Returns the response of this grant type. * @see OAuth2_Response_ProviderInterface::getResponse() */ public function getResponse() { return $this->response; } }
mit
ghtdak/txtorcon
txtorcon/spaghetti.py
3894
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function from __future__ import with_statement import warnings class FSM(object): """ Override Matcher and Handler and pass instances to add_handler to create transitions between states. If a transition handles something, it returns the next state. If you want something to track global state, but it in your data instance passed to process so that transitions, states can access it. """ states = [] state = None def __init__(self, states): """first state is the initial state""" if len(states) > 0: self.state = states[0] self.states = states def process(self, data): if self.state is None: raise RuntimeError("There is no initial state.") next_state = self.state.process(data) if next_state: self.state = next_state else: warnings.warn("No next state", RuntimeWarning) def add_state(self, state): # first added state is initial state if len(self.states) == 0: self.state = state self.states.append(state) def dotty(self): r = 'digraph fsm {\n\n' for s in self.states: r = r + s.dotty() r = r + '\n}\n' return r class State(object): def __init__(self, name): self.name = name self.transitions = [] def process(self, data): for t in self.transitions: r = t.process(data) if r is not None: return r return None def add_transition(self, t): self.transitions.append(t) t.start_state = self def add_transitions(self, transitions): for t in transitions: self.add_transition(t) def __str__(self): r = '<State %s [' % self.name for t in self.transitions: r = r + (' ->%s ' % t.next_state.name) r = r + ']>' return r def dotty(self): r = '%s;\n' % self.name r = r + 'edge [fontsize=8]\n' r = r + 'rankdir=TB;\nnodesep=2;\n' for t in self.transitions: r = r + '%s -> %s [label="%s\\n%s"]\n' % (self.name, t.next_state.name, t.matcher.__name__, t.handler.__name__) return r class Transition(object): def __init__(self, next_state, matcher, handler): self.matcher = matcher self.handler = handler self.start_state = None self.next_state = next_state if self.next_state is None: raise RuntimeError("next_state must be valid") def match(self, data): """ used by process; calls handler if matcher returns true for data by default. may override instead of providing a matcher methdo to ctor. """ if self.matcher is not None: return self.matcher(data) return True def handle(self, data): """ return next state. May override in a subclass to change behavior or pass a handler method to ctor """ if self.handler: state = self.handler(data) if state is None: return self.next_state return state return self.next_state def process(self, data): """return next state, or None if not handled.""" if self.match(data): return self.handle(data) return None def __str__(self): if self.start_state: return "<Transition %s->%s>" % (self.start_state.name, self.next_state.name) return "<Transition ->%s>" % (self.next_state.name,)
mit
salama/salama
lib/risc/fake_memory.rb
1255
module Risc # simulate memory during compile time. # # Memory comes in chunks, power of 2 chunks actually. # # Currently typed instance variables map to ruby instance variables and so do not # end up in memory. Memory being only for indexed word aligned access. # # Parfait really does everything else, apart from the internal_get/set # And our fake memory (other than hte previously used array, does bound check) class FakeMemory attr_reader :min , :object def initialize(object,from , size) @object = object @min = from @memory = Array.new(size) raise "only multiples of 2 !#{size}" unless size == 2**(Math.log2(size).to_i) end def set(index , value) range_check(index) _set(index,value) end alias :[]= :set def _set(index , value) @memory[index] = value value end def get(index) range_check(index) _get(index) end alias :[] :get def _get(index) @memory[index] end def size @memory.length end def range_check(index) raise "index too low #{index} < #{min} in #{object.class}" if index < 0 raise "index too big #{index} >= #{size} #{object.class}" if index >= size end end end
mit
nmengin/traefik
vendor/github.com/opencontainers/runc/libcontainer/container_linux.go
43337
// +build linux package libcontainer import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "reflect" "strings" "sync" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/golang/protobuf/proto" "github.com/opencontainers/runc/libcontainer/cgroups" "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/criurpc" "github.com/opencontainers/runc/libcontainer/system" "github.com/opencontainers/runc/libcontainer/utils" "github.com/syndtr/gocapability/capability" "github.com/vishvananda/netlink/nl" ) const stdioFdCount = 3 type linuxContainer struct { id string root string config *configs.Config cgroupManager cgroups.Manager initArgs []string initProcess parentProcess initProcessStartTime string criuPath string m sync.Mutex criuVersion int state containerState created time.Time } // State represents a running container's state type State struct { BaseState // Platform specific fields below here // Specifies if the container was started under the rootless mode. Rootless bool `json:"rootless"` // Path to all the cgroups setup for a container. Key is cgroup subsystem name // with the value as the path. CgroupPaths map[string]string `json:"cgroup_paths"` // NamespacePaths are filepaths to the container's namespaces. Key is the namespace type // with the value as the path. NamespacePaths map[configs.NamespaceType]string `json:"namespace_paths"` // Container's standard descriptors (std{in,out,err}), needed for checkpoint and restore ExternalDescriptors []string `json:"external_descriptors,omitempty"` } // Container is a libcontainer container object. // // Each container is thread-safe within the same process. Since a container can // be destroyed by a separate process, any function may return that the container // was not found. type Container interface { BaseContainer // Methods below here are platform specific // Checkpoint checkpoints the running container's state to disk using the criu(8) utility. // // errors: // Systemerror - System error. Checkpoint(criuOpts *CriuOpts) error // Restore restores the checkpointed container to a running state using the criu(8) utility. // // errors: // Systemerror - System error. Restore(process *Process, criuOpts *CriuOpts) error // If the Container state is RUNNING or CREATED, sets the Container state to PAUSING and pauses // the execution of any user processes. Asynchronously, when the container finished being paused the // state is changed to PAUSED. // If the Container state is PAUSED, do nothing. // // errors: // ContainerNotExists - Container no longer exists, // ContainerNotRunning - Container not running or created, // Systemerror - System error. Pause() error // If the Container state is PAUSED, resumes the execution of any user processes in the // Container before setting the Container state to RUNNING. // If the Container state is RUNNING, do nothing. // // errors: // ContainerNotExists - Container no longer exists, // ContainerNotPaused - Container is not paused, // Systemerror - System error. Resume() error // NotifyOOM returns a read-only channel signaling when the container receives an OOM notification. // // errors: // Systemerror - System error. NotifyOOM() (<-chan struct{}, error) // NotifyMemoryPressure returns a read-only channel signaling when the container reaches a given pressure level // // errors: // Systemerror - System error. NotifyMemoryPressure(level PressureLevel) (<-chan struct{}, error) } // ID returns the container's unique ID func (c *linuxContainer) ID() string { return c.id } // Config returns the container's configuration func (c *linuxContainer) Config() configs.Config { return *c.config } func (c *linuxContainer) Status() (Status, error) { c.m.Lock() defer c.m.Unlock() return c.currentStatus() } func (c *linuxContainer) State() (*State, error) { c.m.Lock() defer c.m.Unlock() return c.currentState() } func (c *linuxContainer) Processes() ([]int, error) { pids, err := c.cgroupManager.GetAllPids() if err != nil { return nil, newSystemErrorWithCause(err, "getting all container pids from cgroups") } return pids, nil } func (c *linuxContainer) Stats() (*Stats, error) { var ( err error stats = &Stats{} ) if stats.CgroupStats, err = c.cgroupManager.GetStats(); err != nil { return stats, newSystemErrorWithCause(err, "getting container stats from cgroups") } for _, iface := range c.config.Networks { switch iface.Type { case "veth": istats, err := getNetworkInterfaceStats(iface.HostInterfaceName) if err != nil { return stats, newSystemErrorWithCausef(err, "getting network stats for interface %q", iface.HostInterfaceName) } stats.Interfaces = append(stats.Interfaces, istats) } } return stats, nil } func (c *linuxContainer) Set(config configs.Config) error { c.m.Lock() defer c.m.Unlock() status, err := c.currentStatus() if err != nil { return err } if status == Stopped { return newGenericError(fmt.Errorf("container not running"), ContainerNotRunning) } c.config = &config return c.cgroupManager.Set(c.config) } func (c *linuxContainer) Start(process *Process) error { c.m.Lock() defer c.m.Unlock() status, err := c.currentStatus() if err != nil { return err } if status == Stopped { if err := c.createExecFifo(); err != nil { return err } } if err := c.start(process, status == Stopped); err != nil { if status == Stopped { c.deleteExecFifo() } return err } return nil } func (c *linuxContainer) Run(process *Process) error { c.m.Lock() status, err := c.currentStatus() if err != nil { c.m.Unlock() return err } c.m.Unlock() if err := c.Start(process); err != nil { return err } if status == Stopped { return c.exec() } return nil } func (c *linuxContainer) Exec() error { c.m.Lock() defer c.m.Unlock() return c.exec() } func (c *linuxContainer) exec() error { path := filepath.Join(c.root, execFifoFilename) f, err := os.OpenFile(path, os.O_RDONLY, 0) if err != nil { return newSystemErrorWithCause(err, "open exec fifo for reading") } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return err } if len(data) > 0 { os.Remove(path) return nil } return fmt.Errorf("cannot start an already running container") } func (c *linuxContainer) start(process *Process, isInit bool) error { parent, err := c.newParentProcess(process, isInit) if err != nil { return newSystemErrorWithCause(err, "creating new parent process") } if err := parent.start(); err != nil { // terminate the process to ensure that it properly is reaped. if err := parent.terminate(); err != nil { logrus.Warn(err) } return newSystemErrorWithCause(err, "starting container process") } // generate a timestamp indicating when the container was started c.created = time.Now().UTC() if isInit { c.state = &createdState{ c: c, } state, err := c.updateState(parent) if err != nil { return err } c.initProcessStartTime = state.InitProcessStartTime if c.config.Hooks != nil { s := configs.HookState{ Version: c.config.Version, ID: c.id, Pid: parent.pid(), Bundle: utils.SearchLabels(c.config.Labels, "bundle"), } for i, hook := range c.config.Hooks.Poststart { if err := hook.Run(s); err != nil { if err := parent.terminate(); err != nil { logrus.Warn(err) } return newSystemErrorWithCausef(err, "running poststart hook %d", i) } } } } else { c.state = &runningState{ c: c, } } return nil } func (c *linuxContainer) Signal(s os.Signal, all bool) error { if all { return signalAllProcesses(c.cgroupManager, s) } if err := c.initProcess.signal(s); err != nil { return newSystemErrorWithCause(err, "signaling init process") } return nil } func (c *linuxContainer) createExecFifo() error { rootuid, err := c.Config().HostRootUID() if err != nil { return err } rootgid, err := c.Config().HostRootGID() if err != nil { return err } fifoName := filepath.Join(c.root, execFifoFilename) if _, err := os.Stat(fifoName); err == nil { return fmt.Errorf("exec fifo %s already exists", fifoName) } oldMask := syscall.Umask(0000) if err := syscall.Mkfifo(fifoName, 0622); err != nil { syscall.Umask(oldMask) return err } syscall.Umask(oldMask) if err := os.Chown(fifoName, rootuid, rootgid); err != nil { return err } return nil } func (c *linuxContainer) deleteExecFifo() { fifoName := filepath.Join(c.root, execFifoFilename) os.Remove(fifoName) } func (c *linuxContainer) newParentProcess(p *Process, doInit bool) (parentProcess, error) { parentPipe, childPipe, err := utils.NewSockPair("init") if err != nil { return nil, newSystemErrorWithCause(err, "creating new init pipe") } cmd, err := c.commandTemplate(p, childPipe) if err != nil { return nil, newSystemErrorWithCause(err, "creating new command template") } if !doInit { return c.newSetnsProcess(p, cmd, parentPipe, childPipe) } // We only set up rootDir if we're not doing a `runc exec`. The reason for // this is to avoid cases where a racing, unprivileged process inside the // container can get access to the statedir file descriptor (which would // allow for container rootfs escape). rootDir, err := os.Open(c.root) if err != nil { return nil, err } cmd.ExtraFiles = append(cmd.ExtraFiles, rootDir) cmd.Env = append(cmd.Env, fmt.Sprintf("_LIBCONTAINER_STATEDIR=%d", stdioFdCount+len(cmd.ExtraFiles)-1)) return c.newInitProcess(p, cmd, parentPipe, childPipe, rootDir) } func (c *linuxContainer) commandTemplate(p *Process, childPipe *os.File) (*exec.Cmd, error) { cmd := exec.Command(c.initArgs[0], c.initArgs[1:]...) cmd.Stdin = p.Stdin cmd.Stdout = p.Stdout cmd.Stderr = p.Stderr cmd.Dir = c.config.Rootfs if cmd.SysProcAttr == nil { cmd.SysProcAttr = &syscall.SysProcAttr{} } cmd.ExtraFiles = append(cmd.ExtraFiles, p.ExtraFiles...) if p.ConsoleSocket != nil { cmd.ExtraFiles = append(cmd.ExtraFiles, p.ConsoleSocket) cmd.Env = append(cmd.Env, fmt.Sprintf("_LIBCONTAINER_CONSOLE=%d", stdioFdCount+len(cmd.ExtraFiles)-1), ) } cmd.ExtraFiles = append(cmd.ExtraFiles, childPipe) cmd.Env = append(cmd.Env, fmt.Sprintf("_LIBCONTAINER_INITPIPE=%d", stdioFdCount+len(cmd.ExtraFiles)-1), ) // NOTE: when running a container with no PID namespace and the parent process spawning the container is // PID1 the pdeathsig is being delivered to the container's init process by the kernel for some reason // even with the parent still running. if c.config.ParentDeathSignal > 0 { cmd.SysProcAttr.Pdeathsig = syscall.Signal(c.config.ParentDeathSignal) } return cmd, nil } func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe, rootDir *os.File) (*initProcess, error) { cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initStandard)) nsMaps := make(map[configs.NamespaceType]string) for _, ns := range c.config.Namespaces { if ns.Path != "" { nsMaps[ns.Type] = ns.Path } } _, sharePidns := nsMaps[configs.NEWPID] data, err := c.bootstrapData(c.config.Namespaces.CloneFlags(), nsMaps) if err != nil { return nil, err } return &initProcess{ cmd: cmd, childPipe: childPipe, parentPipe: parentPipe, manager: c.cgroupManager, config: c.newInitConfig(p), container: c, process: p, bootstrapData: data, sharePidns: sharePidns, rootDir: rootDir, }, nil } func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*setnsProcess, error) { cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initSetns)) state, err := c.currentState() if err != nil { return nil, newSystemErrorWithCause(err, "getting container's current state") } // for setns process, we don't have to set cloneflags as the process namespaces // will only be set via setns syscall data, err := c.bootstrapData(0, state.NamespacePaths) if err != nil { return nil, err } return &setnsProcess{ cmd: cmd, cgroupPaths: c.cgroupManager.GetPaths(), childPipe: childPipe, parentPipe: parentPipe, config: c.newInitConfig(p), process: p, bootstrapData: data, }, nil } func (c *linuxContainer) newInitConfig(process *Process) *initConfig { cfg := &initConfig{ Config: c.config, Args: process.Args, Env: process.Env, User: process.User, AdditionalGroups: process.AdditionalGroups, Cwd: process.Cwd, Capabilities: process.Capabilities, PassedFilesCount: len(process.ExtraFiles), ContainerId: c.ID(), NoNewPrivileges: c.config.NoNewPrivileges, Rootless: c.config.Rootless, AppArmorProfile: c.config.AppArmorProfile, ProcessLabel: c.config.ProcessLabel, Rlimits: c.config.Rlimits, } if process.NoNewPrivileges != nil { cfg.NoNewPrivileges = *process.NoNewPrivileges } if process.AppArmorProfile != "" { cfg.AppArmorProfile = process.AppArmorProfile } if process.Label != "" { cfg.ProcessLabel = process.Label } if len(process.Rlimits) > 0 { cfg.Rlimits = process.Rlimits } cfg.CreateConsole = process.ConsoleSocket != nil return cfg } func (c *linuxContainer) Destroy() error { c.m.Lock() defer c.m.Unlock() return c.state.destroy() } func (c *linuxContainer) Pause() error { c.m.Lock() defer c.m.Unlock() status, err := c.currentStatus() if err != nil { return err } switch status { case Running, Created: if err := c.cgroupManager.Freeze(configs.Frozen); err != nil { return err } return c.state.transition(&pausedState{ c: c, }) } return newGenericError(fmt.Errorf("container not running or created: %s", status), ContainerNotRunning) } func (c *linuxContainer) Resume() error { c.m.Lock() defer c.m.Unlock() status, err := c.currentStatus() if err != nil { return err } if status != Paused { return newGenericError(fmt.Errorf("container not paused"), ContainerNotPaused) } if err := c.cgroupManager.Freeze(configs.Thawed); err != nil { return err } return c.state.transition(&runningState{ c: c, }) } func (c *linuxContainer) NotifyOOM() (<-chan struct{}, error) { // XXX(cyphar): This requires cgroups. if c.config.Rootless { return nil, fmt.Errorf("cannot get OOM notifications from rootless container") } return notifyOnOOM(c.cgroupManager.GetPaths()) } func (c *linuxContainer) NotifyMemoryPressure(level PressureLevel) (<-chan struct{}, error) { // XXX(cyphar): This requires cgroups. if c.config.Rootless { return nil, fmt.Errorf("cannot get memory pressure notifications from rootless container") } return notifyMemoryPressure(c.cgroupManager.GetPaths(), level) } var criuFeatures *criurpc.CriuFeatures func (c *linuxContainer) checkCriuFeatures(criuOpts *CriuOpts, rpcOpts *criurpc.CriuOpts, criuFeat *criurpc.CriuFeatures) error { var t criurpc.CriuReqType t = criurpc.CriuReqType_FEATURE_CHECK if err := c.checkCriuVersion("1.8"); err != nil { // Feature checking was introduced with CRIU 1.8. // Ignore the feature check if an older CRIU version is used // and just act as before. // As all automated PR testing is done using CRIU 1.7 this // code will not be tested by automated PR testing. return nil } // make sure the features we are looking for are really not from // some previous check criuFeatures = nil req := &criurpc.CriuReq{ Type: &t, // Theoretically this should not be necessary but CRIU // segfaults if Opts is empty. // Fixed in CRIU 2.12 Opts: rpcOpts, Features: criuFeat, } err := c.criuSwrk(nil, req, criuOpts, false) if err != nil { logrus.Debugf("%s", err) return fmt.Errorf("CRIU feature check failed") } logrus.Debugf("Feature check says: %s", criuFeatures) missingFeatures := false if *criuFeat.MemTrack && !*criuFeatures.MemTrack { missingFeatures = true logrus.Debugf("CRIU does not support MemTrack") } if missingFeatures { return fmt.Errorf("CRIU is missing features") } return nil } // checkCriuVersion checks Criu version greater than or equal to minVersion func (c *linuxContainer) checkCriuVersion(minVersion string) error { var x, y, z, versionReq int _, err := fmt.Sscanf(minVersion, "%d.%d.%d\n", &x, &y, &z) // 1.5.2 if err != nil { _, err = fmt.Sscanf(minVersion, "Version: %d.%d\n", &x, &y) // 1.6 } versionReq = x*10000 + y*100 + z out, err := exec.Command(c.criuPath, "-V").Output() if err != nil { return fmt.Errorf("Unable to execute CRIU command: %s", c.criuPath) } x = 0 y = 0 z = 0 if ep := strings.Index(string(out), "-"); ep >= 0 { // criu Git version format var version string if sp := strings.Index(string(out), "GitID"); sp > 0 { version = string(out)[sp:ep] } else { return fmt.Errorf("Unable to parse the CRIU version: %s", c.criuPath) } n, err := fmt.Sscanf(string(version), "GitID: v%d.%d.%d", &x, &y, &z) // 1.5.2 if err != nil { n, err = fmt.Sscanf(string(version), "GitID: v%d.%d", &x, &y) // 1.6 y++ } else { z++ } if n < 2 || err != nil { return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", version, n, err) } } else { // criu release version format n, err := fmt.Sscanf(string(out), "Version: %d.%d.%d\n", &x, &y, &z) // 1.5.2 if err != nil { n, err = fmt.Sscanf(string(out), "Version: %d.%d\n", &x, &y) // 1.6 } if n < 2 || err != nil { return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", out, n, err) } } c.criuVersion = x*10000 + y*100 + z if c.criuVersion < versionReq { return fmt.Errorf("CRIU version must be %s or higher", minVersion) } return nil } const descriptorsFilename = "descriptors.json" func (c *linuxContainer) addCriuDumpMount(req *criurpc.CriuReq, m *configs.Mount) { mountDest := m.Destination if strings.HasPrefix(mountDest, c.config.Rootfs) { mountDest = mountDest[len(c.config.Rootfs):] } extMnt := &criurpc.ExtMountMap{ Key: proto.String(mountDest), Val: proto.String(mountDest), } req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt) } func (c *linuxContainer) addMaskPaths(req *criurpc.CriuReq) error { for _, path := range c.config.MaskPaths { fi, err := os.Stat(fmt.Sprintf("/proc/%d/root/%s", c.initProcess.pid(), path)) if err != nil { if os.IsNotExist(err) { continue } return err } if fi.IsDir() { continue } extMnt := &criurpc.ExtMountMap{ Key: proto.String(path), Val: proto.String("/dev/null"), } req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt) } return nil } func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error { c.m.Lock() defer c.m.Unlock() // TODO(avagin): Figure out how to make this work nicely. CRIU 2.0 has // support for doing unprivileged dumps, but the setup of // rootless containers might make this complicated. if c.config.Rootless { return fmt.Errorf("cannot checkpoint a rootless container") } if err := c.checkCriuVersion("1.5.2"); err != nil { return err } if criuOpts.ImagesDirectory == "" { return fmt.Errorf("invalid directory to save checkpoint") } // Since a container can be C/R'ed multiple times, // the checkpoint directory may already exist. if err := os.Mkdir(criuOpts.ImagesDirectory, 0755); err != nil && !os.IsExist(err) { return err } if criuOpts.WorkDirectory == "" { criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work") } if err := os.Mkdir(criuOpts.WorkDirectory, 0755); err != nil && !os.IsExist(err) { return err } workDir, err := os.Open(criuOpts.WorkDirectory) if err != nil { return err } defer workDir.Close() imageDir, err := os.Open(criuOpts.ImagesDirectory) if err != nil { return err } defer imageDir.Close() rpcOpts := criurpc.CriuOpts{ ImagesDirFd: proto.Int32(int32(imageDir.Fd())), WorkDirFd: proto.Int32(int32(workDir.Fd())), LogLevel: proto.Int32(4), LogFile: proto.String("dump.log"), Root: proto.String(c.config.Rootfs), ManageCgroups: proto.Bool(true), NotifyScripts: proto.Bool(true), Pid: proto.Int32(int32(c.initProcess.pid())), ShellJob: proto.Bool(criuOpts.ShellJob), LeaveRunning: proto.Bool(criuOpts.LeaveRunning), TcpEstablished: proto.Bool(criuOpts.TcpEstablished), ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections), FileLocks: proto.Bool(criuOpts.FileLocks), EmptyNs: proto.Uint32(criuOpts.EmptyNs), } // append optional criu opts, e.g., page-server and port if criuOpts.PageServer.Address != "" && criuOpts.PageServer.Port != 0 { rpcOpts.Ps = &criurpc.CriuPageServerInfo{ Address: proto.String(criuOpts.PageServer.Address), Port: proto.Int32(criuOpts.PageServer.Port), } } //pre-dump may need parentImage param to complete iterative migration if criuOpts.ParentImage != "" { rpcOpts.ParentImg = proto.String(criuOpts.ParentImage) rpcOpts.TrackMem = proto.Bool(true) } // append optional manage cgroups mode if criuOpts.ManageCgroupsMode != 0 { if err := c.checkCriuVersion("1.7"); err != nil { return err } mode := criurpc.CriuCgMode(criuOpts.ManageCgroupsMode) rpcOpts.ManageCgroupsMode = &mode } var t criurpc.CriuReqType if criuOpts.PreDump { feat := criurpc.CriuFeatures{ MemTrack: proto.Bool(true), } if err := c.checkCriuFeatures(criuOpts, &rpcOpts, &feat); err != nil { return err } t = criurpc.CriuReqType_PRE_DUMP } else { t = criurpc.CriuReqType_DUMP } req := &criurpc.CriuReq{ Type: &t, Opts: &rpcOpts, } //no need to dump these information in pre-dump if !criuOpts.PreDump { for _, m := range c.config.Mounts { switch m.Device { case "bind": c.addCriuDumpMount(req, m) break case "cgroup": binds, err := getCgroupMounts(m) if err != nil { return err } for _, b := range binds { c.addCriuDumpMount(req, b) } break } } if err := c.addMaskPaths(req); err != nil { return err } for _, node := range c.config.Devices { m := &configs.Mount{Destination: node.Path, Source: node.Path} c.addCriuDumpMount(req, m) } // Write the FD info to a file in the image directory fdsJSON, err := json.Marshal(c.initProcess.externalDescriptors()) if err != nil { return err } err = ioutil.WriteFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename), fdsJSON, 0655) if err != nil { return err } } err = c.criuSwrk(nil, req, criuOpts, false) if err != nil { return err } return nil } func (c *linuxContainer) addCriuRestoreMount(req *criurpc.CriuReq, m *configs.Mount) { mountDest := m.Destination if strings.HasPrefix(mountDest, c.config.Rootfs) { mountDest = mountDest[len(c.config.Rootfs):] } extMnt := &criurpc.ExtMountMap{ Key: proto.String(mountDest), Val: proto.String(m.Source), } req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt) } func (c *linuxContainer) restoreNetwork(req *criurpc.CriuReq, criuOpts *CriuOpts) { for _, iface := range c.config.Networks { switch iface.Type { case "veth": veth := new(criurpc.CriuVethPair) veth.IfOut = proto.String(iface.HostInterfaceName) veth.IfIn = proto.String(iface.Name) req.Opts.Veths = append(req.Opts.Veths, veth) break case "loopback": break } } for _, i := range criuOpts.VethPairs { veth := new(criurpc.CriuVethPair) veth.IfOut = proto.String(i.HostInterfaceName) veth.IfIn = proto.String(i.ContainerInterfaceName) req.Opts.Veths = append(req.Opts.Veths, veth) } } func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error { c.m.Lock() defer c.m.Unlock() // TODO(avagin): Figure out how to make this work nicely. CRIU doesn't have // support for unprivileged restore at the moment. if c.config.Rootless { return fmt.Errorf("cannot restore a rootless container") } if err := c.checkCriuVersion("1.5.2"); err != nil { return err } if criuOpts.WorkDirectory == "" { criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work") } // Since a container can be C/R'ed multiple times, // the work directory may already exist. if err := os.Mkdir(criuOpts.WorkDirectory, 0655); err != nil && !os.IsExist(err) { return err } workDir, err := os.Open(criuOpts.WorkDirectory) if err != nil { return err } defer workDir.Close() if criuOpts.ImagesDirectory == "" { return fmt.Errorf("invalid directory to restore checkpoint") } imageDir, err := os.Open(criuOpts.ImagesDirectory) if err != nil { return err } defer imageDir.Close() // CRIU has a few requirements for a root directory: // * it must be a mount point // * its parent must not be overmounted // c.config.Rootfs is bind-mounted to a temporary directory // to satisfy these requirements. root := filepath.Join(c.root, "criu-root") if err := os.Mkdir(root, 0755); err != nil { return err } defer os.Remove(root) root, err = filepath.EvalSymlinks(root) if err != nil { return err } err = syscall.Mount(c.config.Rootfs, root, "", syscall.MS_BIND|syscall.MS_REC, "") if err != nil { return err } defer syscall.Unmount(root, syscall.MNT_DETACH) t := criurpc.CriuReqType_RESTORE req := &criurpc.CriuReq{ Type: &t, Opts: &criurpc.CriuOpts{ ImagesDirFd: proto.Int32(int32(imageDir.Fd())), WorkDirFd: proto.Int32(int32(workDir.Fd())), EvasiveDevices: proto.Bool(true), LogLevel: proto.Int32(4), LogFile: proto.String("restore.log"), RstSibling: proto.Bool(true), Root: proto.String(root), ManageCgroups: proto.Bool(true), NotifyScripts: proto.Bool(true), ShellJob: proto.Bool(criuOpts.ShellJob), ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections), TcpEstablished: proto.Bool(criuOpts.TcpEstablished), FileLocks: proto.Bool(criuOpts.FileLocks), EmptyNs: proto.Uint32(criuOpts.EmptyNs), }, } for _, m := range c.config.Mounts { switch m.Device { case "bind": c.addCriuRestoreMount(req, m) break case "cgroup": binds, err := getCgroupMounts(m) if err != nil { return err } for _, b := range binds { c.addCriuRestoreMount(req, b) } break } } if len(c.config.MaskPaths) > 0 { m := &configs.Mount{Destination: "/dev/null", Source: "/dev/null"} c.addCriuRestoreMount(req, m) } for _, node := range c.config.Devices { m := &configs.Mount{Destination: node.Path, Source: node.Path} c.addCriuRestoreMount(req, m) } if criuOpts.EmptyNs&syscall.CLONE_NEWNET == 0 { c.restoreNetwork(req, criuOpts) } // append optional manage cgroups mode if criuOpts.ManageCgroupsMode != 0 { if err := c.checkCriuVersion("1.7"); err != nil { return err } mode := criurpc.CriuCgMode(criuOpts.ManageCgroupsMode) req.Opts.ManageCgroupsMode = &mode } var ( fds []string fdJSON []byte ) if fdJSON, err = ioutil.ReadFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename)); err != nil { return err } if err := json.Unmarshal(fdJSON, &fds); err != nil { return err } for i := range fds { if s := fds[i]; strings.Contains(s, "pipe:") { inheritFd := new(criurpc.InheritFd) inheritFd.Key = proto.String(s) inheritFd.Fd = proto.Int32(int32(i)) req.Opts.InheritFd = append(req.Opts.InheritFd, inheritFd) } } return c.criuSwrk(process, req, criuOpts, true) } func (c *linuxContainer) criuApplyCgroups(pid int, req *criurpc.CriuReq) error { // XXX: Do we need to deal with this case? AFAIK criu still requires root. if err := c.cgroupManager.Apply(pid); err != nil { return err } if err := c.cgroupManager.Set(c.config); err != nil { return newSystemError(err) } path := fmt.Sprintf("/proc/%d/cgroup", pid) cgroupsPaths, err := cgroups.ParseCgroupFile(path) if err != nil { return err } for c, p := range cgroupsPaths { cgroupRoot := &criurpc.CgroupRoot{ Ctrl: proto.String(c), Path: proto.String(p), } req.Opts.CgRoot = append(req.Opts.CgRoot, cgroupRoot) } return nil } func (c *linuxContainer) criuSwrk(process *Process, req *criurpc.CriuReq, opts *CriuOpts, applyCgroups bool) error { fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_SEQPACKET|syscall.SOCK_CLOEXEC, 0) if err != nil { return err } logPath := filepath.Join(opts.WorkDirectory, req.GetOpts().GetLogFile()) criuClient := os.NewFile(uintptr(fds[0]), "criu-transport-client") criuServer := os.NewFile(uintptr(fds[1]), "criu-transport-server") defer criuClient.Close() defer criuServer.Close() args := []string{"swrk", "3"} logrus.Debugf("Using CRIU %d at: %s", c.criuVersion, c.criuPath) logrus.Debugf("Using CRIU with following args: %s", args) cmd := exec.Command(c.criuPath, args...) if process != nil { cmd.Stdin = process.Stdin cmd.Stdout = process.Stdout cmd.Stderr = process.Stderr } cmd.ExtraFiles = append(cmd.ExtraFiles, criuServer) if err := cmd.Start(); err != nil { return err } criuServer.Close() defer func() { criuClient.Close() _, err := cmd.Process.Wait() if err != nil { return } }() if applyCgroups { err := c.criuApplyCgroups(cmd.Process.Pid, req) if err != nil { return err } } var extFds []string if process != nil { extFds, err = getPipeFds(cmd.Process.Pid) if err != nil { return err } } logrus.Debugf("Using CRIU in %s mode", req.GetType().String()) // In the case of criurpc.CriuReqType_FEATURE_CHECK req.GetOpts() // should be empty. For older CRIU versions it still will be // available but empty. if req.GetType() != criurpc.CriuReqType_FEATURE_CHECK { val := reflect.ValueOf(req.GetOpts()) v := reflect.Indirect(val) for i := 0; i < v.NumField(); i++ { st := v.Type() name := st.Field(i).Name if strings.HasPrefix(name, "XXX_") { continue } value := val.MethodByName("Get" + name).Call([]reflect.Value{}) logrus.Debugf("CRIU option %s with value %v", name, value[0]) } } data, err := proto.Marshal(req) if err != nil { return err } _, err = criuClient.Write(data) if err != nil { return err } buf := make([]byte, 10*4096) for true { n, err := criuClient.Read(buf) if err != nil { return err } if n == 0 { return fmt.Errorf("unexpected EOF") } if n == len(buf) { return fmt.Errorf("buffer is too small") } resp := new(criurpc.CriuResp) err = proto.Unmarshal(buf[:n], resp) if err != nil { return err } if !resp.GetSuccess() { typeString := req.GetType().String() return fmt.Errorf("criu failed: type %s errno %d\nlog file: %s", typeString, resp.GetCrErrno(), logPath) } t := resp.GetType() switch { case t == criurpc.CriuReqType_FEATURE_CHECK: logrus.Debugf("Feature check says: %s", resp) criuFeatures = resp.GetFeatures() break case t == criurpc.CriuReqType_NOTIFY: if err := c.criuNotifications(resp, process, opts, extFds); err != nil { return err } t = criurpc.CriuReqType_NOTIFY req = &criurpc.CriuReq{ Type: &t, NotifySuccess: proto.Bool(true), } data, err = proto.Marshal(req) if err != nil { return err } _, err = criuClient.Write(data) if err != nil { return err } continue case t == criurpc.CriuReqType_RESTORE: case t == criurpc.CriuReqType_DUMP: break case t == criurpc.CriuReqType_PRE_DUMP: // In pre-dump mode CRIU is in a loop and waits for // the final DUMP command. // The current runc pre-dump approach, however, is // start criu in PRE_DUMP once for a single pre-dump // and not the whole series of pre-dump, pre-dump, ...m, dump // If we got the message CriuReqType_PRE_DUMP it means // CRIU was successful and we need to forcefully stop CRIU logrus.Debugf("PRE_DUMP finished. Send close signal to CRIU service") criuClient.Close() // Process status won't be success, because one end of sockets is closed _, err := cmd.Process.Wait() if err != nil { logrus.Debugf("After PRE_DUMP CRIU exiting failed") return err } return nil default: return fmt.Errorf("unable to parse the response %s", resp.String()) } break } // cmd.Wait() waits cmd.goroutines which are used for proxying file descriptors. // Here we want to wait only the CRIU process. st, err := cmd.Process.Wait() if err != nil { return err } if !st.Success() { return fmt.Errorf("criu failed: %s\nlog file: %s", st.String(), logPath) } return nil } // block any external network activity func lockNetwork(config *configs.Config) error { for _, config := range config.Networks { strategy, err := getStrategy(config.Type) if err != nil { return err } if err := strategy.detach(config); err != nil { return err } } return nil } func unlockNetwork(config *configs.Config) error { for _, config := range config.Networks { strategy, err := getStrategy(config.Type) if err != nil { return err } if err = strategy.attach(config); err != nil { return err } } return nil } func (c *linuxContainer) criuNotifications(resp *criurpc.CriuResp, process *Process, opts *CriuOpts, fds []string) error { notify := resp.GetNotify() if notify == nil { return fmt.Errorf("invalid response: %s", resp.String()) } switch { case notify.GetScript() == "post-dump": f, err := os.Create(filepath.Join(c.root, "checkpoint")) if err != nil { return err } f.Close() case notify.GetScript() == "network-unlock": if err := unlockNetwork(c.config); err != nil { return err } case notify.GetScript() == "network-lock": if err := lockNetwork(c.config); err != nil { return err } case notify.GetScript() == "setup-namespaces": if c.config.Hooks != nil { s := configs.HookState{ Version: c.config.Version, ID: c.id, Pid: int(notify.GetPid()), Bundle: utils.SearchLabels(c.config.Labels, "bundle"), } for i, hook := range c.config.Hooks.Prestart { if err := hook.Run(s); err != nil { return newSystemErrorWithCausef(err, "running prestart hook %d", i) } } } case notify.GetScript() == "post-restore": pid := notify.GetPid() r, err := newRestoredProcess(int(pid), fds) if err != nil { return err } process.ops = r if err := c.state.transition(&restoredState{ imageDir: opts.ImagesDirectory, c: c, }); err != nil { return err } // create a timestamp indicating when the restored checkpoint was started c.created = time.Now().UTC() if _, err := c.updateState(r); err != nil { return err } if err := os.Remove(filepath.Join(c.root, "checkpoint")); err != nil { if !os.IsNotExist(err) { logrus.Error(err) } } } return nil } func (c *linuxContainer) updateState(process parentProcess) (*State, error) { c.initProcess = process state, err := c.currentState() if err != nil { return nil, err } err = c.saveState(state) if err != nil { return nil, err } return state, nil } func (c *linuxContainer) saveState(s *State) error { f, err := os.Create(filepath.Join(c.root, stateFilename)) if err != nil { return err } defer f.Close() return utils.WriteJSON(f, s) } func (c *linuxContainer) deleteState() error { return os.Remove(filepath.Join(c.root, stateFilename)) } func (c *linuxContainer) currentStatus() (Status, error) { if err := c.refreshState(); err != nil { return -1, err } return c.state.status(), nil } // refreshState needs to be called to verify that the current state on the // container is what is true. Because consumers of libcontainer can use it // out of process we need to verify the container's status based on runtime // information and not rely on our in process info. func (c *linuxContainer) refreshState() error { paused, err := c.isPaused() if err != nil { return err } if paused { return c.state.transition(&pausedState{c: c}) } t, err := c.runType() if err != nil { return err } switch t { case Created: return c.state.transition(&createdState{c: c}) case Running: return c.state.transition(&runningState{c: c}) } return c.state.transition(&stoppedState{c: c}) } // doesInitProcessExist checks if the init process is still the same process // as the initial one, it could happen that the original process has exited // and a new process has been created with the same pid, in this case, the // container would already be stopped. func (c *linuxContainer) doesInitProcessExist(initPid int) (bool, error) { startTime, err := system.GetProcessStartTime(initPid) if err != nil { return false, newSystemErrorWithCausef(err, "getting init process %d start time", initPid) } if c.initProcessStartTime != startTime { return false, nil } return true, nil } func (c *linuxContainer) runType() (Status, error) { if c.initProcess == nil { return Stopped, nil } pid := c.initProcess.pid() // return Running if the init process is alive if err := syscall.Kill(pid, 0); err != nil { if err == syscall.ESRCH { // It means the process does not exist anymore, could happen when the // process exited just when we call the function, we should not return // error in this case. return Stopped, nil } return Stopped, newSystemErrorWithCausef(err, "sending signal 0 to pid %d", pid) } // check if the process is still the original init process. exist, err := c.doesInitProcessExist(pid) if !exist || err != nil { return Stopped, err } // We'll create exec fifo and blocking on it after container is created, // and delete it after start container. if _, err := os.Stat(filepath.Join(c.root, execFifoFilename)); err == nil { return Created, nil } return Running, nil } func (c *linuxContainer) isPaused() (bool, error) { fcg := c.cgroupManager.GetPaths()["freezer"] if fcg == "" { // A container doesn't have a freezer cgroup return false, nil } data, err := ioutil.ReadFile(filepath.Join(fcg, "freezer.state")) if err != nil { // If freezer cgroup is not mounted, the container would just be not paused. if os.IsNotExist(err) { return false, nil } return false, newSystemErrorWithCause(err, "checking if container is paused") } return bytes.Equal(bytes.TrimSpace(data), []byte("FROZEN")), nil } func (c *linuxContainer) currentState() (*State, error) { var ( startTime string externalDescriptors []string pid = -1 ) if c.initProcess != nil { pid = c.initProcess.pid() startTime, _ = c.initProcess.startTime() externalDescriptors = c.initProcess.externalDescriptors() } state := &State{ BaseState: BaseState{ ID: c.ID(), Config: *c.config, InitProcessPid: pid, InitProcessStartTime: startTime, Created: c.created, }, Rootless: c.config.Rootless, CgroupPaths: c.cgroupManager.GetPaths(), NamespacePaths: make(map[configs.NamespaceType]string), ExternalDescriptors: externalDescriptors, } if pid > 0 { for _, ns := range c.config.Namespaces { state.NamespacePaths[ns.Type] = ns.GetPath(pid) } for _, nsType := range configs.NamespaceTypes() { if !configs.IsNamespaceSupported(nsType) { continue } if _, ok := state.NamespacePaths[nsType]; !ok { ns := configs.Namespace{Type: nsType} state.NamespacePaths[ns.Type] = ns.GetPath(pid) } } } return state, nil } // orderNamespacePaths sorts namespace paths into a list of paths that we // can setns in order. func (c *linuxContainer) orderNamespacePaths(namespaces map[configs.NamespaceType]string) ([]string, error) { paths := []string{} order := []configs.NamespaceType{ // The user namespace *must* be done first. configs.NEWUSER, configs.NEWIPC, configs.NEWUTS, configs.NEWNET, configs.NEWPID, configs.NEWNS, } // Remove namespaces that we don't need to join. var nsTypes []configs.NamespaceType for _, ns := range order { if c.config.Namespaces.Contains(ns) { nsTypes = append(nsTypes, ns) } } for _, nsType := range nsTypes { if p, ok := namespaces[nsType]; ok && p != "" { // check if the requested namespace is supported if !configs.IsNamespaceSupported(nsType) { return nil, newSystemError(fmt.Errorf("namespace %s is not supported", nsType)) } // only set to join this namespace if it exists if _, err := os.Lstat(p); err != nil { return nil, newSystemErrorWithCausef(err, "running lstat on namespace path %q", p) } // do not allow namespace path with comma as we use it to separate // the namespace paths if strings.ContainsRune(p, ',') { return nil, newSystemError(fmt.Errorf("invalid path %s", p)) } paths = append(paths, fmt.Sprintf("%s:%s", configs.NsName(nsType), p)) } } return paths, nil } func encodeIDMapping(idMap []configs.IDMap) ([]byte, error) { data := bytes.NewBuffer(nil) for _, im := range idMap { line := fmt.Sprintf("%d %d %d\n", im.ContainerID, im.HostID, im.Size) if _, err := data.WriteString(line); err != nil { return nil, err } } return data.Bytes(), nil } // bootstrapData encodes the necessary data in netlink binary format // as a io.Reader. // Consumer can write the data to a bootstrap program // such as one that uses nsenter package to bootstrap the container's // init process correctly, i.e. with correct namespaces, uid/gid // mapping etc. func (c *linuxContainer) bootstrapData(cloneFlags uintptr, nsMaps map[configs.NamespaceType]string) (io.Reader, error) { // create the netlink message r := nl.NewNetlinkRequest(int(InitMsg), 0) // write cloneFlags r.AddData(&Int32msg{ Type: CloneFlagsAttr, Value: uint32(cloneFlags), }) // write custom namespace paths if len(nsMaps) > 0 { nsPaths, err := c.orderNamespacePaths(nsMaps) if err != nil { return nil, err } r.AddData(&Bytemsg{ Type: NsPathsAttr, Value: []byte(strings.Join(nsPaths, ",")), }) } // write namespace paths only when we are not joining an existing user ns _, joinExistingUser := nsMaps[configs.NEWUSER] if !joinExistingUser { // write uid mappings if len(c.config.UidMappings) > 0 { b, err := encodeIDMapping(c.config.UidMappings) if err != nil { return nil, err } r.AddData(&Bytemsg{ Type: UidmapAttr, Value: b, }) } // write gid mappings if len(c.config.GidMappings) > 0 { b, err := encodeIDMapping(c.config.GidMappings) if err != nil { return nil, err } r.AddData(&Bytemsg{ Type: GidmapAttr, Value: b, }) // The following only applies if we are root. if !c.config.Rootless { // check if we have CAP_SETGID to setgroup properly pid, err := capability.NewPid(os.Getpid()) if err != nil { return nil, err } if !pid.Get(capability.EFFECTIVE, capability.CAP_SETGID) { r.AddData(&Boolmsg{ Type: SetgroupAttr, Value: true, }) } } } } // write oom_score_adj r.AddData(&Bytemsg{ Type: OomScoreAdjAttr, Value: []byte(fmt.Sprintf("%d", c.config.OomScoreAdj)), }) // write rootless r.AddData(&Boolmsg{ Type: RootlessAttr, Value: c.config.Rootless, }) return bytes.NewReader(r.Serialize()), nil }
mit
binary42/RPi-CTD-Server
libphidget-2.1.8.20150410/Java/com/phidgets/event/CurrentChangeListener.java
1253
/* * This file is part of libphidget21 * * Copyright © 2006-2015 Phidgets Inc <patrick@phidgets.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see * <http://www.gnu.org/licenses/> */ package com.phidgets.event; /** * This interface represents a CurrentChangeEvent. This event originates from the Phidget Motor Controller. * This event is not supported by all Motor Controllers. * * @author Phidgets Inc. */ public interface CurrentChangeListener { /** * This method is called with the event data when a new event arrives. * * @param ae the event data object containing event data */ public void currentChanged(CurrentChangeEvent ae); }
mit
cakejs/cakejs
src/Database/DriverManager.js
1392
/** * Copyright (c) 2015 Tiinusen * * Many thanks to Cake Software Foundation, Inc. (http://cakefoundation.org) * This was inspired by http://cakephp.org CakePHP(tm) Project * * Licensed under The MIT License * For full copyright and license information, please see the LICENSE * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) 2015 Tiinusen * @link https://github.com/cakejs/cakejs * @license http://www.opensource.org/licenses/mit-license.php MIT License */ //CakeJS.Database.DriverManager //Types import {MissingConfigException} from '../Exception/MissingConfigException' import {NotImplementedException} from '../Exception/NotImplementedException' import {Mysql} from './Driver/Mysql' export class DriverManager { static _connections = {}; //This will be remade when custom and more drivers are requested static get(configuration) { if(!('driver' in configuration)){ throw new MissingConfigException("driver"); } var key = JSON.stringify(configuration); if(!(key in DriverManager._connections)){ switch(configuration.driver){ case "Mysql": DriverManager._connections[key] = new Mysql(configuration); break; default: throw new NotImplementedException(); break; } } return DriverManager._connections[key]; } }
mit
oliviertassinari/material-ui
packages/mui-icons-material/lib/esm/SatelliteTwoTone.js
643
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M5 19h14V5H5v14zM6 6h2.57c0 1.42-1.15 2.58-2.57 2.58V6zm0 4.29c2.37 0 4.28-1.93 4.28-4.29H12c0 3.31-2.68 6-6 6v-1.71zm3 2.86 2.14 2.58 3-3.86L18 17H6l3-3.85z", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zM8.57 6H6v2.58c1.42 0 2.57-1.16 2.57-2.58zM12 6h-1.72c0 2.36-1.91 4.29-4.28 4.29V12c3.32 0 6-2.69 6-6zm2.14 5.86-3 3.87L9 13.15 6 17h12z" }, "1")], 'SatelliteTwoTone');
mit
tgbot/api
src/Types/PollAnswer.php
1798
<?php namespace TelegramBot\Api\Types; use TelegramBot\Api\BaseType; /** * Class PollAnswer * * @see https://core.telegram.org/bots/api#pollanswer * * This object represents an answer of a user in a non-anonymous poll. * * * @package TelegramBot\Api\Types */ class PollAnswer extends BaseType { /** * {@inheritdoc} * * @var array */ static protected $requiredParams = ['poll_id', 'option_ids', 'user']; /** * {@inheritdoc} * * @var array */ static protected $map = [ 'option_ids' => true, 'user' => User::class, 'poll_id' => true, ]; /** * @var \TelegramBot\Api\Types\User */ protected $user; /** * @var string */ protected $pollId; /** * @var int[] */ protected $optionIds; /** * @return string */ public function getPollId() { return $this->pollId; } /** * @param string $id */ public function setPollId($id) { $this->pollId = $id; } /** * @return User */ public function getUser() { return $this->user; } /** * @param User $from */ public function setUser(User $from) { $this->user = $from; } /** * @return User */ public function getFrom() { return $this->getUser(); } /** * @param User $from */ public function setFrom(User $from) { return $this->setUser($from); } /** * @return int[] */ public function getOptionIds() { return $this->optionIds; } /** * @param int[] $optionIds */ public function setOptionIds($optionIds) { $this->optionIds = $optionIds; } }
mit
SunBurst/hydroview-flask
app/static/js/services/station/station-groups-measurements.service.js
33700
(function() { 'use strict'; angular .module('app.services') .factory('stationGroupMeasurements', stationGroupMeasurements); stationGroupMeasurements.$inject = ['$resource']; function stationGroupMeasurements($resource) { var customInterceptor = { response: function(response) { return response; } }; return { getDynamicGroupMeasurementsChart: getDynamicGroupMeasurementsChart, getDynamicGroupMeasurementsTimeGrouped: getDynamicGroupMeasurementsTimeGrouped, getDailyGroupMeasurementsChart: getDailyGroupMeasurementsChart, getDailyGroupMeasurementsTimeGrouped: getDailyGroupMeasurementsTimeGrouped, getFiveMinGroupMeasurementsChart: getFiveMinGroupMeasurementsChart, getFiveMinGroupMeasurementsTimeGrouped: getFiveMinGroupMeasurementsTimeGrouped, getHourlyGroupMeasurementsChart: getHourlyGroupMeasurementsChart, getHourlyGroupMeasurementsTimeGrouped: getHourlyGroupMeasurementsTimeGrouped, getThirtyMinGroupMeasurementsChart: getThirtyMinGroupMeasurementsChart, getThirtyMinGroupMeasurementsTimeGrouped: getThirtyMinGroupMeasurementsTimeGrouped, getTwentyMinGroupMeasurementsChart: getTwentyMinGroupMeasurementsChart, getTwentyMinGroupMeasurementsTimeGrouped: getTwentyMinGroupMeasurementsTimeGrouped, getFifteenMinGroupMeasurementsChart: getFifteenMinGroupMeasurementsChart, getFifteenMinGroupMeasurementsTimeGrouped: getFifteenMinGroupMeasurementsTimeGrouped, getTenMinGroupMeasurementsChart: getTenMinGroupMeasurementsChart, getTenMinGroupMeasurementsTimeGrouped: getTenMinGroupMeasurementsTimeGrouped, getOneMinGroupMeasurementsChart: getOneMinGroupMeasurementsChart, getOneMinGroupMeasurementsTimeGrouped: getOneMinGroupMeasurementsTimeGrouped, getOneSecGroupMeasurementsChart: getOneSecGroupMeasurementsChart, getOneSecGroupMeasurementsTimeGrouped: getOneSecGroupMeasurementsTimeGrouped }; function getDynamicGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/dynamic_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getGroupMeasurementsChartComplete) .catch(getGroupMeasurementsChartFailed); function getGroupMeasurementsChartComplete(response) { return response; } function getGroupMeasurementsChartFailed(error) { console.log(error); } } function getDynamicGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/dynamic_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getGroupMeasurementsTimeGroupedComplete) .catch(getGroupMeasurementsTimeGroupedFailed); function getGroupMeasurementsTimeGroupedComplete(response) { return response; } function getGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getDailyGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/daily_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getDailyGroupMeasurementsChartComplete) .catch(getDailyGroupMeasurementsChartFailed); function getDailyGroupMeasurementsChartComplete(response) { return response; } function getDailyGroupMeasurementsChartFailed(error) { console.log(error); } } function getDailyGroupMeasurements(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/daily_group_measurements_by_station/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getDailyGroupMeasurementsComplete) .catch(getDailyGroupMeasurementsFailed); function getDailyGroupMeasurementsComplete(response) { return response; } function getDailyGroupMeasurementsFailed(error) { console.log(error); } } function getDailyGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/daily_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getDailyGroupMeasurementsTimeGroupedComplete) .catch(getDailyGroupMeasurementsTimeGroupedFailed); function getDailyGroupMeasurementsTimeGroupedComplete(response) { return response; } function getDailyGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getHourlyGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/hourly_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getHourlyGroupMeasurementsChartComplete) .catch(getHourlyGroupMeasurementsChartFailed); function getHourlyGroupMeasurementsChartComplete(response) { return response; } function getHourlyGroupMeasurementsChartFailed(error) { console.log(error); } } function getHourlyGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/hourly_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getHourlyGroupMeasurementsTimeGroupedComplete) .catch(getHourlyGroupMeasurementsTimeGroupedFailed); function getHourlyGroupMeasurementsTimeGroupedComplete(response) { return response; } function getHourlyGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getThirtyMinGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/thirty_min_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getThirtyMinGroupMeasurementsChartComplete) .catch(getThirtyMinGroupMeasurementsChartFailed); function getThirtyMinGroupMeasurementsChartComplete(response) { return response; } function getThirtyMinGroupMeasurementsChartFailed(error) { console.log(error); } } function getThirtyMinGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/thirty_min_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getThirtyMinGroupMeasurementsTimeGroupedComplete) .catch(getThirtyMinGroupMeasurementsTimeGroupedFailed); function getThirtyMinGroupMeasurementsTimeGroupedComplete(response) { return response; } function getThirtyMinGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getTwentyMinGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/twenty_min_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getTwentyMinGroupMeasurementsChartComplete) .catch(getTwentyMinGroupMeasurementsChartFailed); function getTwentyMinGroupMeasurementsChartComplete(response) { return response; } function getTwentyMinGroupMeasurementsChartFailed(error) { console.log(error); } } function getTwentyMinGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/twenty_min_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getTwentyMinGroupMeasurementsTimeGroupedComplete) .catch(getTwentyMinGroupMeasurementsTimeGroupedFailed); function getTwentyMinGroupMeasurementsTimeGroupedComplete(response) { return response; } function getTwentyMinGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getFifteenMinGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/fifteen_min_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getFifteenMinGroupMeasurementsChartComplete) .catch(getFifteenMinGroupMeasurementsChartFailed); function getFifteenMinGroupMeasurementsChartComplete(response) { return response; } function getFifteenMinGroupMeasurementsChartFailed(error) { console.log(error); } } function getFifteenMinGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/fifteen_min_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getFifteenMinGroupMeasurementsTimeGroupedComplete) .catch(getFifteenMinGroupMeasurementsTimeGroupedFailed); function getFifteenMinGroupMeasurementsTimeGroupedComplete(response) { return response; } function getFifteenMinGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getTenMinGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/ten_min_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getTenMinGroupMeasurementsChartComplete) .catch(getTenMinGroupMeasurementsChartFailed); function getTenMinGroupMeasurementsChartComplete(response) { return response; } function getTenMinGroupMeasurementsChartFailed(error) { console.log(error); } } function getTenMinGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/ten_min_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getTenMinGroupMeasurementsTimeGroupedComplete) .catch(getTenMinGroupMeasurementsTimeGroupedFailed); function getTenMinGroupMeasurementsTimeGroupedComplete(response) { return response; } function getTenMinGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getFiveMinGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/five_min_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getFiveMinGroupMeasurementsChartComplete) .catch(getFiveMinGroupMeasurementsChartFailed); function getFiveMinGroupMeasurementsChartComplete(response) { return response; } function getFiveMinGroupMeasurementsChartFailed(error) { console.log(error); } } function getFiveMinGroupMeasurements(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/five_min_group_measurements_by_station/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getFiveMinGroupMeasurementsComplete) .catch(getFiveMinGroupMeasurementsFailed); function getFiveMinGroupMeasurementsComplete(response) { return response; } function getFiveMinGroupMeasurementsFailed(error) { console.log(error); } } function getFiveMinGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/five_min_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getFiveMinGroupMeasurementsTimeGroupedComplete) .catch(getFiveMinGroupMeasurementsTimeGroupedFailed); function getFiveMinGroupMeasurementsTimeGroupedComplete(response) { return response; } function getFiveMinGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getOneMinGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/one_min_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getOneMinGroupMeasurementsChartComplete) .catch(getOneMinGroupMeasurementsChartFailed); function getOneMinGroupMeasurementsChartComplete(response) { return response; } function getOneMinGroupMeasurementsChartFailed(error) { console.log(error); } } function getOneMinGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/one_min_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getOneMinGroupMeasurementsTimeGroupedComplete) .catch(getOneMinGroupMeasurementsTimeGroupedFailed); function getOneMinGroupMeasurementsTimeGroupedComplete(response) { return response; } function getOneMinGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } function getOneSecGroupMeasurementsChart(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/one_sec_group_measurements_by_station_chart/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: false, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getOneSecGroupMeasurementsChartComplete) .catch(getOneSecGroupMeasurementsChartFailed); function getOneSecGroupMeasurementsChartComplete(response) { return response; } function getOneSecGroupMeasurementsChartFailed(error) { console.log(error); } } function getOneSecGroupMeasurementsTimeGrouped(stationId, groupId, qcLevel, fromTimestamp, toTimestamp) { var resource = $resource('/api/one_sec_group_measurements_by_station_time_grouped/:station_id/:group_id/:qc_level/:from_timestamp/:to_timestamp', {}, { query: { method: 'GET', params: { station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }, isArray: true, interceptor: customInterceptor } }); return resource.query({ station_id: stationId, group_id: groupId, qc_level: qcLevel, from_timestamp: fromTimestamp, to_timestamp: toTimestamp }).$promise .then(getOneSecGroupMeasurementsTimeGroupedComplete) .catch(getOneSecGroupMeasurementsTimeGroupedFailed); function getOneSecGroupMeasurementsTimeGroupedComplete(response) { return response; } function getOneSecGroupMeasurementsTimeGroupedFailed(error) { console.log(error); } } } })();
mit
vladikoff/data
packages/ember-data/tests/integration/relationships/one_to_one_test.js
11655
var env, store, User, Job; var attr = DS.attr, belongsTo = DS.belongsTo; function stringify(string) { return function() { return string; }; } module('integration/relationships/one_to_one_test - OneToOne relationships', { setup: function() { User = DS.Model.extend({ name: attr('string'), bestFriend: belongsTo('user', {async: true}), job: belongsTo('job') }); User.toString = stringify('User'); Job = DS.Model.extend({ isGood: attr(), user: belongsTo('user') }); Job.toString = stringify('Job'); env = setupStore({ user: User, job: Job }); store = env.store; }, teardown: function() { env.container.destroy(); } }); /* Server loading tests */ test("Relationship is available from both sides even if only loaded from one side - async", function () { var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend: 2}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend"}); stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanley, 'User relationship was set up correctly'); })); }); test("Relationship is available from both sides even if only loaded from one side - sync", function () { var job = store.push('job', {id:2 , isGood: true}); var user = store.push('user', {id:1, name: 'Stanley', job:2 }); equal(job.get('user'), user, 'User relationship was set up correctly'); }); test("Fetching a belongsTo that is set to null removes the record from a relationship - async", function () { var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend", bestFriend: 1}); store.push('user', {id:1, name: 'Stanley', bestFriend: null}); stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, null, 'User relationship was removed correctly'); })); }); test("Fetching a belongsTo that is set to null removes the record from a relationship - sync", function () { var job = store.push('job', {id:2 , isGood: true}); store.push('user', {id:1, name: 'Stanley', job:2 }); job = store.push('job', {id:2 , isGood: true, user:null}); equal(job.get('user'), null, 'User relationship was removed correctly'); }); test("Fetching a belongsTo that is set to a different record, sets the old relationship to null - async", function () { expect(3); var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend: 2}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend", bestFriend: 1}); stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanley, 'User relationship was initally setup correctly'); var stanleysNewFriend = store.push('user', {id:3, name: "Stanley's New friend", bestFriend: 1}); stanley.get('bestFriend').then(async(function(fetchedNewFriend){ equal(fetchedNewFriend, stanleysNewFriend, 'User relationship was updated correctly'); })); stanleysFriend.get('bestFriend').then(async(function(fetchedOldFriend){ equal(fetchedOldFriend, null, 'The old relationship was set to null correctly'); })); })); }); test("Fetching a belongsTo that is set to a different record, sets the old relationship to null - sync", function () { var job = store.push('job', {id:2 , isGood: false}); var user = store.push('user', {id:1, name: 'Stanley', job:2 }); equal(job.get('user'), user, 'Job and user initially setup correctly'); var newBetterJob = store.push('job', {id:3, isGood: true, user:1 }); equal(user.get('job'), newBetterJob, 'Job updated correctly'); equal(job.get('user'), null, 'Old relationship nulled out correctly'); equal(newBetterJob.get('user'), user, 'New job setup correctly'); }); /* Local edits */ test("Setting a OneToOne relationship reflects correctly on the other side- async", function () { var stanley = store.push('user', {id:1, name: 'Stanley'}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend"}); stanley.set('bestFriend', stanleysFriend); stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanley, 'User relationship was updated correctly'); })); }); test("Setting a OneToOne relationship reflects correctly on the other side- sync", function () { var job = store.push('job', {id:2 , isGood: true}); var user = store.push('user', {id:1, name: 'Stanley'}); user.set('job', job); equal(job.get('user'), user, 'User relationship was set up correctly'); }); test("Setting a BelongsTo to a promise unwraps the promise before setting- async", function () { var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend:2}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend"}); var newFriend = store.push('user', {id:3, name: "New friend"}); newFriend.set('bestFriend', stanleysFriend.get('bestFriend')); stanley.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, newFriend, 'User relationship was updated correctly'); })); newFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanley, 'User relationship was updated correctly'); })); }); test("Setting a BelongsTo to a promise works when the promise returns null- async", function () { store.push('user', {id:1, name: 'Stanley'}); var igor = store.push('user', {id:2, name: "Igor"}); var newFriend = store.push('user', {id:3, name: "New friend", bestFriend:1}); newFriend.set('bestFriend', igor.get('bestFriend')); newFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, null, 'User relationship was updated correctly'); })); }); test("Setting a BelongsTo to a promise that didn't come from a relationship errors out", function () { var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend:2}); var igor = store.push('user', {id:3, name: 'Igor'}); expectAssertion(function() { stanley.set('bestFriend', Ember.RSVP.resolve(igor)); }, /You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call./); }); test("Setting a BelongsTo to a promise multiple times is resistant to race conditions- async", function () { expect(1); var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend:2}); var igor = store.push('user', {id:3, name: "Igor", bestFriend:5}); var newFriend = store.push('user', {id:7, name: "New friend"}); env.adapter.find = function(store, type, id) { if (id === '5') { return Ember.RSVP.resolve({id:5, name: "Igor's friend"}); } else if (id === '2') { stop(); return new Ember.RSVP.Promise(function(resolve, reject) { setTimeout(function(){ start(); resolve({id:2, name:"Stanley's friend"}); }, 1); }); } }; newFriend.set('bestFriend', stanley.get('bestFriend')); newFriend.set('bestFriend', igor.get('bestFriend')); newFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser.get('name'), "Igor's friend", 'User relationship was updated correctly'); })); }); test("Setting a OneToOne relationship to null reflects correctly on the other side - async", function () { var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend:2}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend", bestFriend:1}); stanley.set('bestFriend', null); // :( stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, null, 'User relationship was removed correctly'); })); }); test("Setting a OneToOne relationship to null reflects correctly on the other side - sync", function () { var job = store.push('job', {id:2 , isGood: false, user:1}); var user = store.push('user', {id:1, name: 'Stanley', job:2}); user.set('job', null); equal(job.get('user'), null, 'User relationship was removed correctly'); }); test("Setting a belongsTo to a different record, sets the old relationship to null - async", function () { expect(3); var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend: 2}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend", bestFriend: 1}); stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanley, 'User relationship was initally setup correctly'); var stanleysNewFriend = store.push('user', {id:3, name: "Stanley's New friend"}); stanleysNewFriend.set('bestFriend', stanley); stanley.get('bestFriend').then(async(function(fetchedNewFriend){ equal(fetchedNewFriend, stanleysNewFriend, 'User relationship was updated correctly'); })); stanleysFriend.get('bestFriend').then(async(function(fetchedOldFriend){ equal(fetchedOldFriend, null, 'The old relationship was set to null correctly'); })); })); }); test("Setting a belongsTo to a different record, sets the old relationship to null - sync", function () { var job = store.push('job', {id:2 , isGood: false}); var user = store.push('user', {id:1, name: 'Stanley', job:2 }); equal(job.get('user'), user, 'Job and user initially setup correctly'); var newBetterJob = store.push('job', {id:3, isGood: true}); newBetterJob.set('user', user); equal(user.get('job'), newBetterJob, 'Job updated correctly'); equal(job.get('user'), null, 'Old relationship nulled out correctly'); equal(newBetterJob.get('user'), user, 'New job setup correctly'); }); /* Deleting tests */ test("When deleting a record that has a belongsTo relationship, the record is removed from the inverse but still has access to its own relationship - async", function () { var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend:2}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend"}); stanley.deleteRecord(); stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, null, 'Stanley got removed'); })); stanley.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanleysFriend, 'Stanleys friend did not get removed'); })); }); test("When deleting a record that has a belongsTo relationship, the record is removed from the inverse but still has access to its own relationship - sync", function () { var job = store.push('job', {id:2 , isGood: true}); var user = store.push('user', {id:1, name: 'Stanley', job:2 }); job.deleteRecord(); equal(user.get('job'), null, 'Job got removed from the user'); equal(job.get('user'), user, 'Job still has the user'); }); /* Rollback tests */ test("Rollbacking a deleted record restores the relationship on both sides - async", function () { var stanley = store.push('user', {id:1, name: 'Stanley', bestFriend:2}); var stanleysFriend = store.push('user', {id:2, name: "Stanley's friend"}); stanley.deleteRecord(); stanley.rollback(); stanleysFriend.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanley, 'Stanley got rollbacked correctly'); })); stanley.get('bestFriend').then(async(function(fetchedUser) { equal(fetchedUser, stanleysFriend, 'Stanleys friend did not get removed'); })); }); test("Rollbacking a deleted record restores the relationship on both sides - sync", function () { var job = store.push('job', {id:2 , isGood: true}); var user = store.push('user', {id:1, name: 'Stanley', job:2 }); job.deleteRecord(); job.rollback(); equal(user.get('job'), job, 'Job got rollbacked correctly'); equal(job.get('user'), user, 'Job still has the user'); });
mit
jackmagic313/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/Models/NetworkInterfaceTapConfigurationListResult.Serialization.cs
1741
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Network.Models { internal partial class NetworkInterfaceTapConfigurationListResult { internal static NetworkInterfaceTapConfigurationListResult DeserializeNetworkInterfaceTapConfigurationListResult(JsonElement element) { Optional<IReadOnlyList<NetworkInterfaceTapConfiguration>> value = default; Optional<string> nextLink = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<NetworkInterfaceTapConfiguration> array = new List<NetworkInterfaceTapConfiguration>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(NetworkInterfaceTapConfiguration.DeserializeNetworkInterfaceTapConfiguration(item)); } value = array; continue; } if (property.NameEquals("nextLink")) { nextLink = property.Value.GetString(); continue; } } return new NetworkInterfaceTapConfigurationListResult(Optional.ToList(value), nextLink.Value); } } }
mit
palestar/medusa
ThirdParty/bullet-2.75/Extras/COLLADA_DOM/src/1.4/dom/domFx_samplerDEPTH_common.cpp
8123
/* * Copyright 2006 Sony Computer Entertainment Inc. * * Licensed under the SCEA Shared Source License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: * http://research.scea.com/scea_shared_source_license.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing permissions and limitations under the * License. */ #include <dae/daeDom.h> #include <dom/domFx_samplerDEPTH_common.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> daeElementRef domFx_samplerDEPTH_common::create(daeInt bytes) { domFx_samplerDEPTH_commonRef ref = new(bytes) domFx_samplerDEPTH_common; return ref; } daeMetaElement * domFx_samplerDEPTH_common::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "fx_samplerDEPTH_common" ); _Meta->registerClass(domFx_samplerDEPTH_common::create, &_Meta); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( _Meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( _Meta, cm, 0, 1, 1 ); mea->setName( "source" ); mea->setOffset( daeOffsetOf(domFx_samplerDEPTH_common,elemSource) ); mea->setElementType( domFx_samplerDEPTH_common::domSource::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 1, 0, 1 ); mea->setName( "wrap_s" ); mea->setOffset( daeOffsetOf(domFx_samplerDEPTH_common,elemWrap_s) ); mea->setElementType( domFx_samplerDEPTH_common::domWrap_s::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 2, 0, 1 ); mea->setName( "wrap_t" ); mea->setOffset( daeOffsetOf(domFx_samplerDEPTH_common,elemWrap_t) ); mea->setElementType( domFx_samplerDEPTH_common::domWrap_t::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 3, 0, 1 ); mea->setName( "minfilter" ); mea->setOffset( daeOffsetOf(domFx_samplerDEPTH_common,elemMinfilter) ); mea->setElementType( domFx_samplerDEPTH_common::domMinfilter::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( _Meta, cm, 4, 0, 1 ); mea->setName( "magfilter" ); mea->setOffset( daeOffsetOf(domFx_samplerDEPTH_common,elemMagfilter) ); mea->setElementType( domFx_samplerDEPTH_common::domMagfilter::registerElement() ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( _Meta, cm, 5, 0, -1 ); mea->setName( "extra" ); mea->setOffset( daeOffsetOf(domFx_samplerDEPTH_common,elemExtra_array) ); mea->setElementType( domExtra::registerElement() ); cm->appendChild( mea ); cm->setMaxOrdinal( 5 ); _Meta->setCMRoot( cm ); _Meta->setElementSize(sizeof(domFx_samplerDEPTH_common)); _Meta->validate(); return _Meta; } daeElementRef domFx_samplerDEPTH_common::domSource::create(daeInt bytes) { domFx_samplerDEPTH_common::domSourceRef ref = new(bytes) domFx_samplerDEPTH_common::domSource; return ref; } daeMetaElement * domFx_samplerDEPTH_common::domSource::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "source" ); _Meta->registerClass(domFx_samplerDEPTH_common::domSource::create, &_Meta); _Meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( daeAtomicType::get("xsNCName")); ma->setOffset( daeOffsetOf( domFx_samplerDEPTH_common::domSource , _value )); ma->setContainer( _Meta ); _Meta->appendAttribute(ma); } _Meta->setElementSize(sizeof(domFx_samplerDEPTH_common::domSource)); _Meta->validate(); return _Meta; } daeElementRef domFx_samplerDEPTH_common::domWrap_s::create(daeInt bytes) { domFx_samplerDEPTH_common::domWrap_sRef ref = new(bytes) domFx_samplerDEPTH_common::domWrap_s; return ref; } daeMetaElement * domFx_samplerDEPTH_common::domWrap_s::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "wrap_s" ); _Meta->registerClass(domFx_samplerDEPTH_common::domWrap_s::create, &_Meta); _Meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( daeAtomicType::get("Fx_sampler_wrap_common")); ma->setOffset( daeOffsetOf( domFx_samplerDEPTH_common::domWrap_s , _value )); ma->setContainer( _Meta ); _Meta->appendAttribute(ma); } _Meta->setElementSize(sizeof(domFx_samplerDEPTH_common::domWrap_s)); _Meta->validate(); return _Meta; } daeElementRef domFx_samplerDEPTH_common::domWrap_t::create(daeInt bytes) { domFx_samplerDEPTH_common::domWrap_tRef ref = new(bytes) domFx_samplerDEPTH_common::domWrap_t; return ref; } daeMetaElement * domFx_samplerDEPTH_common::domWrap_t::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "wrap_t" ); _Meta->registerClass(domFx_samplerDEPTH_common::domWrap_t::create, &_Meta); _Meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( daeAtomicType::get("Fx_sampler_wrap_common")); ma->setOffset( daeOffsetOf( domFx_samplerDEPTH_common::domWrap_t , _value )); ma->setContainer( _Meta ); _Meta->appendAttribute(ma); } _Meta->setElementSize(sizeof(domFx_samplerDEPTH_common::domWrap_t)); _Meta->validate(); return _Meta; } daeElementRef domFx_samplerDEPTH_common::domMinfilter::create(daeInt bytes) { domFx_samplerDEPTH_common::domMinfilterRef ref = new(bytes) domFx_samplerDEPTH_common::domMinfilter; return ref; } daeMetaElement * domFx_samplerDEPTH_common::domMinfilter::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "minfilter" ); _Meta->registerClass(domFx_samplerDEPTH_common::domMinfilter::create, &_Meta); _Meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( daeAtomicType::get("Fx_sampler_filter_common")); ma->setOffset( daeOffsetOf( domFx_samplerDEPTH_common::domMinfilter , _value )); ma->setContainer( _Meta ); _Meta->appendAttribute(ma); } _Meta->setElementSize(sizeof(domFx_samplerDEPTH_common::domMinfilter)); _Meta->validate(); return _Meta; } daeElementRef domFx_samplerDEPTH_common::domMagfilter::create(daeInt bytes) { domFx_samplerDEPTH_common::domMagfilterRef ref = new(bytes) domFx_samplerDEPTH_common::domMagfilter; return ref; } daeMetaElement * domFx_samplerDEPTH_common::domMagfilter::registerElement() { if ( _Meta != NULL ) return _Meta; _Meta = new daeMetaElement; _Meta->setName( "magfilter" ); _Meta->registerClass(domFx_samplerDEPTH_common::domMagfilter::create, &_Meta); _Meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( daeAtomicType::get("Fx_sampler_filter_common")); ma->setOffset( daeOffsetOf( domFx_samplerDEPTH_common::domMagfilter , _value )); ma->setContainer( _Meta ); _Meta->appendAttribute(ma); } _Meta->setElementSize(sizeof(domFx_samplerDEPTH_common::domMagfilter)); _Meta->validate(); return _Meta; } daeMetaElement * domFx_samplerDEPTH_common::_Meta = NULL; daeMetaElement * domFx_samplerDEPTH_common::domSource::_Meta = NULL; daeMetaElement * domFx_samplerDEPTH_common::domWrap_s::_Meta = NULL; daeMetaElement * domFx_samplerDEPTH_common::domWrap_t::_Meta = NULL; daeMetaElement * domFx_samplerDEPTH_common::domMinfilter::_Meta = NULL; daeMetaElement * domFx_samplerDEPTH_common::domMagfilter::_Meta = NULL;
mit
nixdaemon/redmine-sharp
RedmineSharp/Models/IssueList.cs
217
using System; using System.Collections.Generic; using RedmineSharp.Types; namespace RedmineSharp.Models { public class IssueList : BaseModel { public List<Issue> Issues { get; set; } } // class } // namespace
mit
dosievskiy/booker
app/cache/dev/annotations/85f9e8a7fa7f72a5eb8e486e68e90849649a2457$booking.cache.php
224
<?php return unserialize('a:1:{i:0;O:30:"Doctrine\\ORM\\Mapping\\OneToMany":6:{s:8:"mappedBy";s:4:"room";s:12:"targetEntity";s:7:"Booking";s:7:"cascade";N;s:5:"fetch";s:4:"LAZY";s:13:"orphanRemoval";b:0;s:7:"indexBy";N;}}');
mit
RonRademaker/tactician-scheduler-plugin
tests/Scheduler/FileBasedSchedulerTest.php
1399
<?php namespace ConnectHolland\Tactician\SchedulerPlugin\Scheduler\Tests; use ConnectHolland\Tactician\SchedulerPlugin\Exception\ScheduledCommandNotFoundException; use ConnectHolland\Tactician\SchedulerPlugin\Scheduler\FileBasedScheduler; use ConnectHolland\Tactician\SchedulerPlugin\Tests\AbstractFileBasedSchedulerTest; use ConnectHolland\Tactician\SchedulerPlugin\Tests\Fixtures\Command\ScheduledCommand; /** * Unit test for the file based scheduler. * * @author ron */ class FileBasedSchedulerTest extends AbstractFileBasedSchedulerTest { /** * testCreatesSchedulePath. */ public function testCreatesSchedulePath() { $this->assertFalse(is_dir('tests/testpath')); new FileBasedScheduler('tests/testpath'); $this->assertTrue(is_dir('tests/testpath')); rmdir('tests/testpath'); } /** * testMissingScheduledCommandThrowsException. */ public function testMissingScheduledCommandThrowsException() { $scheduler = new FileBasedScheduler($this->path); $command = new ScheduledCommand(); $command->setTimestamp(time() + 1); $id = $scheduler->schedule($command); $this->assertFileExists($this->path.$id); unlink($this->path.$id); sleep(1); $this->setExpectedException(ScheduledCommandNotFoundException::class); $scheduler->getCommands(); } }
mit
mquandalle/6to5
lib/6to5/transformation/templates/array-expression-comprehension-map.js
51
ARRAY.map(function (KEY) { return STATEMENT; });
mit
jordansjones/Draft
source/Draft/Extensions/FormBodyBuilder.Extensions.cs
602
using System; using System.Linq; namespace Draft { internal static class FormBodyBuilderExtensions { public static FormBodyBuilder Add<TKey, TValue>(this FormBodyBuilder This, bool condition, TKey key, Func<TValue> value) { if (condition) { This.Add(key, value()); } return This; } public static FormBodyBuilder Add<TKey, TValue>(this FormBodyBuilder This, Func<bool> predicate, TKey key, Func<TValue> value) { return This.Add(predicate(), key, value); } } }
mit
outrunthewolf/overseer-librato
tests/TimerTest.php
509
<?php namespace League\StatsD\Test; class TimerTest extends TestCase { public function testTiming() { $this->client->timing('test_metric', 123); $this->assertEquals('test_metric:123|ms', $this->client->getLastMessage()); } public function testFunctionTiming() { $this->client->time('test_metric', function () { usleep(50000); }); $this->assertRegExp('/test_metric:5[0-9]{1}\.[0-9]+\|ms/', $this->client->getLastMessage()); } }
mit
bengimbel/Solstice-React-Contacts-Project
node_modules/react-icons/lib/md/local-bar.js
1124
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MdLocalBar = function MdLocalBar(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm12.4 11.6h15.2l2.9-3.2h-21z m22.6-3.2l-13.4 15v8.2h8.4v3.4h-20v-3.4h8.4v-8.2l-13.4-15v-3.4h30v3.4z' }) ) ); }; exports.default = MdLocalBar; module.exports = exports['default'];
mit
obi-two/Rebelion
data/scripts/templates/object/tangible/deed/pet_deed/shared_deed_le_repair_basic.py
716
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/deed/pet_deed/shared_deed_le_repair_basic.iff" result.attribute_template_id = 2 result.stfName("deed","le_repair_basic_deed") #### BEGIN MODIFICATIONS #### result.setStringAttribute("radial_filename", "radials/deed_datapad.py") result.setStringAttribute("deed_pcd", "object/intangible/pet/shared_le_repair_crafted.iff") result.setStringAttribute("deed_mobile", "object/mobile/shared_le_repair_crafted.iff") #### END MODIFICATIONS #### return result
mit
polydawn/go-xlate
tok/fixtures/fixtures_string.go
294
package fixtures import ( . "github.com/polydawn/refmt/tok" ) var sequences_String = []Sequence{ {"empty string", []Token{ TokStr(""), }, }, {"flat string", []Token{ TokStr("value"), }, }, {"strings needing escape", []Token{ TokStr("str\nbroken\ttabbed"), }, }, }
mit
gzilt/bruery-platform
src/bundles/FormatterBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
1014
<?php /** * This file is part of the Bruery Platform. * * (c) Viktore Zara <viktore.zara@gmail.com> * (c) Mell Zamora <mellzamora@outlook.com> * * Copyright (c) 2016. For the full copyright and license information, please view the LICENSE file that was distributed with this source code. */ namespace Bruery\FormatterBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class OverrideServiceCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { ##################################### ## Override Admin Extension ##################################### $definition = $container->getDefinition('sonata.formatter.ckeditor.extension'); $definition->setClass($container->getParameter('bruery.formatter.admin_extenstion.media.class')); } }
mit
exrin/Tesla-Mobile-App
Tesla/Tesla/Tesla/ViewModel/KeyPress.cs
2469
namespace Tesla.ViewModelOperation { using Definition.ViewLocator; using Exrin.Abstraction; using Exrin.Framework; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using TeslaDefinition; using TeslaDefinition.Interfaces.Model; public class PinLoginOperation : IOperation { IAuthModel _model = null; string _backCharacter = ""; public PinLoginOperation(IAuthModel model, string backCharacter) { _model = model; _backCharacter = backCharacter; } public Func<IList<IResult>, object, CancellationToken, Task> Function { get { return async (results, parameter, token) => { var result = new Result(); var character = Convert.ToString(parameter); var pin = _model.AuthModelState.Pin; if (pin == null) pin = string.Empty; if (character != null) if (character == _backCharacter) { if (!String.IsNullOrEmpty(pin) && pin.Length > 0) _model.AuthModelState.Pin = pin.Substring(0, pin.Length - 1); } else { _model.AuthModelState.Pin = pin += character; } if (!await _model.IsPinComplete()) { result.ResultAction = ResultType.None; } else if (await _model.IsAuthenticated()) { result.ResultAction = ResultType.Navigation; result.Arguments = new NavigationArgs() { Key = Control.Main, StackType = Stacks.Control }; } else { result.ResultAction = ResultType.Display; result.Arguments = new DisplayArgs() { Message = "Invalid Pin Entered. Please try again." }; } results.Add(result); }; } } public bool ChainedRollback { get; private set; } = false; public Func<Task> Rollback { get { return null; } } } }
mit
markburns/delfos
lib/delfos/method_trace/code_location/method.rb
1518
# frozen_string_literal: true require_relative "filename_helpers" module Delfos module MethodTrace module CodeLocation class Method include FilenameHelpers attr_reader :object, :line_number, :class_method, :method_object, :super_method # rubocop:disable Metrics/ParameterLists def initialize(object:, method_name:, file:, line_number:, class_method:, method_object: nil, super_method: nil) @object = object @method_name = method_name @file = file @line_number = line_number @class_method = class_method @method_object = method_object @super_method = super_method end # rubocop:enable Metrics/ParameterLists def klass_name klass.name end def klass object.is_a?(Module) ? object : object.class end def method_name (@method_name || "(main)").to_s end def method_type class_method ? "ClassMethod" : "InstanceMethod" end def summary(reverse: false) summary = [source_location, method_summary] (reverse ? summary.reverse : summary).join " " end private def method_summary "#{klass}#{separator}#{method_name}" end def source_location "#{file}:#{line_number}" end def separator class_method ? "." : "#" end end end end end
mit
nkato3/nicole-kato
equations/index.php
113
<?php header("HTTP/1.1 301 Moved Permanently"); header("Location: http://nicolekato.com/index.php/projects"); ?>
mit
alpha721/WikiEduDashboard
spec/lib/tasks/batch_rake_spec.rb
1148
# frozen_string_literal: true require 'rails_helper' # https://robots.thoughtbot.com/test-rake-tasks-like-a-boss describe 'batch:update_constantly' do include_context 'rake' describe 'update_constantly' do it 'initializes a ConstantUpdate' do expect(ConstantUpdate).to receive(:new) subject.invoke end end describe 'update_daily' do it 'initializes a DailyUpdate' do expect(DailyUpdate).to receive(:new) rake['batch:update_daily'].invoke end end describe 'survey_update' do it 'initializes a SurveyUpdate' do expect(SurveyUpdate).to receive(:new) rake['batch:survey_update'].invoke end end describe 'pause' do it 'creates a pause file' do pause_file = 'tmp/batch_pause.pid' rake['batch:pause'].invoke expect(File.exist?(pause_file)).to eq(true) File.delete pause_file end end describe 'resume' do it 'deletes a pause file' do pause_file = 'tmp/batch_pause.pid' File.open(pause_file, 'w') { |f| f.puts 'ohai' } rake['batch:resume'].invoke expect(File.exist?(pause_file)).to eq(false) end end end
mit
friendsofagape/mt2414ui
node_modules/tapable/lib/__tests__/HookCodeFactory.js
5614
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; const HookCodeFactory = require("../HookCodeFactory"); const expectNoSyntaxError = (code) => { new Function("a, b, c", code); }; describe("HookCodeFactory", () => { describe("callTap", () => { const factoryConfigurations = { "no args, no intercept": { args: [], taps: [ { type: "sync" }, { type: "async" }, { type: "promise" } ], interceptors: [] }, "with args, no intercept": { args: ["a", "b", "c"], taps: [ { type: "sync" }, { type: "async" }, { type: "promise" } ], interceptors: [] }, "with args, with intercept": { args: ["a", "b", "c"], taps: [ { type: "sync" }, { type: "async" }, { type: "promise" } ], interceptors: [ { call: () => {}, tap: () => {} }, { tap: () => {} }, { call: () => {} }, ] } } for(const configurationName in factoryConfigurations) { describe(`(${configurationName})`, () => { let factory; beforeEach(() => { factory = new HookCodeFactory(); factory.init(factoryConfigurations[configurationName]); }); it("sync without onResult", () => { const code = factory.callTap(0, { onError: err => `onError(${err});\n`, onDone: () => "onDone();\n" }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); it("sync with onResult", () => { const code = factory.callTap(0, { onError: err => `onError(${err});\n`, onResult: result => `onResult(${result});\n` }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); it("async without onResult", () => { const code = factory.callTap(1, { onError: err => `onError(${err});\n`, onDone: () => "onDone();\n" }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); it("async with onResult", () => { const code = factory.callTap(1, { onError: err => `onError(${err});\n`, onResult: result => `onResult(${result});\n` }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); it("promise without onResult", () => { const code = factory.callTap(2, { onError: err => `onError(${err});\n`, onDone: () => "onDone();\n" }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); it("promise with onResult", () => { const code = factory.callTap(2, { onError: err => `onError(${err});\n`, onResult: result => `onResult(${result});\n` }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); }); } }); describe("taps", () => { const factoryConfigurations = { "none": { args: ["a", "b", "c"], taps: [], interceptors: [] }, "single sync": { args: ["a", "b", "c"], taps: [ { type: "sync" } ], interceptors: [] }, "multiple sync": { args: ["a", "b", "c"], taps: [ { type: "sync" }, { type: "sync" }, { type: "sync" } ], interceptors: [] }, "single async": { args: ["a", "b", "c"], taps: [ { type: "async" } ], interceptors: [] }, "single promise": { args: ["a", "b", "c"], taps: [ { type: "promise" } ], interceptors: [] }, "mixed": { args: ["a", "b", "c"], taps: [ { type: "sync" }, { type: "async" }, { type: "promise" } ], interceptors: [] }, "mixed2": { args: ["a", "b", "c"], taps: [ { type: "async" }, { type: "promise" }, { type: "sync" }, ], interceptors: [] }, } for(const configurationName in factoryConfigurations) { describe(`(${configurationName})`, () => { let factory; beforeEach(() => { factory = new HookCodeFactory(); factory.init(factoryConfigurations[configurationName]); }); it("callTapsSeries", () => { const code = factory.callTapsSeries({ onError: (i, err) => `onError(${i}, ${err});\n`, onResult: (i, result, next, doneBreak) => `onResult(${i}, ${result}, () => {\n${next()}}, () => {\n${doneBreak()}});\n`, onDone: () => "onDone();\n", rethrowIfPossible: true }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); it("callTapsParallel", () => { const code = factory.callTapsParallel({ onError: (i, err) => `onError(${i}, ${err});\n`, onResult: (i, result, done, doneBreak) => `onResult(${i}, ${result}, () => {\n${done()}}, () => {\n${doneBreak()}});\n`, onDone: () => "onDone();\n", rethrowIfPossible: true }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); it("callTapsLooping", () => { const code = factory.callTapsLooping({ onError: (i, err) => `onError(${i}, ${err});\n`, onDone: () => "onDone();\n", rethrowIfPossible: true }); expect(code).toMatchSnapshot(); expectNoSyntaxError(code); }); }); } }); });
mit
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_dressed_sith_shadow_trn_f_01.py
460
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_sith_shadow_trn_f_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","trandoshan_base_female") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
mit
AuditoryBiophysicsLab/EarLab
src/SupportClasses/xercesc/internal/XSerializeEngine.cpp
28699
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: XSerializeEngine.cpp 695949 2008-09-16 15:57:44Z borisk $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/internal/XSerializeEngine.hpp> #include <xercesc/internal/XSerializable.hpp> #include <xercesc/internal/XProtoType.hpp> #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/framework/BinOutputStream.hpp> #include <xercesc/util/BinInputStream.hpp> #include <stdio.h> #include <assert.h> XERCES_CPP_NAMESPACE_BEGIN const bool XSerializeEngine::toWriteBufferLen = true; const bool XSerializeEngine::toReadBufferLen = true; static const unsigned long noDataFollowed = (unsigned long)-1; static const XSerializeEngine::XSerializedObjectId_t fgNullObjectTag = 0; // indicating null ptrs static const XSerializeEngine::XSerializedObjectId_t fgNewClassTag = 0xFFFFFFFF; // indicating new class static const XSerializeEngine::XSerializedObjectId_t fgTemplateObjTag = 0xFFFFFFFE; // indicating template object static const XSerializeEngine::XSerializedObjectId_t fgClassMask = 0x80000000; // indicates class tag static const XSerializeEngine::XSerializedObjectId_t fgMaxObjectCount = 0x3FFFFFFD; #define TEST_THROW_ARG1(condition, data, err_msg) \ if (condition) \ { \ XMLCh value1[17]; \ XMLString::binToText(data, value1, 16, 10, getMemoryManager()); \ ThrowXMLwithMemMgr1(XSerializationException \ , err_msg \ , value1 \ , getMemoryManager()); \ } #define TEST_THROW_ARG2(condition, data1, data2, err_msg) \ if (condition) \ { \ XMLCh value1[17]; \ XMLCh value2[17]; \ XMLString::binToText(data1, value1, 16, 10, getMemoryManager()); \ XMLString::binToText(data2, value2, 16, 10, getMemoryManager()); \ ThrowXMLwithMemMgr2(XSerializationException \ , err_msg \ , value1 \ , value2 \ , getMemoryManager()); \ } // --------------------------------------------------------------------------- // Constructor and Destructor // --------------------------------------------------------------------------- XSerializeEngine::~XSerializeEngine() { if (isStoring()) { flush(); delete fStorePool; } else { delete fLoadPool; } getMemoryManager()->deallocate(fBufStart); } XSerializeEngine::XSerializeEngine(BinInputStream* inStream , XMLGrammarPool* const gramPool , XMLSize_t bufSize) :fStoreLoad(mode_Load) ,fStorerLevel(0) ,fGrammarPool(gramPool) ,fInputStream(inStream) ,fOutputStream(0) ,fBufCount(0) ,fBufSize(bufSize) ,fBufStart( (XMLByte*) gramPool->getMemoryManager()->allocate(bufSize)) ,fBufEnd(0) ,fBufCur(fBufStart) ,fBufLoadMax(fBufStart) ,fStorePool(0) ,fLoadPool( new (gramPool->getMemoryManager()) ValueVectorOf<void*>(29, gramPool->getMemoryManager(), false)) ,fObjectCount(0) { /*** * initialize buffer from the inStream ***/ fillBuffer(); } XSerializeEngine::XSerializeEngine(BinOutputStream* outStream , XMLGrammarPool* const gramPool , XMLSize_t bufSize) :fStoreLoad(mode_Store) ,fStorerLevel(0) ,fGrammarPool(gramPool) ,fInputStream(0) ,fOutputStream(outStream) ,fBufCount(0) ,fBufSize(bufSize) ,fBufStart((XMLByte*) gramPool->getMemoryManager()->allocate(bufSize)) ,fBufEnd(fBufStart+bufSize) ,fBufCur(fBufStart) ,fBufLoadMax(0) ,fStorePool( new (gramPool->getMemoryManager()) RefHashTableOf<XSerializedObjectId, PtrHasher>(29, true, gramPool->getMemoryManager()) ) ,fLoadPool(0) ,fObjectCount(0) { resetBuffer(); //initialize store pool fStorePool->put(0, new (gramPool->getMemoryManager()) XSerializedObjectId(fgNullObjectTag)); } void XSerializeEngine::flush() { if (isStoring()) flushBuffer(); } // --------------------------------------------------------------------------- // Storing // --------------------------------------------------------------------------- void XSerializeEngine::write(XSerializable* const objectToWrite) { ensureStoring(); //don't ensurePointer here !!! XSerializedObjectId_t objIndex = 0; if (!objectToWrite) // null pointer { *this << fgNullObjectTag; } else if (0 != (objIndex = lookupStorePool((void*) objectToWrite))) { // writing an object reference tag *this << objIndex; } else { // write protoType first XProtoType* protoType = objectToWrite->getProtoType(); write(protoType); // put the object into StorePool addStorePool((void*)objectToWrite); // ask the object to serialize itself objectToWrite->serialize(*this); } } void XSerializeEngine::write(XProtoType* const protoType) { ensureStoring(); ensurePointer(protoType); XSerializedObjectId_t objIndex = lookupStorePool((void*)protoType); if (objIndex) { //protoType seen in the store pool *this << (fgClassMask | objIndex); } else { // store protoType *this << fgNewClassTag; protoType->store(*this); addStorePool((void*)protoType); } } /*** * ***/ void XSerializeEngine::write(const XMLCh* const toWrite , XMLSize_t writeLen) { write((XMLByte*)toWrite, (sizeof(XMLCh)/sizeof(XMLByte)) * writeLen); } void XSerializeEngine::write(const XMLByte* const toWrite , XMLSize_t writeLen) { ensureStoring(); ensurePointer((void*)toWrite); ensureStoreBuffer(); if (writeLen == 0) return; /*** * If the available space is sufficient, write it up ***/ XMLSize_t bufAvail = fBufEnd - fBufCur; if (writeLen <= bufAvail) { memcpy(fBufCur, toWrite, writeLen); fBufCur += writeLen; return; } const XMLByte* tempWrite = (const XMLByte*) toWrite; XMLSize_t writeRemain = writeLen; // fill up the avaiable space and flush memcpy(fBufCur, tempWrite, bufAvail); tempWrite += bufAvail; writeRemain -= bufAvail; flushBuffer(); // write chunks of fBufSize while (writeRemain >= fBufSize) { memcpy(fBufCur, tempWrite, fBufSize); tempWrite += fBufSize; writeRemain -= fBufSize; flushBuffer(); } // write the remaining if any if (writeRemain) { memcpy(fBufCur, tempWrite, writeRemain); fBufCur += writeRemain; } } /*** * * Storage scheme (normal): * * < * 1st integer: bufferLen (optional) * 2nd integer: dataLen * bytes following: * > * * Storage scheme (special): * < * only integer: noDataFollowed * > */ void XSerializeEngine::writeString(const XMLCh* const toWrite , const XMLSize_t bufferLen , bool toWriteBufLen) { if (toWrite) { if (toWriteBufLen) *this<<(unsigned long)bufferLen; XMLSize_t strLen = XMLString::stringLen(toWrite); *this<<(unsigned long)strLen; write(toWrite, strLen); } else { *this<<noDataFollowed; } } void XSerializeEngine::writeString(const XMLByte* const toWrite , const XMLSize_t bufferLen , bool toWriteBufLen) { if (toWrite) { if (toWriteBufLen) *this<<(unsigned long)bufferLen; XMLSize_t strLen = XMLString::stringLen((char*)toWrite); *this<<(unsigned long)strLen; write(toWrite, strLen); } else { *this<<noDataFollowed; } } // --------------------------------------------------------------------------- // Loading // --------------------------------------------------------------------------- XSerializable* XSerializeEngine::read(XProtoType* const protoType) { ensureLoading(); ensurePointer(protoType); XSerializedObjectId_t objectTag; XSerializable* objRet; if (! read(protoType, &objectTag)) { /*** * We hava a reference to an existing object in * load pool, get it. */ objRet = lookupLoadPool(objectTag); } else { // create the object from the prototype objRet = protoType->fCreateObject(getMemoryManager()); Assert((objRet != 0), XMLExcepts::XSer_CreateObject_Fail); // put it into load pool addLoadPool(objRet); // de-serialize it objRet->serialize(*this); } return objRet; } bool XSerializeEngine::read(XProtoType* const protoType , XSerializedObjectId_t* objectTagRet) { ensureLoading(); ensurePointer(protoType); XSerializedObjectId_t obTag; *this >> obTag; // object reference tag found if (!(obTag & fgClassMask)) { *objectTagRet = obTag; return false; } if (obTag == fgNewClassTag) { // what follows fgNewClassTag is the prototype object info // for the object anticipated, go and verify the info XProtoType::load(*this, protoType->fClassName, getMemoryManager()); addLoadPool((void*)protoType); } else { // what follows class tag is an XSerializable object XSerializedObjectId_t classIndex = (obTag & ~fgClassMask); XSerializedObjectId_t loadPoolSize = (XSerializedObjectId_t)fLoadPool->size(); TEST_THROW_ARG2(((classIndex == 0 ) || (classIndex > loadPoolSize)) , classIndex , loadPoolSize , XMLExcepts::XSer_Inv_ClassIndex ) ensurePointer(lookupLoadPool(classIndex)); } return true; } void XSerializeEngine::read(XMLCh* const toRead , XMLSize_t readLen) { read((XMLByte*)toRead, (sizeof(XMLCh)/sizeof(XMLByte))*readLen); } void XSerializeEngine::read(XMLByte* const toRead , XMLSize_t readLen) { ensureLoading(); ensurePointer(toRead); ensureLoadBuffer(); if (readLen == 0) return; /*** * If unread is sufficient, read it up ***/ XMLSize_t dataAvail = fBufLoadMax - fBufCur; if (readLen <= dataAvail) { memcpy(toRead, fBufCur, readLen); fBufCur += readLen; return; } /*** * * fillBuffer will discard anything left in the buffer * before it asks the inputStream to fill in the buffer, * so we need to readup everything in the buffer before * calling fillBuffer * ***/ XMLByte* tempRead = (XMLByte*) toRead; XMLSize_t readRemain = readLen; // read the unread memcpy(tempRead, fBufCur, dataAvail); tempRead += dataAvail; readRemain -= dataAvail; // read chunks of fBufSize while (readRemain >= fBufSize) { fillBuffer(); memcpy(tempRead, fBufCur, fBufSize); tempRead += fBufSize; readRemain -= fBufSize; } // read the remaining if any if (readRemain) { fillBuffer(); memcpy(tempRead, fBufCur, readRemain); fBufCur += readRemain; } } /*** * * Storage scheme (normal): * * < * 1st integer: bufferLen (optional) * 2nd integer: dataLen * bytes following: * > * * Storage scheme (special): * < * only integer: noDataFollowed * > */ void XSerializeEngine::readString(XMLCh*& toRead , XMLSize_t& bufferLen , XMLSize_t& dataLen , bool toReadBufLen) { /*** * Check if any data written ***/ unsigned long tmp; *this>>tmp; bufferLen=tmp; if (bufferLen == noDataFollowed) { toRead = 0; bufferLen = 0; dataLen = 0; return; } if (toReadBufLen) { *this>>tmp; dataLen=tmp; } else { dataLen = bufferLen++; } toRead = (XMLCh*) getMemoryManager()->allocate(bufferLen * sizeof(XMLCh)); read(toRead, dataLen); toRead[dataLen] = 0; } void XSerializeEngine::readString(XMLByte*& toRead , XMLSize_t& bufferLen , XMLSize_t& dataLen , bool toReadBufLen) { /*** * Check if any data written ***/ unsigned long tmp; *this>>tmp; bufferLen=tmp; if (bufferLen == noDataFollowed) { toRead = 0; bufferLen = 0; dataLen = 0; return; } if (toReadBufLen) { *this>>tmp; dataLen=tmp; } else { dataLen = bufferLen++; } toRead = (XMLByte*) getMemoryManager()->allocate(bufferLen * sizeof(XMLByte)); read(toRead, dataLen); toRead[dataLen] = 0; } // --------------------------------------------------------------------------- // Insertion & Extraction // --------------------------------------------------------------------------- XSerializeEngine& XSerializeEngine::operator<<(XMLCh xch) { checkAndFlushBuffer(calBytesNeeded(sizeof(XMLCh))); alignBufCur(sizeof(XMLCh)); *(XMLCh*)fBufCur = xch; fBufCur += sizeof(XMLCh); return *this; } XSerializeEngine& XSerializeEngine::operator>>(XMLCh& xch) { checkAndFillBuffer(calBytesNeeded(sizeof(XMLCh))); alignBufCur(sizeof(XMLCh)); xch = *(XMLCh*)fBufCur; fBufCur += sizeof(XMLCh); return *this; } XSerializeEngine& XSerializeEngine::operator<<(XMLByte by) { checkAndFlushBuffer(sizeof(XMLByte)); *(XMLByte*)fBufCur = by; fBufCur += sizeof(XMLByte); return *this; } XSerializeEngine& XSerializeEngine::operator>>(XMLByte& by) { checkAndFillBuffer(sizeof(XMLByte)); by = *(XMLByte*)fBufCur; fBufCur += sizeof(XMLByte); return *this; } XSerializeEngine& XSerializeEngine::operator<<(bool b) { checkAndFlushBuffer(sizeof(bool)); *(bool*)fBufCur = b; fBufCur += sizeof(bool); return *this; } XSerializeEngine& XSerializeEngine::operator>>(bool& b) { checkAndFillBuffer(sizeof(bool)); b = *(bool*)fBufCur; fBufCur += sizeof(bool); return *this; } void XSerializeEngine::writeSize (XMLSize_t t) { checkAndFlushBuffer(sizeof(t)); memcpy(fBufCur, &t, sizeof(t)); fBufCur += sizeof(t); } void XSerializeEngine::writeInt64 (XMLInt64 t) { checkAndFlushBuffer(sizeof(t)); memcpy(fBufCur, &t, sizeof(t)); fBufCur += sizeof(t); } void XSerializeEngine::writeUInt64 (XMLUInt64 t) { checkAndFlushBuffer(sizeof(t)); memcpy(fBufCur, &t, sizeof(t)); fBufCur += sizeof(t); } void XSerializeEngine::readSize (XMLSize_t& t) { checkAndFillBuffer(sizeof(t)); memcpy(&t, fBufCur, sizeof(t)); fBufCur += sizeof(t); } void XSerializeEngine::readInt64 (XMLInt64& t) { checkAndFillBuffer(sizeof(t)); memcpy(&t, fBufCur, sizeof(t)); fBufCur += sizeof(t); } void XSerializeEngine::readUInt64 (XMLUInt64& t) { checkAndFillBuffer(sizeof(t)); memcpy(&t, fBufCur, sizeof(t)); fBufCur += sizeof(t); } XSerializeEngine& XSerializeEngine::operator<<(char ch) { return XSerializeEngine::operator<<((XMLByte)ch); } XSerializeEngine& XSerializeEngine::operator>>(char& ch) { return XSerializeEngine::operator>>((XMLByte&)ch); } XSerializeEngine& XSerializeEngine::operator<<(short sh) { checkAndFlushBuffer(calBytesNeeded(sizeof(short))); alignBufCur(sizeof(short)); *(short*)fBufCur = sh; fBufCur += sizeof(short); return *this; } XSerializeEngine& XSerializeEngine::operator>>(short& sh) { checkAndFillBuffer(calBytesNeeded(sizeof(short))); alignBufCur(sizeof(short)); sh = *(short*)fBufCur; fBufCur += sizeof(short); return *this; } XSerializeEngine& XSerializeEngine::operator<<(int i) { checkAndFlushBuffer(calBytesNeeded(sizeof(int))); alignBufCur(sizeof(int)); *(int*)fBufCur = i; fBufCur += sizeof(int); return *this; } XSerializeEngine& XSerializeEngine::operator>>(int& i) { checkAndFillBuffer(calBytesNeeded(sizeof(int))); alignBufCur(sizeof(int)); i = *(int*)fBufCur; fBufCur += sizeof(int); return *this; } XSerializeEngine& XSerializeEngine::operator<<(unsigned int ui) { checkAndFlushBuffer(calBytesNeeded(sizeof(unsigned int))); alignBufCur(sizeof(unsigned int)); *(unsigned int*)fBufCur = ui; fBufCur += sizeof(unsigned int); return *this; } XSerializeEngine& XSerializeEngine::operator>>(unsigned int& ui) { checkAndFillBuffer(calBytesNeeded(sizeof(unsigned int))); alignBufCur(sizeof(unsigned int)); ui = *(unsigned int*)fBufCur; fBufCur += sizeof(unsigned int); return *this; } XSerializeEngine& XSerializeEngine::operator<<(long l) { checkAndFlushBuffer(calBytesNeeded(sizeof(long))); alignBufCur(sizeof(long)); *(long*)fBufCur = l; fBufCur += sizeof(long); return *this; } XSerializeEngine& XSerializeEngine::operator>>(long& l) { checkAndFillBuffer(calBytesNeeded(sizeof(long))); alignBufCur(sizeof(long)); l = *(long*)fBufCur; fBufCur += sizeof(long); return *this; } XSerializeEngine& XSerializeEngine::operator<<(unsigned long ul) { checkAndFlushBuffer(calBytesNeeded(sizeof(unsigned long))); alignBufCur(sizeof(unsigned long)); *(unsigned long*)fBufCur = ul; fBufCur += sizeof(unsigned long); return *this; } XSerializeEngine& XSerializeEngine::operator>>(unsigned long& ul) { checkAndFillBuffer(calBytesNeeded(sizeof(unsigned long))); alignBufCur(sizeof(unsigned long)); ul = *(unsigned long*)fBufCur; fBufCur += sizeof(unsigned long); return *this; } XSerializeEngine& XSerializeEngine::operator<<(float f) { checkAndFlushBuffer(calBytesNeeded(sizeof(float))); alignBufCur(sizeof(float)); *(float*)fBufCur = *(float*)&f; fBufCur += sizeof(float); return *this; } XSerializeEngine& XSerializeEngine::operator>>(float& f) { checkAndFillBuffer(calBytesNeeded(sizeof(float))); alignBufCur(sizeof(float)); *(float*)&f = *(float*)fBufCur; fBufCur += sizeof(float); return *this; } XSerializeEngine& XSerializeEngine::operator<<(double d) { checkAndFlushBuffer(calBytesNeeded(sizeof(double))); alignBufCur(sizeof(double)); *(double*)fBufCur = *(double*)&d; fBufCur += sizeof(double); return *this; } XSerializeEngine& XSerializeEngine::operator>>(double& d) { checkAndFillBuffer(calBytesNeeded(sizeof(double))); alignBufCur(sizeof(double)); *(double*)&d = *(double*)fBufCur; fBufCur += sizeof(double); return *this; } // --------------------------------------------------------------------------- // StorePool/LoadPool Opertions // --------------------------------------------------------------------------- XSerializeEngine::XSerializedObjectId_t XSerializeEngine::lookupStorePool(void* const objToLookup) const { //0 indicating object is not in the StorePool XSerializedObjectId* data = fStorePool->get(objToLookup); return (XSerializeEngine::XSerializedObjectId_t) (data ? data->getValue() : 0); } void XSerializeEngine::addStorePool(void* const objToAdd) { pumpCount(); fStorePool->put(objToAdd, new (fGrammarPool->getMemoryManager()) XSerializedObjectId(fObjectCount)); } XSerializable* XSerializeEngine::lookupLoadPool(XSerializedObjectId_t objectTag) const { /*** * an object tag read from the binary refering to * an object beyond the upper most boundary of the load pool ***/ TEST_THROW_ARG2( (objectTag > fLoadPool->size()) , objectTag , (unsigned long)fLoadPool->size() // @@ Need to use sizeToText directly. , XMLExcepts::XSer_LoadPool_UppBnd_Exceed ) if (objectTag == 0) return 0; /*** * A non-null object tag starts from 1 while fLoadPool starts from 0 ***/ return (XSerializable*) fLoadPool->elementAt(objectTag - 1); } void XSerializeEngine::addLoadPool(void* const objToAdd) { TEST_THROW_ARG2( (fLoadPool->size() != fObjectCount) , fObjectCount , (unsigned long)fLoadPool->size() // @@ Need to use sizeToText directly. , XMLExcepts::XSer_LoadPool_NoTally_ObjCnt ) pumpCount(); fLoadPool->addElement(objToAdd); } void XSerializeEngine::pumpCount() { TEST_THROW_ARG2( (fObjectCount >= fgMaxObjectCount) , fObjectCount , fgMaxObjectCount , XMLExcepts::XSer_ObjCount_UppBnd_Exceed ) fObjectCount++; } // --------------------------------------------------------------------------- // Buffer Opertions // --------------------------------------------------------------------------- /*** * * Though client may need only miniBytesNeeded, we always request * a full size reading from our inputStream. * * Whatever possibly left in the buffer is abandoned, such as in * the case of CheckAndFillBuffer() * ***/ void XSerializeEngine::fillBuffer() { ensureLoading(); ensureLoadBuffer(); resetBuffer(); XMLSize_t bytesRead = fInputStream->readBytes(fBufStart, fBufSize); /*** * InputStream MUST fill in the exact amount of bytes as requested * to do: combine the checking and create a new exception code later ***/ TEST_THROW_ARG2( (bytesRead < fBufSize) , (unsigned long)bytesRead // @@ Need to use sizeToText directly. , (unsigned long)fBufSize // @@ Need to use sizeToText directly. , XMLExcepts::XSer_InStream_Read_LT_Req ) TEST_THROW_ARG2( (bytesRead > fBufSize) , (unsigned long)bytesRead // @@ Need to use sizeToText directly. , (unsigned long)fBufSize // @@ Need to use sizeToText directly. , XMLExcepts::XSer_InStream_Read_OverFlow ) fBufLoadMax = fBufStart + fBufSize; fBufCur = fBufStart; ensureLoadBuffer(); fBufCount++; } /*** * * Flush out whatever left in the buffer, from * fBufStart to fBufEnd. * ***/ void XSerializeEngine::flushBuffer() { ensureStoring(); ensureStoreBuffer(); fOutputStream->writeBytes(fBufStart, fBufSize); fBufCur = fBufStart; resetBuffer(); ensureStoreBuffer(); fBufCount++; } inline void XSerializeEngine::checkAndFlushBuffer(XMLSize_t bytesNeedToWrite) { TEST_THROW_ARG1( (bytesNeedToWrite <= 0) , (unsigned long)bytesNeedToWrite // @@ Need to use sizeToText directly. , XMLExcepts::XSer_Inv_checkFlushBuffer_Size ) // fBufStart ... fBufCur ...fBufEnd if ((fBufCur + bytesNeedToWrite) > fBufEnd) flushBuffer(); } inline void XSerializeEngine::checkAndFillBuffer(XMLSize_t bytesNeedToRead) { TEST_THROW_ARG1( (bytesNeedToRead <= 0) , (unsigned long)bytesNeedToRead // @@ Need to use sizeToText directly. , XMLExcepts::XSer_Inv_checkFillBuffer_Size ) // fBufStart ... fBufCur ...fBufLoadMax if ((fBufCur + bytesNeedToRead) > fBufLoadMax) { fillBuffer(); } } inline void XSerializeEngine::ensureStoreBuffer() const { TEST_THROW_ARG2 ( !((fBufStart <= fBufCur) && (fBufCur <= fBufEnd)) , (unsigned long)(fBufCur - fBufStart) // @@ Need to use sizeToText directly. , (unsigned long)(fBufEnd - fBufCur) // @@ Need to use sizeToText directly. , XMLExcepts::XSer_StoreBuffer_Violation ) } inline void XSerializeEngine::ensureLoadBuffer() const { TEST_THROW_ARG2 ( !((fBufStart <= fBufCur) && (fBufCur <= fBufLoadMax)) , (unsigned long)(fBufCur - fBufStart) , (unsigned long)(fBufLoadMax - fBufCur) , XMLExcepts::XSer_LoadBuffer_Violation ) } inline void XSerializeEngine::ensurePointer(void* const ptr) const { TEST_THROW_ARG1( (ptr == 0) , 0 , XMLExcepts::XSer_Inv_Null_Pointer ) } inline void XSerializeEngine::resetBuffer() { memset(fBufStart, 0, fBufSize * sizeof(XMLByte)); } // --------------------------------------------------------------------------- // Template object // --------------------------------------------------------------------------- /*** * * Search the store pool to see if the address has been seen before or not. * * If yes, write the corresponding object Tag to the internal buffer * and return true. * * Otherwise, add the address to the store pool and return false * to notifiy the client application code to store the template object. * ***/ bool XSerializeEngine::needToStoreObject(void* const templateObjectToWrite) { ensureStoring(); //don't ensurePointer here !!! XSerializedObjectId_t objIndex = 0; if (!templateObjectToWrite) { *this << fgNullObjectTag; // null pointer return false; } else if (0 != (objIndex = lookupStorePool(templateObjectToWrite))) { *this << objIndex; // write an object reference tag return false; } else { *this << fgTemplateObjTag; // write fgTemplateObjTag to denote that actual // template object follows addStorePool(templateObjectToWrite); // put the address into StorePool return true; } } bool XSerializeEngine::needToLoadObject(void** templateObjectToRead) { ensureLoading(); XSerializedObjectId_t obTag; *this >> obTag; if (obTag == fgTemplateObjTag) { /*** * what follows fgTemplateObjTag is the actual template object * We need the client application to create a template object * and register it through registerObject(), and deserialize * template object ***/ return true; } else { /*** * We hava a reference to an existing template object, get it. */ *templateObjectToRead = lookupLoadPool(obTag); return false; } } void XSerializeEngine::registerObject(void* const templateObjectToRegister) { ensureLoading(); addLoadPool(templateObjectToRegister); } XMLGrammarPool* XSerializeEngine::getGrammarPool() const { return fGrammarPool; } XMLStringPool* XSerializeEngine::getStringPool() const { return fGrammarPool->getURIStringPool(); } MemoryManager* XSerializeEngine::getMemoryManager() const { //todo: changed to return fGrammarPool->getMemoryManager() return fGrammarPool ? fGrammarPool->getMemoryManager() : XMLPlatformUtils::fgMemoryManager; } // // Based on the current position (fBufCur), calculated the needed size // to read/write // inline XMLSize_t XSerializeEngine::alignAdjust(XMLSize_t size) const { XMLSize_t remainder = (XMLSize_t) fBufCur % size; return (remainder == 0) ? 0 : (size - remainder); } // Adjust the fBufCur inline void XSerializeEngine::alignBufCur(XMLSize_t size) { fBufCur+=alignAdjust(size); assert(((XMLSize_t) fBufCur % size)==0); } inline XMLSize_t XSerializeEngine::calBytesNeeded(XMLSize_t size) const { return (alignAdjust(size) + size); } void XSerializeEngine::trace(char* /*funcName*/) const { return; /* if (isStoring()) printf("\n funcName=<%s>, storing, count=<%lu>, postion=<%lu>\n", funcName, fBufCount, getBufCurAccumulated()); else printf("\n funcName=<%s>, loading, count=<%lu>, postion=<%lu>\n", funcName, fBufCount, getBufCurAccumulated()); */ } XERCES_CPP_NAMESPACE_END
mit
hirotakagi/Ponytail
Twintail Project/ch2Solution/twin/Tools/X2ch/Samba24.cs
4160
// Samba24.cs namespace Twin.Tools { using System; using System.Collections.Generic; using System.IO; using CSharpSamples; using System.Net; using System.Text.RegularExpressions; using System.Diagnostics; /// <summary> /// Samba24‘΍ô‚ÉŽ©Žå‹K§‚ðs‚¤ /// </summary> public class Samba24 { private Dictionary<string, DateTime> dicCounter = new Dictionary<string, DateTime>(); private CSPrivateProfile profile = new CSPrivateProfile(); private string filePath = null; /// <summary> /// Žw’肵‚½ƒT[ƒo[–¼‚Ì‹K§•b”‚ðŽæ“¾ /// </summary> public int this[string server] { get { return profile.GetInt("samba", server, 0); } } /// <summary> /// Samba24ƒNƒ‰ƒX‚̃Cƒ“ƒXƒ^ƒ“ƒX‚ð‰Šú‰» /// </summary> public Samba24() { // // TODO: ƒRƒ“ƒXƒgƒ‰ƒNƒ^ ƒƒWƒbƒN‚ð‚±‚±‚ɒljÁ‚µ‚Ä‚­‚¾‚³‚¢B // } /// <summary> /// Samba24ƒNƒ‰ƒX‚̃Cƒ“ƒXƒ^ƒ“ƒX‚ð‰Šú‰» /// </summary> public Samba24(string filePath) : this() { Load(filePath); } /// <summary> /// sambaÝ’èƒtƒ@ƒCƒ‹‚ð“ǂݍž‚Þ /// </summary> /// <param name="filePath"></param> public void Load(string filePath) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (File.Exists(filePath)) profile.Read(filePath); this.filePath = filePath; } /// <summary> /// Žw’肵‚½ƒT[ƒo[‚̃JƒEƒ“ƒ^[ŠJŽn /// </summary> /// <param name="server"></param> public void CountStart(string serverName) { // Œ»Ý’l‚ðÝ’è dicCounter[serverName] = DateTime.Now; } /// <summary> /// Žw’肵‚½ƒT[ƒo[‚Ì‹K§ŽžŠÔ‚ªŒo‰ß‚µ‚½‚©‚Ç‚¤‚©‚ð”»’f /// </summary> /// <param name="server">ƒ`ƒFƒbƒN‚·‚éƒT[ƒo[–¼iƒzƒXƒgƒAƒhƒŒƒX‚ł͂Ȃ¢j</param> /// <returns>‹K§ŽžŠÔ‚ð‰ß‚¬‚Ä‚¢‚½‚çtrueA‹K§ŽžŠÔ“à‚È‚çfalse</returns> public bool IsElapsed(string serverName) { int r; return IsElapsed(serverName, out r); } /// <summary> /// Žw’肵‚½ƒT[ƒo[‚Ì‹K§ŽžŠÔ‚ªŒo‰ß‚µ‚½‚©‚Ç‚¤‚©‚ð”»’fB /// ƒJƒEƒ“ƒ^‚ªŠJŽn‚³‚ê‚Ä‚¢‚È‚¯‚ê‚΁Aí‚Étrue‚ð•Ô‚·B /// </summary> /// <param name="server">ƒ`ƒFƒbƒN‚·‚éƒT[ƒo[–¼iƒzƒXƒgƒAƒhƒŒƒX‚ł͂Ȃ¢j</param> /// <param name="result">Žc‚è•b”‚ªŠi”[‚³‚ê‚é</param> /// <returns>server ‚ªƒJƒEƒ“ƒ^‚É“o˜^‚³‚ê‚Ä‚¢‚È‚¢ê‡A‚Ü‚½‚̓JƒEƒ“ƒ^‚ª‹K§ŽžŠÔ‚ð‰ß‚¬‚Ä‚¢‚½‚çtrueA‹K§ŽžŠÔ“à‚È‚çfalse</returns> public bool IsElapsed(string serverName, out int result) { if (dicCounter.ContainsKey(serverName)) { var time = dicCounter[serverName]; // ŠJŽn’l // Œo‰ß•b”‚ðŒvŽZ int elapsedSeconds = (DateTime.Now - time).Seconds; // Žc‚è•b”‚ðŒvŽZ result = this[serverName] - elapsedSeconds; return (elapsedSeconds > this[serverName]) ? true : false; } else { //throw new ArgumentException(server + "‚ÌŠJŽn’l‚ª‘¶Ý‚µ‚Ü‚¹‚ñ"); result = 0; return true; } } /// <summary> /// Žw’肵‚½ƒT[ƒo[‚ÌSambaƒJƒEƒ“ƒg‚ðC³ /// </summary> /// <param name="serverName">ƒT[ƒo[–¼iƒzƒXƒgƒAƒhƒŒƒX‚ł͂Ȃ¢j</param> /// <param name="newCount"></param> public void Correct(string serverName, int newCount) { // ƒe[ƒuƒ‹‚ɐV‚µ‚¢’l‚ðÝ’肵‚ĕۑ¶ profile.SetValue("samba", serverName, newCount); if (filePath != null) profile.Write(filePath); } /// <summary> /// ‚·‚ׂẴJƒEƒ“ƒ^‚ðƒŠƒZƒbƒg /// </summary> public void Reset() { dicCounter.Clear(); } /// <summary> /// ”‚̃gƒbƒvƒy[ƒW‚ðŽæ“¾‚µ‚āAÅV‚Ìsamba’l‚ðŽæ“¾B /// </summary> /// <param name="bi"></param> /// <returns>³‚µ‚­XV‚³‚ꂽê‡‚ɂ́AÅV‚Ìsamba24‚Ì’l‚ð•Ô‚µ‚Ü‚·BƒT[ƒo[ƒGƒ‰[‚ȂǁA‚»‚êˆÈŠO‚Í -1 ‚ð•Ô‚µ‚Ü‚·B</returns> public int Update(BoardInfo bi) { if (bi == null) throw new ArgumentNullException("bi"); try { using (WebClient w = new WebClient()) { string html = w.DownloadString(bi.Url); Match m = Regex.Match(html, @"\+Samba24=([0-9]+)", RegexOptions.RightToLeft); int newVal; if (Int32.TryParse(m.Groups[1].Value, out newVal)) { Correct(bi.ServerName, newVal); Debug.WriteLine("Samba24, Update: " + newVal); return newVal; } } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } return -1; } } }
mit
musicsnap/LearnCode
php/code/yaf/application/library/Taobao/Request/WlbNotifyMessageConfirmRequest.php
935
<?php /** * TOP API: taobao.wlb.notify.message.confirm request * * @author auto create * @since 1.0, 2013-09-13 16:51:03 */ class Taobao_Request_WlbNotifyMessageConfirmRequest { /** * 物流宝通知消息的id,通过taobao.wlb.notify.message.page.get接口得到的WlbMessage数据结构中的id字段 **/ private $messageId; private $apiParas = array(); public function setMessageId($messageId) { $this->messageId = $messageId; $this->apiParas["message_id"] = $messageId; } public function getMessageId() { return $this->messageId; } public function getApiMethodName() { return "taobao.wlb.notify.message.confirm"; } public function getApiParas() { return $this->apiParas; } public function check() { Taobao_RequestCheckUtil::checkNotNull($this->messageId, "messageId"); } public function putOtherTextParam($key, $value) { $this->apiParas[$key] = $value; $this->$key = $value; } }
mit
enclose-io/enclose-io
db/migrate/20170720032819_alter_name_of_projects.rb
314
class AlterNameOfProjects < ActiveRecord::Migration[5.1] def change change_column :projects, :name, :string, null: false, unique: true add_index :projects, :name, unique: true change_column :projects, :token, :string, null: false, unique: true add_index :projects, :token, unique: true end end
mit
devatwork/Premotion-Mansion
src/Premotion.Mansion.Core/Templating/ParseTemplateException.cs
879
using System; using Premotion.Mansion.Core.IO; namespace Premotion.Mansion.Core.Templating { /// <summary> /// Thrown when a <see cref="IResource"/> can not be parsed into a <see cref="ITemplate"/>. /// </summary> public class ParseTemplateException : ApplicationException { #region Constructors /// <summary> /// </summary> /// <param name="resource"></param> /// <param name="innerException"></param> public ParseTemplateException(IResource resource, Exception innerException) : base(string.Empty, innerException) { // validate arguments if (resource == null) throw new ArgumentNullException("resource"); // set values Resource = resource; } #endregion #region Properties /// <summary> /// Gets the resource which couldn't be parsed properly. /// </summary> public IResource Resource { get; private set; } #endregion } }
mit
ceciGomez/proyecto
application/views/home/escri.php
2731
<!-- Content Wrapper. Contains page content --><style> table { border-collapse: collapse; width: 100%; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; } tr:hover{background-color:#f5f5f5} </style> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <br> <ol class="breadcrumb"> <li><a href="<?=base_url()?>index.php/c_loginescri"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">Escribano</li> </ol> </section> <!-- Main content --> <section class="content"> <!-- Main row --> <div class="row"> <div class="col-md-12"> <!-- Profile Image --> <div class="box box-primary"> <div class="box-body box-profile"> <h3 class="profile-username text-center">BIENVENIDO A SIRMI</h3> <img class="profile-user-img img-responsive img-circle" src="<?=base_url()?>assets/dist/img/<?php echo $this->session->userdata('foto'); ?>" alt="User profile picture"> <h3 class="profile-username text-center"><?php echo $this->session->userdata('nomyap') ?></h3> <p class="text-muted text-center"><?php echo $this->session->userdata('perfil') ?></p> </div> <!-- /.box-body --> <table class="table" class="table-bordered" > <tbody> <tr> <th> Nombre y Apellido</th><td> <?php echo $escribano[0]->nomyap ?> </td> </tr> <tr> <th> Nombre de Usuario</th><td> <?php echo $escribano[0]->usuario ?></td> </tr> <tr> <th> Fecha de Registración</th><td> <?php echo $escribano[0]->fechaReg ?> </td> </tr> <tr> <th> DNI</th><td><?php echo $escribano[0]->dni ?> </td> </tr> <tr> <th> Dirección</th><td> <?php echo $escribano[0]->matricula ?> </td> </tr> <tr> <th> Teléfono</th><td> <?php echo $escribano[0]->telefono ?> </td> </tr> <tr> <th> Email</th><td> <?php echo $escribano[0]->email ?> </td> </tr> <tr> <tr> <th> Dirección</th><td> <?php echo $escribano[0]->direccion ?> </td> </tr> <th> Localidad</th><td> <?php echo $escribano[0]->nombreLocalidad?></td> </tr> <tr> <th> Perfil</th><td> Escribano </td> </tr> </tbody> </table> </div> <!-- /.box --> </div> <!-- /.col --> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <!-- /.content-wrapper -->
mit
arenoir/data
packages/-ember-data/tests/test-helper.js
1392
import { setApplication } from '@ember/test-helpers'; import QUnit from 'qunit'; import RSVP from 'rsvp'; import { start } from 'ember-qunit'; import assertAllDeprecations from '@ember-data/unpublished-test-infra/test-support/assert-all-deprecations'; import additionalLegacyAsserts from '@ember-data/unpublished-test-infra/test-support/legacy'; import configureAsserts from '@ember-data/unpublished-test-infra/test-support/qunit-asserts'; import customQUnitAdapter from '@ember-data/unpublished-test-infra/test-support/testem/custom-qunit-adapter'; import Application from '../app'; import config from '../config/environment'; if (window.Promise === undefined) { window.Promise = RSVP.Promise; } configureAsserts(); additionalLegacyAsserts(); setApplication(Application.create(config.APP)); assertAllDeprecations(); if (window.Testem) { window.Testem.useCustomAdapter(customQUnitAdapter); } QUnit.begin(function() { RSVP.configure('onerror', reason => { // only print error messages if they're exceptions; // otherwise, let a future turn of the event loop // handle the error. // TODO kill this off if (reason && reason instanceof Error) { throw reason; } }); }); QUnit.config.testTimeout = 2000; QUnit.config.urlConfig.push({ id: 'enableoptionalfeatures', label: 'Enable Opt Features', }); start({ setupTestIsolationValidation: true });
mit
jnajdi/canvas_starter_app_local
client/node_modules/material-ui/lib/svg-icons/image/colorize.js
569
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var ImageColorize = React.createClass({ displayName: 'ImageColorize', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M20.71 5.63l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42zM6.92 19L5 17.08l8.06-8.06 1.92 1.92L6.92 19z' }) ); } }); module.exports = ImageColorize;
mit
kphanjsu/TicTacToe-1
src/com/java/laiy/Main.java
181
package com.java.laiy; import com.java.laiy.view.*; public class Main { public static void main(final String[] args) { ConsoleMenuView.showMenuWithResult(); } }
mit
xabbuh/platform
src/Oro/Bundle/NotificationBundle/Tests/Unit/Doctrine/EntityPoolTest.php
2883
<?php namespace Oro\Bundle\NotificationBundle\Tests\Unit\Doctrine; use Oro\Bundle\NotificationBundle\Doctrine\EntityPool; class EntityPoolTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPUnit_Framework_MockObject_MockObject */ protected $entityManager; /** * @var EntityPool */ protected $entityPool; public function setUp() { $this->entityManager = $this->getMockBuilder('Doctrine\\ORM\\EntityManager') ->disableOriginalConstructor() ->getMock(); $this->entityPool = new EntityPool(); } public function testAddPersistEntity() { $entity = $this->createTestEntity(); $this->entityPool->addPersistEntity($entity); $this->assertAttributeEquals(array($entity), 'persistEntities', $this->entityPool); } public function testAddPersistAndClearWithNoEntities() { $this->entityManager->expects($this->never())->method($this->anything()); $this->entityPool->persistAndClear($this->entityManager); } public function testAddPersistAndClear() { $this->entityPool->addPersistEntity($fooEntity = $this->createTestEntity()); $this->entityPool->addPersistEntity($barEntity = $this->createTestEntity()); $this->entityManager->expects($this->at(0)) ->method('persist') ->with($fooEntity); $this->entityManager->expects($this->at(1)) ->method('persist') ->with($barEntity); $this->entityManager->expects($this->never()) ->method('flush'); $this->entityPool->persistAndClear($this->entityManager); $this->assertAttributeEquals(array(), 'persistEntities', $this->entityPool); } public function testAddPersistAndFlushWithNoEntities() { $this->entityManager->expects($this->never())->method($this->anything()); $this->entityPool->persistAndFlush($this->entityManager); } public function testAddPersistAndFlush() { $this->entityPool->addPersistEntity($fooEntity = $this->createTestEntity()); $this->entityPool->addPersistEntity($barEntity = $this->createTestEntity()); $this->entityManager->expects($this->at(0)) ->method('persist') ->with($fooEntity); $this->entityManager->expects($this->at(1)) ->method('persist') ->with($barEntity); $this->entityManager->expects($this->at(2)) ->method('flush'); $this->entityPool->persistAndFlush($this->entityManager); $this->assertAttributeEquals(array(), 'persistEntities', $this->entityPool); } protected function createEntityManager() { return $this->getMock('TestEntity'); } protected function createTestEntity() { return $this->getMock('TestEntity'); } }
mit
Hwesta/python-client-sword2
tests/functional/test_connection.py
4154
from . import TestController from sword2 import Connection from sword2.compatible_libs import json long_service_doc = '''<?xml version="1.0" ?> <service xmlns:dcterms="http://purl.org/dc/terms/" xmlns:sword="http://purl.org/net/sword/terms/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns="http://www.w3.org/2007/app"> <sword:version>2.0</sword:version> <sword:maxUploadSize>16777216</sword:maxUploadSize> <workspace> <atom:title>Main Site</atom:title> <collection href="http://swordapp.org/col-iri/43"> <atom:title>Collection 43</atom:title> <accept>*/*</accept> <accept alternate="multipart-related">*/*</accept> <sword:collectionPolicy>Collection Policy</sword:collectionPolicy> <dcterms:abstract>Collection Description</dcterms:abstract> <sword:mediation>false</sword:mediation> <sword:treatment>Treatment description</sword:treatment> <sword:acceptPackaging>http://purl.org/net/sword/package/SimpleZip</sword:acceptPackaging> <sword:acceptPackaging>http://purl.org/net/sword/package/METSDSpaceSIP</sword:acceptPackaging> <sword:service>http://swordapp.org/sd-iri/e4</sword:service> </collection> </workspace> <workspace> <atom:title>Sub-site</atom:title> <collection href="http://swordapp.org/col-iri/44"> <atom:title>Collection 44</atom:title> <accept>*/*</accept> <accept alternate="multipart-related">*/*</accept> <sword:collectionPolicy>Collection Policy</sword:collectionPolicy> <dcterms:abstract>Collection Description</dcterms:abstract> <sword:mediation>true</sword:mediation> <sword:treatment>Treatment description</sword:treatment> <sword:acceptPackaging>http://purl.org/net/sword/package/SimpleZip</sword:acceptPackaging> <sword:service>http://swordapp.org/sd-iri/e5</sword:service> <sword:service>http://swordapp.org/sd-iri/e6</sword:service> <sword:service>http://swordapp.org/sd-iri/e7</sword:service> <sword:service>http://swordapp.org/sd-iri/e8</sword:service> </collection> <collection href="http://swordapp.org/col-iri/46"> <atom:title>Collection 46</atom:title> <accept>application/zip</accept> <accept alternate="multipart-related">application/zip</accept> <sword:collectionPolicy>Only Theses</sword:collectionPolicy> <dcterms:abstract>Theses dropbox</dcterms:abstract> <sword:mediation>true</sword:mediation> <sword:treatment>Treatment description</sword:treatment> <sword:acceptPackaging>http://purl.org/net/sword/package/SimpleZip</sword:acceptPackaging> </collection> </workspace> </service>''' class TestConnection(TestController): def test_01_blank_init(self): conn = Connection("http://example.org/service-doc") assert conn.sd_iri == "http://example.org/service-doc" assert conn.sd == None def test_02_init_then_load_from_string(self): conn = Connection("http://example.org/service-doc") assert conn.sd_iri == "http://example.org/service-doc" assert conn.sd == None conn.load_service_document(long_service_doc) assert conn.sd != None assert len(conn.sd.workspaces) == 2 assert len(conn.workspaces) == 2 assert conn.sd.workspaces[0][0] == "Main Site" assert conn.sd.workspaces[1][0] == "Sub-site" assert len(conn.sd.workspaces[1][1]) == 2 def test_03_init_then_load_from_string_t_history(self): conn = Connection("http://example.org/service-doc") assert conn.sd_iri == "http://example.org/service-doc" assert conn.sd == None conn.load_service_document(long_service_doc) # Should have made a two client 'transactions', the init and subsequent XML load assert len(conn.history) == 2 assert conn.history[0]['type'] == "init" assert conn.history[1]['type'] == "SD Parse"
mit
FansWorldTV/web
src/Kaltura/Client/Plugin/DropFolder/Type/FtpDropFolder.php
2127
<?php // =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2011 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== /** * @namespace */ namespace Kaltura\Client\Plugin\DropFolder\Type; /** * @package Kaltura * @subpackage Client */ class FtpDropFolder extends RemoteDropFolder { public function getKalturaObjectType() { return 'KalturaFtpDropFolder'; } public function __construct(\SimpleXMLElement $xml = null) { parent::__construct($xml); if(is_null($xml)) return; $this->host = (string)$xml->host; if(count($xml->port)) $this->port = (int)$xml->port; $this->username = (string)$xml->username; $this->password = (string)$xml->password; } /** * * @var string */ public $host = null; /** * * @var int */ public $port = null; /** * * @var string */ public $username = null; /** * * @var string */ public $password = null; }
mit
darrelljefferson/themcset.com
bin/test/g/p/n.php
37
<?php namespace test\g\p; class n { }
mit
arjenm/symfony
src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
8399
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Cache\Adapter; use Psr\Cache\CacheItemInterface; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerAwareTrait; use Symfony\Component\Cache\CacheItem; use Symfony\Component\Cache\ResettableInterface; use Symfony\Contracts\Cache\CacheInterface; /** * @author Nicolas Grekas <p@tchwork.com> */ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInterface, ResettableInterface { use LoggerAwareTrait; private $storeSerialized; private $values = []; private $expiries = []; private $createCacheItem; /** * @param bool $storeSerialized Disabling serialization can lead to cache corruptions when storing mutable values but increases performance otherwise */ public function __construct(int $defaultLifetime = 0, bool $storeSerialized = true) { $this->storeSerialized = $storeSerialized; $this->createCacheItem = \Closure::bind( function ($key, $value, $isHit) use ($defaultLifetime) { $item = new CacheItem(); $item->key = $key; $item->value = $value; $item->isHit = $isHit; $item->defaultLifetime = $defaultLifetime; return $item; }, null, CacheItem::class ); } /** * {@inheritdoc} */ public function get(string $key, callable $callback, float $beta = null, array &$metadata = null) { $item = $this->getItem($key); $metadata = $item->getMetadata(); // ArrayAdapter works in memory, we don't care about stampede protection if (INF === $beta || !$item->isHit()) { $save = true; $this->save($item->set($callback($item, $save))); } return $item->get(); } /** * {@inheritdoc} */ public function delete(string $key): bool { return $this->deleteItem($key); } /** * {@inheritdoc} */ public function hasItem($key) { if (\is_string($key) && isset($this->expiries[$key]) && $this->expiries[$key] > microtime(true)) { return true; } CacheItem::validateKey($key); return isset($this->expiries[$key]) && !$this->deleteItem($key); } /** * {@inheritdoc} */ public function getItem($key) { if (!$isHit = $this->hasItem($key)) { $this->values[$key] = $value = null; } else { $value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key]; } $f = $this->createCacheItem; return $f($key, $value, $isHit); } /** * {@inheritdoc} */ public function getItems(array $keys = []) { foreach ($keys as $key) { if (!\is_string($key) || !isset($this->expiries[$key])) { CacheItem::validateKey($key); } } return $this->generateItems($keys, microtime(true), $this->createCacheItem); } /** * {@inheritdoc} */ public function deleteItem($key) { if (!\is_string($key) || !isset($this->expiries[$key])) { CacheItem::validateKey($key); } unset($this->values[$key], $this->expiries[$key]); return true; } /** * {@inheritdoc} */ public function deleteItems(array $keys) { foreach ($keys as $key) { $this->deleteItem($key); } return true; } /** * {@inheritdoc} */ public function save(CacheItemInterface $item) { if (!$item instanceof CacheItem) { return false; } $item = (array) $item; $key = $item["\0*\0key"]; $value = $item["\0*\0value"]; $expiry = $item["\0*\0expiry"]; if (null !== $expiry && $expiry <= microtime(true)) { $this->deleteItem($key); return true; } if ($this->storeSerialized && null === $value = $this->freeze($value, $key)) { return false; } if (null === $expiry && 0 < $item["\0*\0defaultLifetime"]) { $expiry = microtime(true) + $item["\0*\0defaultLifetime"]; } $this->values[$key] = $value; $this->expiries[$key] = null !== $expiry ? $expiry : PHP_INT_MAX; return true; } /** * {@inheritdoc} */ public function saveDeferred(CacheItemInterface $item) { return $this->save($item); } /** * {@inheritdoc} */ public function commit() { return true; } /** * {@inheritdoc} */ public function clear(string $prefix = '') { if ('' !== $prefix) { foreach ($this->values as $key => $value) { if (0 === strpos($key, $prefix)) { unset($this->values[$key], $this->expiries[$key]); } } } else { $this->values = $this->expiries = []; } return true; } /** * Returns all cached values, with cache miss as null. * * @return array */ public function getValues() { if (!$this->storeSerialized) { return $this->values; } $values = $this->values; foreach ($values as $k => $v) { if (null === $v || 'N;' === $v) { continue; } if (!\is_string($v) || !isset($v[2]) || ':' !== $v[1]) { $values[$k] = serialize($v); } } return $values; } /** * {@inheritdoc} */ public function reset() { $this->clear(); } private function generateItems(array $keys, $now, $f) { foreach ($keys as $i => $key) { if (!$isHit = isset($this->expiries[$key]) && ($this->expiries[$key] > $now || !$this->deleteItem($key))) { $this->values[$key] = $value = null; } else { $value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key]; } unset($keys[$i]); yield $key => $f($key, $value, $isHit); } foreach ($keys as $key) { yield $key => $f($key, null, false); } } private function freeze($value, $key) { if (null === $value) { return 'N;'; } if (\is_string($value)) { // Serialize strings if they could be confused with serialized objects or arrays if ('N;' === $value || (isset($value[2]) && ':' === $value[1])) { return serialize($value); } } elseif (!is_scalar($value)) { try { $serialized = serialize($value); } catch (\Exception $e) { $type = \is_object($value) ? \get_class($value) : \gettype($value); $message = sprintf('Failed to save key "{key}" of type %s: %s', $type, $e->getMessage()); CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e]); return; } // Keep value serialized if it contains any objects or any internal references if ('C' === $serialized[0] || 'O' === $serialized[0] || preg_match('/;[OCRr]:[1-9]/', $serialized)) { return $serialized; } } return $value; } private function unfreeze(string $key, bool &$isHit) { if ('N;' === $value = $this->values[$key]) { return null; } if (\is_string($value) && isset($value[2]) && ':' === $value[1]) { try { $value = unserialize($value); } catch (\Exception $e) { CacheItem::log($this->logger, 'Failed to unserialize key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e]); $value = false; } if (false === $value) { $this->values[$key] = $value = null; $isHit = false; } } return $value; } }
mit
tanbo800/asta4js
src/form-option.js
6771
"use strict"; var util = require("./util"); var arrayUtil=require("./arrayUtil"); var config = require("./config"); var constant = require("./constant") var Snippet = require("./snippet") var metaApi = require("./meta") var $ = config.$; var getOptionBindingHub=function(bindContext, identifier){ var info = bindContext._getResource("optionBindingHub", identifier); if(!info){ info = {}; bindContext._addResource("optionBindingHub", identifier, info); } return info; } var throwMalformedOptionMeta=function(meta){ throw "There must be one property or a pair of _duplicator/_item (_item is ignorable) to be declared for option binding, but got:" + JSON.stringify(meta); } var retrieveTargetPropMetaRoot=function(meta){ var checkKeys = Object.keys(meta); if (checkKeys.length == 0) { return meta; }else if(checkKeys.length == 1){ if(checkKeys[0] === "_duplicator"){ return meta; }else if(checkKeys[0] === "_item"){ return meta; }else{ return retrieveTargetPropMetaRoot(meta[checkKeys[0]]); } }else if(checkKeys.length == 2){ if(checkKeys.indexOf("_duplicator") && checkKeys.indexOf("_item")){ return meta; }else{ throwMalformedOptionMeta(meta); } }else{ throwMalformedOptionMeta(meta); } } var defaultValueFn=function (v){ if(v === undefined){ return undefined; }else if(v.value === undefined){ return v; }else{ return v.value; } } var defaultTextFn=function(v){ if(v === undefined){ return undefined; }else if(v.text === undefined){ return v; }else{ return v.text; } }; /* * */ var rewriteOptionMeta=function(optionMeta, inputType){ var newMeta = util.clone(optionMeta); var targetPropMetaRoot = retrieveTargetPropMetaRoot(newMeta); if(!targetPropMetaRoot._item){ targetPropMetaRoot._item = {}; } targetPropMetaRoot._value = function(newValue, oldValue, bindContext){ var fn = bindContext._optionBindingHub.notifyOptionChanged; if(fn){ //delay it 3 delay cycle to make sure all the necessary change handlers related to option has finished. util.delay(fn, 0, 3); } } //TODO we should handle splice but not now /* targetPropMetaRoot._splice = function(newValue, oldValue, bindContext){ var fn = bindContext.optionBindingHub.notifyOptionChange(); if(fn){ fn.apply(); } } */ var itemDef = targetPropMetaRoot._item; var valueFn = itemDef._value ? itemDef._value : defaultValueFn; delete itemDef._value; var textFn = itemDef._text ? itemDef._text : defaultTextFn; delete itemDef._text; if(inputType === "select"){ if(!targetPropMetaRoot._duplicator){ targetPropMetaRoot._duplicator = "option:not([aj-diverge-value]):first"; } if(!itemDef._selector){ itemDef._selector = ":root"; } if (!itemDef._render) { itemDef._render = function (target, newValue, oldValue, bindContext) { target.val(valueFn(newValue)); target.text(textFn(newValue)); }; } }else if (inputType === "checkbox" || inputType === "radio"){ if(!targetPropMetaRoot._duplicator){ throw "_duplicator must be specified for options of checkbox or radio:" + JSON.stringify(targetPropMetaRoot); } if(!itemDef._selector){ itemDef._selector = ":root"; } if(itemDef._register_dom_change || itemDef._register_assign || itemDef._assign){ throw "_register_dom_change/_register_assign/_assign cannot be specified for checkbox/radio option"; }else{ itemDef._register_dom_change = function (target, changeHandler, bindContext){ var optionContext = bindContext._parentContext; var optionBindingHub = optionContext._optionBindingHub; var changeEvents = optionBindingHub.changeEvents; var events = optionBindingHub.changeEvents.join(" "); target.find("input").bind(events, function () { var je = $(this); var value = je.val(); var checked = je.prop("checked"); changeHandler({ "value": value, "checked": checked }, bindContext); }); //if there is click being bound to input, we do not need to bind any event on label //because the click handle will be invoked automatically when the label is clicked. if(changeEvents.indexOf("click") < 0){ target.find("label").bind(events, function(){ var je= $(this); var id = je.attr("for"); var input = target.find("#" + id); var value = input.val(); //label click may before checkbox "being clicked" var checked = !input.prop("checked"); changeHandler({ "value": value, "checked": checked }, bindContext); }); } /* */ } itemDef._assign = function (changedValue, bindContext) { var optionContext = bindContext._parentContext; var optionBindingHub = optionContext._optionBindingHub; var targetValueRef = optionBindingHub.targetValueRef; var inputType = optionBindingHub.inputType; var value = changedValue.value; var checked = changedValue.checked; if(inputType === "checkbox"){ var newResult = arrayUtil.regulateArray(targetValueRef.getValue()); var vidx = newResult.indexOf(value); if(checked && vidx>= 0){ //it is ok }else if(checked && vidx < 0){ //add newResult.push(value); }else if(!checked && vidx >= 0){ //remove newResult.splice(vidx, 1); }else{// !checked && vidx < 0 //it is ok } targetValueRef.setValue(newResult); }else{ targetValueRef.setValue(value); } } //_assign } // else of (itemDef._register_dom_change || itemDef._assign) if (!itemDef._render) { itemDef._render = function (target, newValue, oldValue, bindContext) { var optionContext = bindContext._parentContext; var optionBindingHub = optionContext._optionBindingHub; var snippet = bindContext._snippet; var uid = util.createUID(); snippet.find(":root").attr("aj-option-binding", optionBindingHub.optionId); snippet.find("input[type="+optionBindingHub.inputType+"]").attr("id", uid).val(valueFn(newValue));; snippet.find("label").attr("for", uid).text(textFn(newValue)); }; } }//end checkbox or radio return metaApi.normalizeMeta(newMeta); }//end optionRewrite module.exports={ rewriteOptionMeta : rewriteOptionMeta, getOptionBindingHub : getOptionBindingHub }
mit
fireyy/react-antd-admin
mocha-compiler.js
151
function noop() { return null; } require.extensions['.css'] = noop; require.extensions['.less'] = noop; require.extensions['.png'] = noop; // ..etc
mit
GroestlCoin/GroestlCoin-obsolete
src/alert.cpp
7491
// // Alert system // #include <algorithm> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/foreach.hpp> #include <map> #include "alert.h" #include "key.h" #include "net.h" #include "sync.h" #include "ui_interface.h" using namespace std; map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; static const char* pszMainKey = "04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"; static const char* pszTestKey = "04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"; void CUnsignedAlert::SetNull() { nVersion = 1; nRelayUntil = 0; nExpiration = 0; nID = 0; nCancel = 0; setCancel.clear(); nMinVer = 0; nMaxVer = 0; setSubVer.clear(); nPriority = 0; strComment.clear(); strStatusBar.clear(); strReserved.clear(); } std::string CUnsignedAlert::ToString() const { std::string strSetCancel; BOOST_FOREACH(int n, setCancel) strSetCancel += strprintf("%d ", n); std::string strSetSubVer; BOOST_FOREACH(std::string str, setSubVer) strSetSubVer += "\"" + str + "\" "; return strprintf( "CAlert(\n" " nVersion = %d\n" " nRelayUntil = %"PRI64d"\n" " nExpiration = %"PRI64d"\n" " nID = %d\n" " nCancel = %d\n" " setCancel = %s\n" " nMinVer = %d\n" " nMaxVer = %d\n" " setSubVer = %s\n" " nPriority = %d\n" " strComment = \"%s\"\n" " strStatusBar = \"%s\"\n" ")\n", nVersion, nRelayUntil, nExpiration, nID, nCancel, strSetCancel.c_str(), nMinVer, nMaxVer, strSetSubVer.c_str(), nPriority, strComment.c_str(), strStatusBar.c_str()); } void CUnsignedAlert::print() const { printf("%s", ToString().c_str()); } void CAlert::SetNull() { CUnsignedAlert::SetNull(); vchMsg.clear(); vchSig.clear(); } bool CAlert::IsNull() const { return (nExpiration == 0); } uint256 CAlert::GetHash() const { return HashGroestl(this->vchMsg.begin(), this->vchMsg.end()); } bool CAlert::IsInEffect() const { return (GetAdjustedTime() < nExpiration); } bool CAlert::Cancels(const CAlert& alert) const { if (!IsInEffect()) return false; // this was a no-op before 31403 return (alert.nID <= nCancel || setCancel.count(alert.nID)); } bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const { // TODO: rework for client-version-embedded-in-strSubVer ? return (IsInEffect() && nMinVer <= nVersion && nVersion <= nMaxVer && (setSubVer.empty() || setSubVer.count(strSubVerIn))); } bool CAlert::AppliesToMe() const { return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>())); } bool CAlert::RelayTo(CNode* pnode) const { if (!IsInEffect()) return false; // returns true if wasn't already contained in the set if (pnode->setKnown.insert(GetHash()).second) { if (AppliesTo(pnode->nVersion, pnode->strSubVer) || AppliesToMe() || GetAdjustedTime() < nRelayUntil) { pnode->PushMessage("alert", *this); return true; } } return false; } bool CAlert::CheckSignature() const { CKey key; if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey))) return error("CAlert::CheckSignature() : SetPubKey failed"); if (!key.Verify(HashGroestl(vchMsg.begin(), vchMsg.end()), vchSig)) return error("CAlert::CheckSignature() : verify signature failed"); // Now unserialize the data CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION); sMsg >> *(CUnsignedAlert*)this; return true; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert(bool fThread) { if (!CheckSignature()) return false; if (!IsInEffect()) return false; // alert.nID=max is reserved for if the alert key is // compromised. It must have a pre-defined message, // must never expire, must apply to all versions, // and must cancel all previous // alerts or it will be ignored (so an attacker can't // send an "everything is OK, don't panic" version that // cannot be overridden): int maxInt = std::numeric_limits<int>::max(); if (nID == maxInt) { if (!( nExpiration == maxInt && nCancel == (maxInt-1) && nMinVer == 0 && nMaxVer == maxInt && setSubVer.empty() && nPriority == maxInt && strStatusBar == "URGENT: Alert key compromised, upgrade required" )) return false; } { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI and -alertnotify if it applies to me if(AppliesToMe()) { uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); std::string strCmd = GetArg("-alertnotify", ""); if (!strCmd.empty()) { // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strStatusBar); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); if (fThread) boost::thread t(runCommand, strCmd); // thread runs free else runCommand(strCmd); } } } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; }
mit