text
stringlengths
27
775k
package csw.services.internal class Environment(settings: Settings) { def setup(): Unit = { import settings._ System.setProperty("CLUSTER_SEEDS", s"$hostName:$clusterPort") System.setProperty("csw-location-server.http-port", locationHttpPort) System.setProperty("INTERFACE_NAME", insideInterfaceName) System.setProperty("AAS_INTERFACE_NAME", outsideInterfaceName) System.setProperty("TMT_LOG_HOME", logHome) } }
#!/usr/bin/env kotlin println((1..999).filter { it % 3 == 0 || it % 5 == 0}.sum())
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Handle.hpp> #include <RED4ext/NativeTypes.hpp> #include <RED4ext/Scripting/Natives/Generated/Vector3.hpp> #include <RED4ext/Scripting/Natives/Generated/game/EntityReference.hpp> #include <RED4ext/Scripting/Natives/Generated/game/JournalEntry.hpp> #include <RED4ext/Scripting/Natives/Generated/game/mappins/PointOfInterestMappinData.hpp> namespace RED4ext { namespace game { struct JournalPath; } namespace game { struct JournalPointOfInterestMappin : game::JournalEntry { static constexpr const char* NAME = "gameJournalPointOfInterestMappin"; static constexpr const char* ALIAS = "JournalPointOfInterestMappin"; NodeRef staticNodeRef; // 60 game::EntityReference dynamicEntityRef; // 68 NodeRef securityAreaRef; // A0 game::mappins::PointOfInterestMappinData mappinData; // A8 Vector3 offset; // C8 uint8_t unkD4[0xD8 - 0xD4]; // D4 Handle<game::JournalPath> questPath; // D8 TweakDBID recommendedLevelID; // E8 NodeRef notificationTriggerAreaRef; // F0 }; RED4EXT_ASSERT_SIZE(JournalPointOfInterestMappin, 0xF8); } // namespace game using JournalPointOfInterestMappin = game::JournalPointOfInterestMappin; } // namespace RED4ext
unit ce_dastworx; {$I ce_defines.inc} interface uses Classes, SysUtils, process, ce_common; (** * Gets the module name and the imports of the source code located in * "source". The first line of "import" contains the module name, double quoted. * Each following line contain an import. *) procedure getModuleImports(source, imports: TStrings); (** * Gets the module names and the imports of the sources in "files". * source. Each line in "import" that contains double quoted text indicates * that a new group of import starts. *) procedure getModulesImports(const files: string; results: TStrings); implementation var toolname: string; function getToolName: string; begin if toolname = '' then toolname := exeFullName('dastworx' + exeExt); exit(toolname); end; procedure getModuleImports(source, imports: TStrings); var str: string; prc: TProcess; begin str := getToolName; if str.isEmpty then exit; prc := TProcess.Create(nil); try prc.Executable := str; prc.Parameters.Add('-i'); prc.Options := [poUsePipes{$IFDEF WINDOWS}, poNewConsole{$ENDIF}]; prc.ShowWindow := swoHIDE; prc.Execute; str := source.Text; prc.Input.Write(str[1], str.length); prc.CloseInput; processOutputToStrings(prc, imports); while prc.Running do ; finally prc.free; end; end; procedure getModulesImports(const files: string; results: TStrings); var str: string; prc: TProcess; begin str := getToolName; if str.isEmpty then exit; prc := TProcess.Create(nil); try prc.Executable := str; prc.Parameters.Add(files); prc.Parameters.Add('-i'); prc.Options := [poUsePipes {$IFDEF WINDOWS}, poNewConsole{$ENDIF}]; prc.ShowWindow := swoHIDE; prc.Execute; prc.CloseInput; processOutputToStrings(prc, results); while prc.Running do ; finally prc.free; end; end; end.
# Ordered Floats Provides several wrapper types for Ord and Eq implementations on f64. See `src/lib.rs` for documentation and details. ## License MIT ## Tools Built using Cargo Tested using Stainless
# AutocompletionSystem Building a naive recommendation system on AWS using amazon ec2 and Elastic Cache's Redis Database.
using System; using System.Numerics; public class Catch_the_Thief { public static void Main() { var numeralType = Console.ReadLine(); var countOfIds = int.Parse(Console.ReadLine()); BigInteger thiefsId = 0; BigInteger minPositiveDifference = ulong.MaxValue; for (int i = 0; i < countOfIds; i++) { BigInteger id = BigInteger.Parse(Console.ReadLine()); BigInteger differenceToMaxTypeValue; if (numeralType == "sbyte") { differenceToMaxTypeValue = sbyte.MaxValue - id; if (differenceToMaxTypeValue <= minPositiveDifference && differenceToMaxTypeValue >= 0) { minPositiveDifference = differenceToMaxTypeValue; thiefsId = id; } } else if (numeralType == "int") { differenceToMaxTypeValue = int.MaxValue - id; if (differenceToMaxTypeValue <= minPositiveDifference && differenceToMaxTypeValue >= 0) { minPositiveDifference = differenceToMaxTypeValue; thiefsId = id; } } else if (numeralType == "long") { differenceToMaxTypeValue = long.MaxValue - id; if (differenceToMaxTypeValue <= minPositiveDifference && differenceToMaxTypeValue >= 0) { minPositiveDifference = differenceToMaxTypeValue; thiefsId = id; } } } Console.WriteLine(thiefsId); } }
<?php namespace Enhavo\Bundle\AppBundle\Action\Type; use Enhavo\Bundle\AppBundle\Action\AbstractUrlActionType; use Enhavo\Bundle\AppBundle\Action\ActionTypeInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Routing\RouterInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Class ExportModalActionType * @package SummitDatabaseBundle\Action */ class OpenActionType extends AbstractUrlActionType implements ActionTypeInterface { /** * @param array $options * @param null $resource * @return array|string */ public function createViewData(array $options, $resource = null) { $data = parent::createViewData($options, $resource); $data = array_merge($data, [ 'target' => $options['target'], 'key' => $options['view_key'] ]); return $data; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { parent::configureOptions($resolver); $resolver->setDefaults([ 'component' => 'open-action', 'label' => 'label.open', 'icon' => 'arrow_forward', 'target' => '_self', 'view_key' => null ]); } /** * @return string */ public function getType() { return 'open'; } }
<?php class Service_Adresse { /** * Récupération de l'ensemble des communes * * @return array */ public function getAllCommunes() { $model_commune = new Model_DbTable_AdresseCommune; return $model_commune->fetchAll()->toArray(); } /** * Récupération des communes via le nom ou le code postal * * @param string $q Code postal ou nom d'une commune * @return array */ public function get($q) { if(strlen($q) == 5 && is_numeric($q)) { $DB_adresse = new Model_DbTable_EtablissementAdresse; return $DB_adresse->getVilleByCP($q); } $model_adresse = new Model_DbTable_AdresseCommune; return $model_adresse->get($q); } /** * Retourne les types de voie d'une commune identifiée par son code insee * * @param int $code_insee * @return array */ public function getTypesVoieParVille($code_insee) { $DB_adresse = new Model_DbTable_EtablissementAdresse; return $DB_adresse->getTypesVoieByVille($code_insee); } /** * Retourne les voies par rapport à une ville * * @param int $code_insee * @param string $q * @return array */ public function getVoies($code_insee, $q = '') { $DB_adresse = new Model_DbTable_EtablissementAdresse; return $DB_adresse->getVoies($code_insee, $q); } /** * Retourne le maire de la commune concernée * * @param int $numinsee le numéro insee de la commune * @return array les informations de la fiche contact du maire */ public function getMaire($numinsee) { $select = new Zend_Db_Select(Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('db')); $select->from("adressecommune") ->join("utilisateurinformations", "utilisateurinformations.ID_UTILISATEURINFORMATIONS = adressecommune.ID_UTILISATEURINFORMATIONS") ->where("adressecommune.NUMINSEE_COMMUNE = ?", $numinsee) ->limit(1); return $select->query()->fetch(); } }
#ifndef EMPLOY_SCOREBOARD_H #define EMPLOY_SCOREBOARD_H #include <employees.h> #include <json.hpp> class EmployScoreboard : public WsjcppEmployBase { public: EmployScoreboard(); static std::string name() { return "EmployScoreboard"; } virtual bool init(); virtual bool deinit() override; void loadSync(); int count(); nlohmann::json toJson(); void asyncUpdatedQuestScore(int nQuestID); void asyncUpdatedUserRating(int nUserID); void asyncUpdatedLeaksScore(int nUserID); private: struct User{ int userid = 0; std::string logo = ""; std::string nick = ""; std::string university = ""; }; struct ScoreboardRow { int place = 0; int rating = 0; std::vector<User *> vUsers; }; std::vector<ScoreboardRow *> m_vRows; int findScoreboardRowByRating(int rating); }; #endif // EMPLOY_SCOREBOARD_H
#! /bin/bash which protoc if [ $? != 0 ]; then echo "Protocol buffer installation not found" exit 1 fi which protoc-gen-go if [ $? != 0 ]; then echo "Installing go extension for protocol buffers" go get -u github.com/golang/protobuf/protoc-gen-go fi
/* * Copyright 2017 Chris Nappin * * 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. */ package com.nappin.play.recaptcha import com.typesafe.config.ConfigException import play.api.{Configuration, Logger} import javax.inject.{Inject, Singleton} /** * Module configuration. * * @author chrisnappin, gmalouf */ @Singleton class RecaptchaSettings @Inject() (configuration: Configuration) { import RecaptchaSettings._ private val logger = Logger(this.getClass()) /** The application's recaptcha private key. */ val privateKey: String = configuration.get[String](PrivateKeyConfigProp) /** The application's recaptcha public key. */ val publicKey: String = configuration.get[String](PublicKeyConfigProp) /** The millisecond request timeout duration, when connecting to the recaptcha web API. */ val requestTimeoutMs: Long = configuration.getOptional[String](RequestTimeoutConfigProp) match { case Some(_) => configuration.getMillis(RequestTimeoutConfigProp) case None => RequestTimeoutMsDefault.toMillis } /** The theme for the recaptcha widget to use (if any). */ val theme: Option[String] = configuration.getOptional[String](ThemeConfigProp) /** The captcha type to use (if any). */ val captchaType: String = configuration.getOptional[String](CaptchaTypeConfigProp) match { case Some(_) => configuration.getAndValidate[String](CaptchaTypeConfigProp, values = Set("image", "audio")) case None => CaptchaTypeDefault } /** The captcha size to use (if any). */ val captchaSize: String = configuration.getOptional[String](CaptchaSizeConfigProp) match { case Some(_) => configuration.getAndValidate[String](CaptchaSizeConfigProp, values = Set("normal", "compact")) case None => CaptchaSizeDefault } /** The captcha language mode to use (if any). */ val languageMode: String = configuration.getOptional[String](LanguageModeConfigProp) match { case Some(_) => configuration.getAndValidate[String](LanguageModeConfigProp, values = Set("auto", "play", "force")) case None => LanguageModeDefault } /** The language to force use of (if any). */ val forceLanguage: Option[String] = configuration.getOptional[String](ForceLanguageConfigProp) /** The content security policy to use (if any). */ val contentSecurityPolicy: String = configuration.getOptional[String](ContentSecurityPolicyProp) .getOrElse(ContentSecurityPolicyDefault) /** The length of nonces to generate (if any). */ val nonceLength: Int = configuration.getOptional[Int](NonceLengthProp).getOrElse(NonceLengthDefault) /** The seed to use for nonce generation (if any). */ val nonceSeed: Option[Long] = configuration.getOptional[Long](NonceSeedProp) /** Sanity check the configuration, log descriptive error if invalid. */ checkMandatoryConfigurationPresent(configuration) checkConfigurationValid(configuration) /** * Get the URL (secure or insecure) for the verify API. * * @return The URL */ def verifyUrl: String = "https://www.google.com/recaptcha/api/siteverify" /** * Get the URL (secure or insecure if v1, always secure if v2) for the widget (script). * * @return The URL */ def widgetScriptUrl: String = "https://www.google.com/recaptcha/api.js" /** * Get the URL (secure or insecure if v1, always secure if v2) for the widget (no script). * * @return The URL */ def widgetNoScriptUrl: String = "https://www.google.com/recaptcha/api/fallback" /** * Check whether the mandatory configuration is present. If not a suitable error log * message will be written. * @param configuration The configuration to check */ private def checkMandatoryConfigurationPresent(configuration: Configuration): Unit = { var mandatoryConfigurationPresent = true // keep looping so all missing items get logged, not just the first one... mandatoryConfiguration.foreach(key => { if (!configuration.keys.contains(key)) { logger.error(key + " not found in application configuration") mandatoryConfigurationPresent = false } }) if (!mandatoryConfigurationPresent) { logger.error("Mandatory configuration missing. Please check the module " + "documentation and add the missing items to your application.conf file.") } } /** * Check whether the configuration is valid. If not a suitable error log message will * be written. * @param configuration The configuration to check * @throws ConfigException.Missing If configuration is invalid */ private def checkConfigurationValid(configuration: Configuration): Unit = { // if languageMode is set to "force" then "forceLanguage" must be defined if (languageMode == "force" && forceLanguage.isEmpty) { logger.error("If languageMode is \"force\" then forceLanguage must be defined") throw new ConfigException.Missing(LanguageModeConfigProp) } } } object RecaptchaSettings { private val root = "recaptcha" /** The application's recaptcha private key. */ val PrivateKeyConfigProp = s"$root.privateKey" /** The application's recaptcha public key. */ val PublicKeyConfigProp = s"$root.publicKey" /** The millisecond request timeout duration, when connecting to the recaptcha web API. */ val RequestTimeoutConfigProp = s"$root.requestTimeout" /** The theme for the recaptcha widget to use (if any). */ val ThemeConfigProp = s"$root.theme" /** The captcha type to use (if any). */ val CaptchaTypeConfigProp = s"$root.type" /** The captcha size to use (if any). */ val CaptchaSizeConfigProp = s"$root.size" /** The language mode to use (if any). */ val LanguageModeConfigProp = s"$root.languageMode" /** The forced language value to use (if any). */ val ForceLanguageConfigProp = s"$root.forceLanguage" /** The Content Security Policy to use (if any). */ val ContentSecurityPolicyProp = s"$root.nonceAction.contentSecurityPolicy" /** The length of the nonces to generate (if any). */ val NonceLengthProp = s"$root.nonceAction.nonceLength" /** The nonce generation seed (if any). */ val NonceSeedProp = s"$root.nonceAction.nonceSeed" // Default Values import scala.concurrent.duration._ val RequestTimeoutMsDefault = 10.seconds val DefaultLanguageDefault = "en" val CaptchaTypeDefault = "image" val CaptchaSizeDefault = "normal" val LanguageModeDefault = "auto" val ContentSecurityPolicyDefault = "default-src 'self'; script-src 'self' 'nonce-{nonce}'; " + "style-src 'self' 'unsafe-inline'; frame-src https://www.google.com/recaptcha/;" val NonceLengthDefault = 20 /** The mandatory configuration items that must exist for this module to work. */ private[recaptcha] val mandatoryConfiguration = Seq(PrivateKeyConfigProp, PublicKeyConfigProp) }
<?php namespace App\Http\Requests\Backend\Auth; use App\Http\Requests\BaseRequest; class RuleRequest extends BaseRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * 表单验证. * * @return array */ public function rules() { return [ /* 'cms_auth_rule_type' => 'required', 'cms_auth_rule_pid' => 'required|integer', 'cms_auth_rule_name' => 'required|max:100', 'cms_auth_rule_title' => 'required|max:50', 'cms_auth_rule_icon' => 'required|max:50', 'cms_auth_rule_condition' => 'required|max:255', 'cms_auth_rule_remark' => 'required', 'cms_auth_rule_ismenu' => 'required|integer', 'cms_auth_rule_weigh' => 'required|integer', 'cms_auth_rule_status' => 'required|max:30', 'deleted_at' => '|integer',*/ ]; } }
use Test::More tests => 17; BEGIN { use_ok('P4'); } ## test 1 # Load test utils unshift( @INC, "." ); unshift( @INC, "t" ); require_ok("p4test"); ## test 2 my $test = new P4::Test; my $p4 = $test->InitClient(); ok( defined($p4) ); ## test 3 ok( $p4->Connect() ); ## test 4 ## Read value from returned spec my $i = $p4->IterateChanges("-m4"); my $spec = $i->next; ok( $spec->{Change} == 8 ); ## test 5 ## Read all remaining specs (changes 9,10,11) $c = 0; while ( $i->hasNext ) { my $spec = $i->next; $c++; } ok( $c == 3 ); ## test 6 ## Test iterate when empty my $null = $i->next; ok( !defined $null ); ## test 7 my @specs = ( 'clients', 'labels', 'branches', 'changes', 'streams', 'jobs', 'users', 'groups', 'depots', 'servers' ); foreach my $s (@specs) { my $i = $p4->Iterate($s); ok( defined($i) ); ## test 8-17 }
# frozen_string_literal: true CommandDispatcher.register name: 'image', help_text: 'displays information about a specific image' do |msg, args| msg.reply '_no such image!_' unless Image.send_image(msg, args.raw) end CommandDispatcher.alias 'i', 'image' CommandDispatcher.alias 'img', 'image'
import numpy as np import os import datetime import cv2 import torch import glob import time import shutil import gym from utils import utils from tqdm import tqdm from scipy.stats import multivariate_normal from tensorboardX import SummaryWriter from shutil import copyfile from scipy import signal from methods import TD3Polar from mujoco_py import GlfwContext # train the actor to fit the data class Solver(object): def __init__(self, args, env, project_path): print(args) self.args = args self.env = env self.file_name = '' self.project_path = project_path self.result_path = project_path + "results" self.evaluations = [] self.estimate_Q_vals = [] self.Q1_vec = [] self.Q2_vec = [] self.true_Q_vals = [] self.Q_ae_mean_vec = [] self.Q_ae_std_vec = [] self.env.seed(args.seed) torch.manual_seed(args.seed) np.random.seed(args.seed) state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] max_action = float(env.action_space.high[0]) # Initialize policy if 'TD3Polar' == args.policy_name: policy = TD3Polar.TD3Polar(1, action_dim, max_action, lr = args.lr) elif 'TD3Sigmoid' == args.policy_name: policy = TD3Sigmoid.TD3Sigmoid(state_dim, action_dim, max_action, lr=args.lr) else: policy = TD3.TD3(state_dim, action_dim, max_action, lr = args.lr) self.policy = policy self.policy_name = self.policy.__class__.__name__ print('-------Current policy: {} --------------'.format(self.policy_name)) # self.replay_buffer = utils.ReplayBuffer(max_size=1e4) self.replay_buffer = utils.ReplayBufferMat(max_size=args.max_time_steps) self.total_time_steps = 0 self.episode_timesteps = 0 self.pre_num_steps = self.total_time_steps self.time_steps_since_eval = 0 self.time_steps_calc_Q_vale = 0 self.best_reward = -1e4 self.env_timeStep = 5 def train_once(self): if self.total_time_steps > self.args.eval_freq: self.policy.train(self.replay_buffer, self.args.batch_size, self.args.discount, self.args.tau, self.args.policy_noise, self.args.noise_clip, self.args.policy_freq) def eval_once(self): self.pbar.update(self.total_time_steps - self.pre_num_steps) self.pre_num_steps = self.total_time_steps # Evaluate episode if self.time_steps_since_eval >= self.args.eval_freq: self.time_steps_since_eval %= self.args.eval_freq avg_reward = evaluate_policy(self.env, self.policy, self.args) self.evaluations.append(avg_reward) self.writer_test.add_scalar('ave_reward', avg_reward, self.total_time_steps) if self.args.save_all_policy: self.policy.save( self.file_name + str(int(int(self.total_time_steps / self.args.eval_freq) * self.args.eval_freq)), directory=self.log_dir) np.save(self.log_dir + "/test_accuracy", self.evaluations) utils.write_table(self.log_dir + "/test_accuracy", np.asarray(self.evaluations)) if self.best_reward < avg_reward: self.best_reward = avg_reward # print("-------------------Best reward!----------------------") self.policy.save(self.file_name, directory=self.log_dir) print("Best reward! Total T: %d Reward: %f" % (self.total_time_steps, avg_reward)) # self.policy.save(self.file_name, directory=self.log_dir) # print("Total T: %d Reward: %f" % # (self.total_time_steps, avg_reward)) def reset(self): # Reset environment self.obs = self.env.reset() self.obs_vec = np.dot(np.ones((self.args.seq_len, 1)), self.obs.reshape((1, -1))) self.episode_timesteps = 0 self.still_steps = 0 def step_episode(self, action): # Perform action ave_reward = 0 done = False while not done: new_obs, reward, done, _ = self.env.step(action) ave_reward += reward self.episode_timesteps += 1 self.total_time_steps += 1 self.time_steps_since_eval += 1 self.time_steps_calc_Q_vale += 1 return new_obs, ave_reward, done, {} def step_k_steps(self, action, k = 1): ave_reward = 0 finish = False # while not finish: for _ in range(k): new_obs, reward, done, _ = self.env.step(action) ave_reward += reward self.episode_timesteps += 1 self.total_time_steps += 1 self.time_steps_since_eval += 1 self.time_steps_calc_Q_vale += 1 # finish = done or 0 == self.env.control_time if done: break # print('0 == new_obs[-1]: ', 0 == new_obs[-1]) return new_obs, ave_reward, done, {} def pre_train(self): data = np.load('../data/im_motion/walk_dataset.npy', allow_pickle=True).item() states = data['state'] actions = data['action'] train_loader, valid_loader, test_loader, states_test, actions_test = \ utils.generate_dataset(states, actions, self.args.batch_size, shuffle=True) print('Length of training set: {}, validation set: {}, and test set: {}'.format( len(train_loader.dataset), len(valid_loader.dataset), len(test_loader.dataset))) pre_loss = 1.0 for t in range(100): train_loss, valid_loss = self.policy.train_expert(train_loader, valid_loader) if valid_loss < pre_loss: print('Training loss: {}, valid loss: {}'.format(train_loss, valid_loss)) pre_loss = valid_loss self.policy.save(self.file_name, directory=self.log_dir) self.policy.load(self.file_name, directory=self.log_dir) self.policy.transfer_expert() print('Finish pre-training.') def save_sample(self, sample_num = int(1e3)): self.log_dir = '{}/{}/reward_samples'.format(self.result_path, self.args.log_path) print("---------------------------------------") print("Settings: %s" % self.log_dir) print("---------------------------------------") if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) action_num = self.env.action_space.shape[0] self.pbar = tqdm(total=sample_num * action_num, initial=0, position=0, leave=True) sample_buffer = np.zeros((sample_num * action_num, action_num + 1)) for r in range(sample_num): for c in range(action_num): self.pbar.update(1) self.env.reset() action = 0.5 * np.ones(action_num) action[c] = np.random.uniform(0, 1) # action = self.env.action_space.sample() new_obs, reward, done, _ = self.step_episode(action) idx = r * action_num + c sample_buffer[idx, :-1] = action sample_buffer[idx, -1] = reward if 0 == idx % 20: np.save(self.log_dir + "/reward_samples.npy", sample_buffer) def train(self): # Evaluate untrained policy self.evaluations = [evaluate_policy(self.env, self.policy, self.args)] self.log_dir = '{}/{}/{}_{}_seed_{}'.format(self.result_path, self.args.log_path, self.args.policy_name, self.args.env_name, self.args.seed) print("---------------------------------------") print("Settings: %s" % self.log_dir) print("---------------------------------------") if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) # copy solver, TD3, and DAC to the log_dir copyfile('methods/{}.py'.format(self.policy_name), '{}/{}.py'.format(self.log_dir, self.policy_name)) copyfile('utils/solver_im.py', '{}/solver_im.py'.format(self.log_dir)) copyfile('utils/utils.py', '{}/utils.py'.format(self.log_dir)) copyfile('envs/cheetah_mujoco.py', '{}/cheetah_mujoco.py'.format(self.log_dir)) copyfile('main_im.py', '{}/main_im.py'.format(self.log_dir)) # TesnorboardX self.writer_test = SummaryWriter(logdir=self.log_dir) self.pbar = tqdm(total=self.args.max_time_steps, initial=self.total_time_steps, position=0, leave=True) done = True if 'IM' in self.args.policy_name and 'End' not in self.args.policy_name: self.pre_train() # train_expert while self.total_time_steps < self.args.max_time_steps: # ================ Train =============================================# self.train_once() # ====================================================================# if done: self.eval_once() self.reset() # Select action randomly or according to policy if self.total_time_steps < self.args.start_time_steps: # print(self.env.action_space.low, self.env.action_space.high) action = self.env.action_space.sample() else: if 'Polar' in self.args.policy_name: action = self.policy.select_action(np.asarray([self.obs[0]])) else: action = self.policy.select_action(np.array(self.obs)) # if np.random.uniform(0, 1) < self.args.expl_noise: # action = self.env.action_space.sample() # else: noise = np.random.normal(0, self.args.expl_noise, size=action.shape[0]) action = (action + noise) if 'Polar' in self.args.policy_name or 'k_steps' in self.args.policy_name: action = action.clip(0, 1) else: action = action.clip(-1, 1) state_id = 0 # Perform action if 'Polar' in self.args.policy_name: new_obs, reward, done, _ = self.step_episode(action) # elif 'k_steps' in self.args.policy_name: # new_obs, reward, done, _ = self.step_k_steps(action) else: new_obs, reward, done, _ = self.env.step(action) self.episode_timesteps += 1 self.total_time_steps += 1 self.time_steps_since_eval += 1 self.time_steps_calc_Q_vale += 1 done_bool = 0 if self.episode_timesteps >= self.env._max_episode_steps else float(done) if 'Polar' in self.args.policy_name: self.replay_buffer.add((np.asarray([self.obs[0]]), np.asarray([new_obs[0]]), action, reward, done_bool, state_id)) else: self.replay_buffer.add((self.obs, new_obs, action, reward, done_bool, state_id)) self.obs = new_obs # Final evaluation self.eval_once() self.env.reset() def eval_only(self, is_reset = True): video_dir = '{}/video_all/video_IM/{}_{}'.format( self.result_path, self.args.policy_name, self.args.env_name) if not os.path.exists(video_dir): os.makedirs(video_dir) model_path_vec = glob.glob(self.result_path + '/{}/{}_{}_seed*'.format( self.args.log_path, self.args.policy_name, self.args.env_name)) print(model_path_vec) fps = 50 self.env.render(mode='human') for model_path in model_path_vec: # print(model_path) self.policy.load("%s" % (self.file_name + self.args.load_policy_idx), directory=model_path) video_name = video_dir + '/{}_{}_{}.mp4'.format( datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S"), self.file_name, self.args.load_policy_idx) obs = self.env.reset() obs_mat = np.asarray(obs) action_mat = None time.sleep(1) use_mujoco = True # if use_mujoco and self.args.save_video: # GlfwContext(offscreen=True) done = False ave_reward = 0.0 ave_vel = obs[3] * 3 if self.args.save_video: fourcc = cv2.VideoWriter_fourcc(*'MP4V') img = self.env.render(mode='rgb_array') out_video = cv2.VideoWriter(video_name, fourcc, fps, (img.shape[1], img.shape[0])) t = 0 while not done: obs = self.add_disturbance(t, obs) if 'Polar' in self.args.policy_name: action = self.policy.select_action(np.asarray([obs[0]])) else: action = self.policy.select_action(np.array(obs)) obs, reward, done, _ = self.env.step(action) ave_reward += reward obs_mat = np.c_[obs_mat, np.asarray(obs)] if action_mat is None: action_mat = np.asarray(self.env.get_torque()) else: action_mat = np.c_[action_mat, np.asarray(self.env.get_torque())] if self.args.save_video: if 0 == t % (1 / (fps * self.env.dt)): img = self.env.render(mode='rgb_array') img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) out_video.write(img) elif self.args.render: self.env.render(mode='human') t += 1 if not self.args.render: utils.write_table(video_name + '_state', np.transpose(obs_mat)) utils.write_table(video_name + '_torque', np.transpose(action_mat)) if self.args.save_video: out_video.release() print('Average reward: {}'.format(ave_reward)) if is_reset: self.env.reset() def add_disturbance(self, t, obs): if t < 400: v_d = 2 elif t < 800: v_d = 4 else: v_d = 3 self.env.update_v_d(v_d) obs[0] = v_d if t > 1200 and t < 1300: self.env.update_external_force(f_x = self.env.scale * 10) elif t > 1600 and t < 1700: self.env.update_external_force(f_x = -self.env.scale * 10) else: self.env.update_external_force(f_x=0) return obs # Runs policy for X episodes and returns average reward def evaluate_policy(env, policy, args, eval_episodes=10): avg_reward = 0. for i in range(eval_episodes): obs = env.reset() done = False t = 0 if 'Polar' in args.policy_name: action = policy.select_action(np.asarray([obs[0]])) while not done: if 'Polar' not in args.policy_name: # if 'k_steps' in args.policy_name: # # if 0 == t % 100: # if 0 == env.control_time: # action = policy.select_action(np.array(obs)) # else: action = policy.select_action(np.array(obs)) obs, reward, done, _ = env.step(action) avg_reward += reward t += 1 avg_reward /= eval_episodes return avg_reward
# frozen_string_literal: true require "test_helper" class MessagingServicesControllerTest < ActionDispatch::IntegrationTest setup do @messaging_service = create(:messaging_service) end test "should get index" do get messaging_services_url assert_response :success end test "should get new" do get new_messaging_service_url assert_response :success end test "should create messaging_service" do assert_difference("MessagingService.count") do post messaging_services_url, params: { messaging_service: attributes_for(:messaging_service) } end assert_redirected_to messaging_service_url(MessagingService.order(:created_at).last) end test "should show messaging_service" do get messaging_service_url(@messaging_service) assert_response :success end test "should get edit" do get edit_messaging_service_url(@messaging_service) assert_response :success end test "should update messaging_service" do patch messaging_service_url(@messaging_service), params: { messaging_service: { alias_name: @messaging_service.alias_name, webhook_url: @messaging_service.webhook_url } } assert_redirected_to messaging_service_url(@messaging_service) end test "should destroy messaging_service" do assert_difference("MessagingService.count", -1) do delete messaging_service_url(@messaging_service) end assert_redirected_to messaging_services_url end end
#!/bin/bash # Build config for build.sh APP_NAME=extensiondev CHROME_PROVIDERS="content locale skin" ROOT_FILES="install.js 7zip.bat cygzip.bat winrar.bat winzip.bat wzcline.bat zip.bat zip.sh" ROOT_DIRS="chrome"
// Interfaces shared across the app but not necessary going into database export enum ScoreType { ORES_DAMAGING = 'ores_damaging', ORES_BADFAITH = 'ores_badfaith', STIKI = 'stiki', CLUEBOTNG = 'cbng', WIKITRUST = 'wikitrust' } export enum BasicJudgement { LooksGood = 'LooksGood', NotSure = 'NotSure', ShouldRevert = 'ShouldRevert' } export interface Score { type: ScoreType, score: number, isBad: boolean, version?: string, } export interface RevisionPanelItem { feed?: string, wiki: string, revId: number, title: string, summary: string, author: string, timestamp: number, diffHtml?: string, } export enum WikiActionType { RedirectToRevert = 'RedirectRevert', RedirectToHistory = 'RedirectToHistory', DirectRevert = 'DirectRevert', }
from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser #from django.forms import CharField, PasswordInput import hashlib import urllib2 from django.conf import settings from datetime import datetime class UserManager(BaseUserManager): def create_user(self, email, firstName, lastName, password=None): if not email: raise ValueError('Users must have an email address') user = self.model(email=UserManager.normalize_email(email), firstName=firstName, lastName=lastName, ) user.set_password(password) timestring = datetime.now().strftime("%a %b %d %h:%m:%s mst %y") stringtohash = timestring + user.email user.guid = hashlib.sha1(stringtohash).hexdigest() user.save(using=self._db) return user def create_superuser(self, email, firstName, lastName, password): user = self.create_user(email=email, firstName=firstName, lastName=lastName, password=password, ) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): class Meta: verbose_name_plural = 'Users' verbose_name = 'User' def clean(self): """ clean and validate the models fields. """ # only set the guid once if not self.guid: timestring = datetime.now().strftime("%a %b %d %h:%m:%s mst %y") stringtohash = timestring + self.email self.guid = hashlib.sha1(stringtohash).hexdigest() if not self.displayname: self.displayname = self.firstName + " " + self.lastName email = models.EmailField("Email", max_length=75, unique=True) firstName = models.CharField("First Name", max_length=50) lastName = models.CharField("Last Name", max_length=50) displayname = models.CharField("Display Name", max_length=100) guid = models.CharField("guid", max_length=40, blank=True) host = models.CharField("Host", max_length=40) url = models.CharField("URL", max_length=150) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstName', 'lastName'] def get_full_name(self): # The user is identified by full name return self.firstName + " " + self.lastName def get_short_name(self): # The user is identified by their first name return self.firstName def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin class Category(models.Model): """ This model tracks all the categories entered by the users. There isn't anything about this section in the spec, however it did appear in the example_artivle.json. """ def __str__(self): return self.category_name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" category_name = models.CharField("Category", max_length=100, blank=True) class Friends(models.Model): """ Defines the Friends relationship Fields: user_requester user_target accepted (false, true) With the foreign keys here the reverse relationships should be available on the User model. """ user_id_requester = models.ForeignKey(User, related_name='requester') user_id_receiver = models.ForeignKey(User, related_name='receiver') accepted = models.BooleanField(default=False) class Meta: unique_together = ("user_id_requester", "user_id_receiver") verbose_name = "Friends" verbose_name_plural = "Friends" def __str__(self): return self.user_id_requester.email + " -> " \ + self.user_id_receiver.email + " " + str(self.accepted) class Post(models.Model): """ Defines a Post Model Fields from JSON example_artivle.json title: Title of the post source: The URL of where we got the post origin: The URL of where it actually came from description: Brief description of the post, limited by characters of 100 content-type: choice of [text/html, text/x-markdown, text/plain] content: Text field to input the contents of the post author: Foreign key referenceing author * Need clarification of that implementation of this field categories: List, multiple select options for categories this post falls under * Special case * Comments: Foreign key referencing a comment entry For settings up the one-to-many relationship in this case set up a foreign key on each comment referencing a post, and django will automatically set up the reverse relationship so we can get the comments on a post easily. This is accomplished by the 'related_name' argument in the foreignKey of each comment. Then we can do 'some_post.comments' and get all the comments for that post Published date: Date the post was created, not modifiable afterwards giud: Still to be implemented. A guid is a 40 digit sha1 thats unique globally between all servers. visibility: choice of [PUBLIC, FOAF, FRIENDS, PRIVATE, SERVERONLY] * From the requirements there is another type. PRIVATE to another author """ class Meta: verbose_name = "Post" verbose_name_plural = "Posts" def __str__(self): return self.title + "-posted by-" + self.author.email def clean(self): """ clean and validate the models fields. Also for posts adds the guid from the present data. """ # only set the guid once if not self.guid: timestring = datetime.now().strftime("%a %b %d %h:%m:%s mst %y") stringtohash = self.title + timestring + self.author.email self.guid = hashlib.sha1(stringtohash).hexdigest() def save(self, *args, **kwargs): if self.image_url: image = urllib2.urlopen(self.image_url) image_file_path = settings.MEDIA_URL + '%s.jpg' % self.guid image_file_path = image_file_path.lstrip('/') image_file = open(image_file_path, 'wb') image_file.write(image.read()) image_file.close() self.image_location = image_file_path super(Post, self).save(*args, **kwargs) # Choices for content_type field CONTENT_TYPE_CHOICES = ( ('HTML', 'text/html'), ('X-MARKDOWN', 'text/x-markdown'), ('PLAIN', 'text/plain'), ('IMAGE', 'image'), ) # Choices for visibility field VISIBILITY_CHOICES = ( ('PUBLIC', 'Public'), ('FOAF', 'Friend of a friend'), ('FRIENDS', 'Friends'), ('PRIVATE', 'Private'), ('SERVERONLY', 'Server only'), ) # ID/PK done auto for us title = models.CharField("Title", max_length=80) source = models.URLField("Source") origin = models.URLField("Origin") description = models.CharField("Description", max_length=100) content_type = models.CharField("Content type", max_length=20, choices=CONTENT_TYPE_CHOICES) content = models.TextField("Content") author = models.ForeignKey(User) # Commenting out until we get clarification on the implementation of categories categories = models.ManyToManyField(Category) published_date = models.DateTimeField(auto_now_add=True) guid = models.CharField("guid", max_length=40, blank=True) visibility = models.CharField("Visibility", max_length=20, choices=VISIBILITY_CHOICES) # This is for image posts image_url = models.URLField("Image URL", blank=True) image_location = models.CharField("image_location", max_length=100, blank=True) class Comment(models.Model): """ Defines a Comment of a post, made by a user Fields: post: This is a one-to-many field on posts, from the post we can call post.comments to get all the comments for that post. user: This is a many-to-one field on the comment. A user can author many posts content: Text field for inputing the contents of the comment message published_date: Date comment was published, unchangable after creation giud: Still to be implemented. A guid is a 40 digit sha1 thats unique globally between all servers. """ class Meta: verbose_name = "Comment" verbose_name_plural = "Comments" def __str__(self): return self.post.title + "-commented on by-" + self.user.email def clean(self): """ clean and validate the models fields. """ # only set the guid once if not self.guid: timestring = datetime.now().strftime("%a %b %d %h:%m:%s mst %y") stringtohash = self.post.title + timestring + self.user.email self.guid = hashlib.sha1(stringtohash).hexdigest() post = models.ForeignKey(Post, related_name='comments') user = models.ForeignKey(User) content = models.TextField("Content") published_date = models.DateTimeField(auto_now_add=True) guid = models.CharField("guid", max_length=40, blank=True) class GitHub(models.Model): user = models.ForeignKey(User) gitUser = models.CharField(max_length=20) token = models.CharField(max_length=40) class Server(models.Model): name = models.CharField("Name", max_length=40) ip = models.IPAddressField("IP Address") url = models.URLField("URL") port = models.IntegerField("Port") host = models.CharField("Host", max_length=40) class Meta: verbose_name = "Server" verbose_name_plural = "Servers" def __str__(self): return self.name
export default class Player { constructor(playerId, playerIndex, playerName) { this._playerId = playerId; this._playerIndex = playerIndex; this._playerName = playerName; } playerId() { return this._playerId; } playerIndex() { return this._playerIndex; } playerName() { return this._playerName; } }
using System.Threading; using System.Threading.Tasks; namespace Snijderman.Common.Async.ProducerConsumer; public interface IProducerConsumerChannelBase<T> { /// <summary> /// This method wil produce the content that can be picked up by the worker tasks /// </summary> /// <param name="contentToProduce">Content that should be produced</param> /// <param name="cancellationToken"></param> /// <returns></returns> Task ProduceAsync(T contentToProduce, CancellationToken cancellationToken = default); /// <summary> /// Complete the channel, so no new items can be produced and wait for the consumers to be done /// The channel is closed when all is done. /// </summary> /// <returns></returns> Task CompleteAsync(); /// <summary> /// Get the number of consumers that is currently busy processing content /// </summary> int ActiveConsumerCount { get; } /// <summary> /// Indication if all data that is produced is picked up and processed by the consumer(s) /// </summary> bool AllProducedItemsConsumed { get; } /// <summary> /// Get the number of unprocessed queued items /// </summary> int ItemsInQueue { get; } }
/** * @license * Copyright 2016 Google 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 {AxesLineHelper} from 'neuroglancer/axes_lines'; import {DisplayContext} from 'neuroglancer/display_context'; import {MouseSelectionState, RenderLayer, VisibleRenderLayerTracker} from 'neuroglancer/layer'; import {PickIDManager} from 'neuroglancer/object_picking'; import {RenderedDataPanel} from 'neuroglancer/rendered_data_panel'; import {SliceView, SliceViewRenderHelper} from 'neuroglancer/sliceview/frontend'; import {ElementVisibilityFromTrackableBoolean, TrackableBoolean} from 'neuroglancer/trackable_boolean'; import {Mat4, identityMat4, mat4, vec3, vec4} from 'neuroglancer/util/geom'; import {startRelativeMouseDrag} from 'neuroglancer/util/mouse_drag'; import {ViewerState} from 'neuroglancer/viewer_state'; import {OffscreenCopyHelper, OffscreenFramebuffer} from 'neuroglancer/webgl/offscreen'; import {ShaderBuilder} from 'neuroglancer/webgl/shader'; import {ScaleBarWidget} from 'neuroglancer/widget/scale_bar'; import {Signal} from 'signals'; export interface SliceViewerState extends ViewerState { showScaleBar: TrackableBoolean; } export enum OffscreenTextures { COLOR, PICK, NUM_TEXTURES } export function sliceViewPanelEmit(builder: ShaderBuilder) { builder.addFragmentExtension('GL_EXT_draw_buffers'); builder.addFragmentCode(` void emit(vec4 color, vec4 pickId) { gl_FragData[${OffscreenTextures.COLOR}] = color; gl_FragData[${OffscreenTextures.PICK}] = pickId; } `); } export interface SliceViewPanelRenderContext { dataToDevice: Mat4; pickIDs: PickIDManager; } export class SliceViewPanelRenderLayer extends RenderLayer { redrawNeeded = new Signal(); draw(renderContext: SliceViewPanelRenderContext) { // Must be overriden by subclass. } }; export class SliceViewPanel extends RenderedDataPanel { private axesLineHelper = AxesLineHelper.get(this.gl); private sliceViewRenderHelper = SliceViewRenderHelper.get(this.gl, 'SliceViewRenderHelper', sliceViewPanelEmit); private colorFactor = vec4.fromValues(1, 1, 1, 1); private backgroundColor = vec4.fromValues(0.5, 0.5, 0.5, 1.0); private pickIDs = new PickIDManager(); private visibleLayerTracker = this.registerDisposer(new VisibleRenderLayerTracker<SliceViewPanelRenderLayer>( this.viewer.layerManager, SliceViewPanelRenderLayer, layer => { layer.redrawNeeded.add(this.scheduleRedraw, this); this.scheduleRedraw(); }, layer => { layer.redrawNeeded.remove(this.scheduleRedraw, this); this.scheduleRedraw(); })); private offscreenFramebuffer = new OffscreenFramebuffer(this.gl, {numDataBuffers: OffscreenTextures.NUM_TEXTURES}); private offscreenCopyHelper = OffscreenCopyHelper.get(this.gl); private scaleBarWidget = this.registerDisposer(new ScaleBarWidget()); get navigationState() { return this.sliceView.navigationState; } constructor( context: DisplayContext, element: HTMLElement, public sliceView: SliceView, viewer: SliceViewerState) { super(context, element, viewer); this.registerDisposer(sliceView); this.registerSignalBinding(sliceView.viewChanged.add(context.scheduleRedraw, context)); this.registerSignalBinding(viewer.showAxisLines.changed.add(() => { this.scheduleRedraw(); })); { let scaleBar = this.scaleBarWidget.element; this.registerDisposer( new ElementVisibilityFromTrackableBoolean(viewer.showScaleBar, scaleBar)); this.element.appendChild(scaleBar); } } draw() { let {sliceView} = this; if (!sliceView.hasValidViewport) { return; } sliceView.updateRendering(); let {gl} = this; let {width, height, dataToDevice} = sliceView; this.offscreenFramebuffer.bind(width, height); gl.disable(gl.SCISSOR_TEST); this.gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.clear(gl.COLOR_BUFFER_BIT); // Draw axes lines. // FIXME: avoid use of temporary matrix let mat = mat4.create(); this.sliceViewRenderHelper.draw( sliceView.offscreenFramebuffer.dataTextures[0], identityMat4, this.colorFactor, this.backgroundColor, 0, 0, 1, 1); let visibleLayers = this.visibleLayerTracker.getVisibleLayers(); let {pickIDs} = this; pickIDs.clear(); let renderContext = {dataToDevice: sliceView.dataToDevice, pickIDs: pickIDs}; for (let renderLayer of visibleLayers) { renderLayer.draw(renderContext); } if (this.viewer.showAxisLines.value) { // Construct matrix that maps [-1, +1] x/y range to the full viewport data // coordinates. mat4.copy(mat, dataToDevice); for (let i = 0; i < 3; ++i) { mat[12 + i] = 0; } for (let i = 0; i < 4; ++i) { mat[2 + 4 * i] = 0; } let axisLength = Math.min(width, height) / 4 * 1.5; let pixelSize = sliceView.pixelSize; for (let i = 0; i < 12; ++i) { // pixelSize is nm / pixel // mat[i] *= axisLength * pixelSize; } gl.WEBGL_draw_buffers.drawBuffersWEBGL([gl.WEBGL_draw_buffers.COLOR_ATTACHMENT0_WEBGL]); this.axesLineHelper.draw(mat); } this.offscreenFramebuffer.unbind(); // Draw the texture over the whole viewport. this.setGLViewport(); this.offscreenCopyHelper.draw(this.offscreenFramebuffer.dataTextures[OffscreenTextures.COLOR]); // Update the scale bar if needed. { let {scaleBarWidget} = this; let {dimensions} = scaleBarWidget; dimensions.targetLengthInPixels = Math.min(width / 4, 100); dimensions.nanometersPerPixel = sliceView.pixelSize; scaleBarWidget.update(); } } onResize() { this.sliceView.setViewportSize(this.element.clientWidth, this.element.clientHeight); } updateMouseState(mouseState: MouseSelectionState) { mouseState.pickedRenderLayer = null; let sliceView = this.sliceView; if (!sliceView.hasValidViewport) { return false; } let {width, height} = sliceView; let {offscreenFramebuffer} = this; if (!offscreenFramebuffer.hasSize(width, height)) { return false; } let out = mouseState.position; let glWindowX = this.mouseX; let y = this.mouseY; vec3.set(out, glWindowX - width / 2, y - height / 2, 0); vec3.transformMat4(out, out, sliceView.viewportToData); let glWindowY = height - y; this.pickIDs.setMouseState( mouseState, offscreenFramebuffer.readPixelAsUint32(OffscreenTextures.PICK, glWindowX, glWindowY)); return true; } onMousedown(e: MouseEvent) { if (event.target !== this.element) { return; } super.onMousedown(e); if (!this.sliceView.hasValidViewport) { return; } if (e.button === 0) { let {mouseState} = this.viewer; if (mouseState.updateUnconditionally()) { let initialPosition = vec3.clone(this.viewer.mouseState.position); startRelativeMouseDrag(e, (event, deltaX, deltaY) => { let {position} = this.viewer.navigationState; if (event.shiftKey) { let {viewportAxes} = this.sliceView; this.viewer.navigationState.pose.rotateAbsolute( viewportAxes[1], deltaX / 4.0 * Math.PI / 180.0, initialPosition); this.viewer.navigationState.pose.rotateAbsolute( viewportAxes[0], deltaY / 4.0 * Math.PI / 180.0, initialPosition); } else { let pos = position.spatialCoordinates; vec3.set(pos, deltaX, deltaY, 0); vec3.transformMat4(pos, pos, this.sliceView.viewportToData); position.changed.dispatch(); } }); } } } /** * Zooms by the specified factor, maintaining the data position that projects to the current mouse * position. */ zoomByMouse(factor: number) { let {navigationState} = this; if (!navigationState.valid) { return; } let {sliceView} = this; let {width, height} = sliceView; let {mouseX, mouseY} = this; mouseX -= width / 2; mouseY -= height / 2; let oldZoom = this.navigationState.zoomFactor.value; // oldPosition + (mouseX * viewportAxes[0] + mouseY * viewportAxes[1]) * oldZoom // === newPosition + (mouseX * viewportAxes[0] + mouseY * viewportAxes[1]) * newZoom // Therefore, we compute newPosition by: // newPosition = oldPosition + (viewportAxes[0] * mouseX + // viewportAxes[1] * mouseY) * (oldZoom - newZoom). navigationState.zoomBy(factor); let newZoom = navigationState.zoomFactor.value; let {spatialCoordinates} = navigationState.position; vec3.scaleAndAdd( spatialCoordinates, spatialCoordinates, sliceView.viewportAxes[0], mouseX * (oldZoom - newZoom)); vec3.scaleAndAdd( spatialCoordinates, spatialCoordinates, sliceView.viewportAxes[1], mouseY * (oldZoom - newZoom)); navigationState.position.changed.dispatch(); } };
package akkaviz.server import akka.actor.ActorSystem import akka.http.scaladsl.marshalling.Marshaller import akka.http.scaladsl.marshalling.Marshalling.WithFixedContentType import akka.http.scaladsl.model.MediaTypes import akka.http.scaladsl.testkit.ScalatestRouteTest import akka.stream.ActorMaterializer import akka.stream.scaladsl._ import akka.stream.testkit.scaladsl._ import org.scalatest.concurrent.ScalaFutures import org.scalatest.{FunSuite, Matchers} import scala.concurrent.duration._ class AkkaHttpHelpersTest extends FunSuite with Matchers with ScalaFutures with ScalatestRouteTest { import AkkaHttpHelpers._ override implicit val patienceConfig: PatienceConfig = PatienceConfig(10.seconds) private[this] implicit val system: ActorSystem = ActorSystem() private[this] implicit val materializer = ActorMaterializer()(system) private[this] implicit val marshaller = Marshaller.strict[Int, String] { received => WithFixedContentType(MediaTypes.`application/json`, () => String.valueOf(received)) } test("Should work for empty Source") { whenReady(Source.empty[Int].via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) { _ shouldBe "[]" } } test("Should work for single element in Source") { whenReady(Source.single(1).via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) { _ shouldBe "[1]" } } test("Should work for multiple elements element in Source") { whenReady(Source(List(1, 2, 3)).via(asJsonArray).map(_.data.utf8String).runReduce(_ + _)) { _ shouldBe "[1,2,3]" } } test("asJsonArray is incremental") { val (pub, sub) = TestSource.probe[Int] .via(asJsonArray) .map(_.data().utf8String) .toMat(TestSink.probe[String])(Keep.both) .run() pub.sendNext(1) sub.request(10) sub.expectNext("[") pub.sendNext(2) sub.expectNext("1") pub.sendNext(3) sub.expectNext(",2") pub.sendComplete() sub.expectNext(",3") sub.expectNext("]") sub.expectComplete() } test("completeAsJson works properly") { val source = Source(List(1, 2, 3)) Get() ~> completeAsJson(source) ~> check { chunks should have size (5) responseAs[String] shouldEqual "[1,2,3]" } } }
import { baseAddressFromXpub} from './helpers/addresses' const HARDENED_THRESHOLD = 0x80000000; const shelleyPath = (account: number, isChange: boolean, addrIdx: number) => { return [ HARDENED_THRESHOLD + 1852, HARDENED_THRESHOLD + 1815, HARDENED_THRESHOLD + account, isChange ? 1 : 0, addrIdx, ] } const shelleyStakeAccountPath = (account: number) => { return [ HARDENED_THRESHOLD + 1852, HARDENED_THRESHOLD + 1815, HARDENED_THRESHOLD + account, 2, // "staking key chain" 0, ] } export const getStakingXpub = async ( cryptoProvider, accountIndex: number ) => { const path = shelleyStakeAccountPath(accountIndex) const xpubHex = (await cryptoProvider.deriveXpub(path)).toString('hex') return { path, xpubHex, } } export const getAccountXpub = async ( cryptoProvider, accountIndex: number ) => { const path = shelleyStakeAccountPath(accountIndex).slice(0, 3) const xpubHex = (await cryptoProvider.deriveXpub(path)).toString('hex') return { path, xpubHex, } } export const ShelleyBaseAddressProvider = ( cryptoProvider, accountIndex: number, isChange: boolean ) => async (i: number) => { const pathSpend = shelleyPath(accountIndex, isChange, i) const spendXpub = await cryptoProvider.deriveXpub(pathSpend) const pathStake = shelleyStakeAccountPath(accountIndex) const stakeXpub = await cryptoProvider.deriveXpub(pathStake) return { path: pathSpend, address: baseAddressFromXpub(spendXpub, stakeXpub, cryptoProvider.network.networkId), } }
package d3.genericMethods; import java.util.ArrayList; import java.util.List; public class GenericMethods { public static <T> List<T> createList(T item, int count) { List<T> list = new ArrayList<>(); for (int i = 0; i < count; i++) { list.add(item); } return list; } public static <T> void printClass(T item) { System.out.println(item.getClass().getName()); } public static <T extends Comparable<T>> T getMax(List<T> list) { T max = list.get(0); for (int i = 1; i < list.size(); i++) { if (max.compareTo(list.get(i)) < 0) { max = list.get(i); } } return max; } }
# 快速搜索 * [Everything](http://www.voidtools.com) * http://www.voidtools.com/Everything-1.4.1.895.x86-Setup.exe
require 'spec_helper' require 'actions/package_create' module VCAP::CloudController describe PackageCreate do let(:package_create) { PackageCreate.new(user, user_email) } describe '#create' do let(:app) { AppModel.make } let(:type) { 'docker' } let(:app_guid) { app.guid } let(:message) { PackageCreateMessage.new({ type: type, app_guid: app_guid }) } let(:user) { User.make } let(:user_email) { 'user@example.com' } it 'creates the package with the correct values' do result = package_create.create(message) expect(app.packages.first).to eq(result) created_package = PackageModel.find(guid: result.guid) expect(created_package).to eq(result) expect(created_package.type).to eq(type) end it 'creates an audit event' do expect(Repositories::Runtime::PackageEventRepository).to receive(:record_app_add_package).with( instance_of(PackageModel), user, user_email, { 'app_guid' => app_guid, 'type' => type, } ) package_create.create(message) end describe 'docker packages' do let(:message) do data = { type: 'docker', app_guid: app_guid, data: { image: 'registry/image:latest', credentials: { user: 'user name', password: 'pw', email: 'email', login_server: 'login server' }, store_image: true } } PackageCreateMessage.new(data) end it 'persists docker info' do result = package_create.create(message) expect(app.packages.first).to eq(result) created_package = PackageModel.find(guid: result.guid) expect(created_package).to eq(result) expect(created_package.docker_data.image).to eq('registry/image:latest') expect(created_package.docker_data.store_image).to eq(true) expect(created_package.docker_data.user).to eq('user name') expect(created_package.docker_data.password).to eq('pw') expect(created_package.docker_data.login_server).to eq('login server') end context 'when store_image is not provided' do let(:message) do data = { type: 'docker', app_guid: app_guid, data: { image: 'registry/image:latest', credentials: { user: 'user name', password: 'pw', email: 'email', login_server: 'login server' }, store_image: '' } } PackageCreateMessage.new(data) end it 'defaults to false' do result = package_create.create(message) expect(app.packages.first).to eq(result) created_package = PackageModel.find(guid: result.guid) expect(created_package.docker_data.store_image).to eq(false) end end end describe 'package state' do context 'when type is bits' do let(:type) { 'bits' } let(:url) { nil } it 'sets the state to CREATED_STATE' do result = package_create.create(message) expect(result.type).to eq('bits') expect(result.state).to eq(PackageModel::CREATED_STATE) end end context 'when the type is docker' do it 'sets the state to READY_STATE' do result = package_create.create(message) expect(result.type).to eq('docker') expect(result.state).to eq(PackageModel::READY_STATE) end end end context 'when the package is invalid' do before do allow_any_instance_of(PackageModel).to receive(:save).and_raise(Sequel::ValidationFailed.new('the message')) end it 'raises an InvalidPackage error' do expect { package_create.create(message) }.to raise_error(PackageCreate::InvalidPackage, 'the message') end end end end end
// All web components polyfills (including platform) with "window" passed as argument to the iife import "../thirdparty/webcomponents-sd-ce-pf.js"; // All IE11 polyfills, needed by the project itself import "./IE11.js";
// Copyright (C) 2003-2010 Xtensive LLC. // All rights reserved. // For conditions of distribution and use, see license. // Created by: Alex Yakunin // Created: 2010.06.24 using System; using System.Linq; using NUnit.Framework; using Xtensive.Core; using Xtensive.Orm.Configuration; namespace Xtensive.Orm.Tests.Storage.SetFieldTest { [Serializable] [HierarchyRoot] public class Book : Entity { [Key, Field] public Guid Id { get; private set; } [Field] public string Title { get; set; } [Field] public DateTime Date { get; set; } [Field] public Direction? NullableDirection { get; set; } [Field] public byte[] Image { get; set; } [Field] public Book Pair { get; set; } } [TestFixture] public class SetFieldTest : AutoBuildTest { private int fieldSetCallCount; protected override DomainConfiguration BuildConfiguration() { var configuration = base.BuildConfiguration(); configuration.Types.Register(typeof(Book).Assembly, typeof(Book).Namespace); return configuration; } [Test] public void CombinedTest() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { session.Events.EntityFieldValueSetting += (sender, e) => { fieldSetCallCount++; }; var book = new Book(); AssertIsCalled (() => { book.Title = "A"; }); AssertIsNotCalled(() => { book.Title = "A"; }); AssertIsCalled (() => { book.Date = new DateTime(1,2,3); }); AssertIsNotCalled(() => { book.Date = new DateTime(1,2,3); }); var image = new byte[] {1, 2, 3}; AssertIsCalled (() => { book.Image = image; }); AssertIsCalled (() => { book.Image = image; }); AssertIsNotCalled(() => { book.Pair = null; }); AssertIsCalled (() => { book.Pair = book; }); AssertIsNotCalled(() => { book.Pair = book; }); AssertIsCalled (() => { book.Pair = null; }); AssertIsNotCalled(() => { book.Pair = null; }); } } [Test] public void NullableEnumSetTest() { using (var session = Domain.OpenSession()) using (var tx = session.OpenTransaction()) { var book = new Book(); book.NullableDirection = Direction.Positive; book.NullableDirection = null; } } private void AssertIsCalled(Action action) { int oldCallCount = fieldSetCallCount; action.Invoke(); if (fieldSetCallCount==oldCallCount) Assert.Fail("Expected event didn't occur."); } private void AssertIsNotCalled(Action action) { int oldCallCount = fieldSetCallCount; action.Invoke(); if (fieldSetCallCount!=oldCallCount) Assert.Fail("Event occurred, although it shouldn't."); } } }
import 'dart:async'; import 'package:flutter/services.dart'; import 'constants.dart'; import 'extensions/extensions.dart'; import 'models/authentication_completed.dart'; import 'models/ignore_device_completed.dart'; import 'models/logs_sent_server.dart'; import 'models/pairing_options_required.dart'; import 'models/pairing_completed.dart'; import 'models/enums/trust_level.dart'; import 'models/enums/action.dart'; class PingIDSDKClient { final MethodChannel _channel = const MethodChannel('pingidsdk'); StreamController<PairingOptionsRequired> _pairingOptionsRequiredController; StreamController<PairingOptionsRequired> _pairingOptionsRequiredWithPasswordController; StreamController<String> _pairingProgressController; StreamController<PairingCompleted> _pairingCompletedController; StreamController<IgnoreDeviceCompleted> _ignoreDeviceCompletedController; StreamController<void> _didUntrustDeviceCompletedController; StreamController<dynamic> _authenticationRequiredController; StreamController<AuthenticationCompleted> _authenticationCompletedController; StreamController<void> _authenticationCancelledController; StreamController<String> _oneTimePasswordChangedController; StreamController<dynamic> _authenticationTokenStatusController; StreamController<void> _servicePayloadReceivedWithStatusDoneController; StreamController<LogsSentToServer> _logsSentToServerController; StreamController<String> _generalMessageController; StreamController<int> _googlePlayServicesStatusReceivedController; StreamController<dynamic> _errorController; PingIDSDKClient() { _pairingOptionsRequiredController = StreamController<PairingOptionsRequired>.broadcast(); _pairingOptionsRequiredWithPasswordController = StreamController<PairingOptionsRequired>.broadcast(); _pairingProgressController = StreamController<String>.broadcast(); _pairingCompletedController = StreamController<PairingCompleted>.broadcast(); _ignoreDeviceCompletedController = StreamController<IgnoreDeviceCompleted>.broadcast(); _didUntrustDeviceCompletedController = StreamController<void>.broadcast(); _authenticationRequiredController = StreamController<dynamic>.broadcast(); _authenticationCompletedController = StreamController<AuthenticationCompleted>.broadcast(); _authenticationCancelledController = StreamController<void>.broadcast(); _oneTimePasswordChangedController = StreamController<String>.broadcast(); _authenticationTokenStatusController = StreamController<dynamic>.broadcast(); _servicePayloadReceivedWithStatusDoneController = StreamController<void>.broadcast(); _logsSentToServerController = StreamController<LogsSentToServer>.broadcast(); _generalMessageController = StreamController<String>.broadcast(); _googlePlayServicesStatusReceivedController = StreamController<int>.broadcast(); _errorController = StreamController<dynamic>.broadcast(); _channel.setMethodCallHandler(_callbacks); } Future<dynamic> _callbacks(MethodCall call) { print(call.method); print(call.arguments); try { switch (call.method) { case PingEvents.PAIRING_OPTIONS_REQUIRED: _pairingOptionsRequiredController .add(call.parsePairingOptionsRequired()); break; case PingEvents.PAIRING_OPTIONS_REQUIRED_WITH_PASSWORD: _pairingOptionsRequiredWithPasswordController .add(call.parsePairingOptionsRequiredWithPassword()); break; case PingEvents.PAIRING_PROGRESS: _pairingProgressController.add(call.parsePairingProgress()); break; case PingEvents.PAIRING_COMPLETED: _pairingCompletedController.add(call.parsePairingCompleted()); break; case PingEvents.IGNORE_DEVICE_COMPLETED: _ignoreDeviceCompletedController .add(call.parseIgnoreDeviceCompleted()); break; case PingEvents.DID_UNTRUST_DEVICE: _didUntrustDeviceCompletedController.add(null); break; case PingEvents.AUTHENTICATION_REQUIRED: _authenticationRequiredController .add(call.parseAuthenticationRequired()); break; case PingEvents.AUTHENTICATION_COMPLETED: _authenticationCompletedController .add(call.parseAuthenticationCompleted()); break; case PingEvents.AUTHENTICATION_CANCELLED: _authenticationCancelledController.add(null); break; case PingEvents.ONE_TIME_PASSWORD_CHANGED: _oneTimePasswordChangedController .add(call.parseOneTimePasswordChanged()); break; case PingEvents.AUTHENTICATION_TOKEN_STATUS: _authenticationTokenStatusController .add(call.parseAuthenticationTokenStatus()); break; case PingEvents.SERVICE_PAYLOAD_RECEIVED_WITH_STATUS_DONE: _servicePayloadReceivedWithStatusDoneController.add(null); break; case PingEvents.LOGS_SENT_TO_SERVER: _logsSentToServerController.add(call.parseLogsSentToServer()); break; case PingEvents.GENERAL_MESSAGE: _generalMessageController.add(call.parseGeneralMessage()); break; case PingEvents.GOOGLE_PLAY_SERVICES_STATUS_RECEIVED: _googlePlayServicesStatusReceivedController .add(call.parseGooglePlayServicesStatusReceived()); break; case PingEvents.ERROR: _errorController.add(call.parseError()); break; } } catch (e) { print(e); } return null; } Future<String> get payload => _channel.invokeMethod(NativeMethods.GET_PAYLOAD); Future<void> sendServerPayload(String payload) => _channel.invokeMethod(NativeMethods.SEND_SERVER_PAYLOAD, { SendServerPayloadArgs.PAYLOAD: payload, }); Future<void> pairingSelection( TrustLevel trustLevel, Action action, String username) => _channel.invokeMethod(NativeMethods.PAIRING_SELECTION, { PairingSelectionArgs.TRUST_LEVEL: trustLevel.value, PairingSelectionArgs.ACTION: action.value, PairingSelectionArgs.USERNAME: username }); Future<void> authenticationSelection(Action action, String username) => _channel.invokeMethod(NativeMethods.AUTHENTICATION_SELECTION, { AuthenticationSelectionArgs.ACTION: action.value, AuthenticationSelectionArgs.USERNAME: username }); Future<bool> get deviceIsTrusted => _channel.invokeMethod(NativeMethods.DEVICE_IS_TRUSTED); Stream<PairingOptionsRequired> get pairingOptionsRequired => _pairingOptionsRequiredController.stream; Stream<PairingOptionsRequired> get pairingOptionsRequiredWithPassword => _pairingOptionsRequiredWithPasswordController.stream; Stream<String> get pairingProgress => _pairingProgressController.stream; Stream<PairingCompleted> get pairingCompleted => _pairingCompletedController.stream; Stream<IgnoreDeviceCompleted> get ignoreDeviceCompleted => _ignoreDeviceCompletedController.stream; Stream<void> get didUntrustDevice => _didUntrustDeviceCompletedController.stream; Stream<dynamic> get authenticationRequired => _authenticationRequiredController.stream; Stream<AuthenticationCompleted> get authenticationCompleted => _authenticationCompletedController.stream; Stream<void> get authenticationCancelled => _authenticationCancelledController.stream; Stream<String> get oneTimePasswordChanged => _oneTimePasswordChangedController.stream; Stream<dynamic> get authenticationTokenStatus => _authenticationTokenStatusController.stream; Stream<void> get servicePayloadReceivedWithStatusDone => _servicePayloadReceivedWithStatusDoneController.stream; Stream<LogsSentToServer> get logsSentToServer => _logsSentToServerController.stream; Stream<String> get generalMessage => _generalMessageController.stream; Stream<int> get googlePlayServicesStatusReceived => _googlePlayServicesStatusReceivedController.stream; Stream<dynamic> get error => _errorController.stream; }
<?php $data = Timber::get_context(); $post = Timber::query_post(); $data['post'] = $post; // Solution if (is_singular('solution')) : // Get header image $data['header_img'] = get_field('acf_solution_image'); // Get connected cases if (get_field('acf_solution_products')): $case_args = array( 'post_type' => 'case', 'meta_query' => array( array( 'key' => 'acf_case_solutions', 'value' => '"' . $post->ID . '"', 'compare' => 'LIKE' ) ) ); $data['solution_cases'] = Timber::get_posts($case_args); endif; $data['data_sheet'] = get_field('acf_solution_data_sheet'); // Get connected products $product_ids = get_field('acf_solution_products', false, false); if ($product_ids) : $product_args = array( 'post_type' => 'product', 'post__in' => $product_ids, 'orderby' => 'post__in', 'posts_per_page' => -1 ); $data['products'] = Timber::get_posts($product_args); endif; // Case elseif (is_singular('case')): // Get header image $data['header_img'] = get_field('acf_case_image'); $data['header_title'] = true; // Get connected solutions $solutions_ids = get_field('acf_case_solutions', false, false); if ($solutions_ids) : $solutions_args = array( 'post_type' => 'solution', 'post__in' => $solutions_ids, 'orderby' => 'post__in', 'posts_per_page' => -1 ); $data['solutions'] = Timber::get_posts($solutions_args); endif; // Installation elseif (is_singular('installation')): // Get header image $data['header_img'] = get_field('acf_installation_image'); $data['steps'] = get_field('acf_installation_steps'); // Get connected products $product_ids = get_field('acf_installation_products', false, false); if ($product_ids) : $product_args = array( 'post_type' => 'product', 'post__in' => $product_ids, 'orderby' => 'post__in', 'posts_per_page' => -1 ); $data['products'] = Timber::get_posts($product_args); endif; $data['data_sheet'] = get_field('acf_installation_data_sheet'); endif; Timber::render(array( 'single-' . $post->post_type . '.twig', 'page.twig' ), $data);
#!/usr/bin/env bash ## Firefox ## https://www.mozilla.org/firefox/ ## Remove export HOSTNAME=$(hostname -s) if (type "porg" > /dev/null 2>&1); then porg -r firefox fi rm -rf ${HOME}/.porg/$HOSTNAME/src/firefox ## Setup mkdir -pv ${HOME}/.porg/$HOSTNAME/src/firefox cd ${HOME}/.porg/$HOSTNAME/src/firefox ## Download # NOTE: http://ftp.mozilla.org/pub/firefox/releases/latest/README.txt export URL="https://download.mozilla.org/?product=firefox-latest&os=linux64&lang=en-US" wget -O firefox.tar.bz2 --no-check-certificate ${URL} tar -xvf firefox.tar.bz2 ## Install export VERSION=$(${HOME}/.porg/$HOSTNAME/src/firefox/firefox/firefox -v | awk '{print $3}') porg -lp firefox-${VERSION} "cp -rf ${HOME}/.porg/$HOSTNAME/src/firefox/firefox ${HOME}/.porg/$HOSTNAME/opt" ## Check porg firefox cd ${HOME}
MyCuteAssistant ========================================= Your cute girl-for-all on your screen. Let her plan, automate & assist by jobs, making your life easier.
const sass = require('node-sass') module.exports = { '_hypot($x...)': x => { const list = [] for (let i = 0; i < x.getLength(); i++) { const value = x.getValue(i) if (!(value instanceof sass.types.Number)) { throw "$x: Expected a number." } else if (value.getUnit()) { throw '$x: Expected a unitless number.' } list.push(value.getValue()) } return new sass.types.Number(Math.hypot(...list)) } }
package egovframework.com.uss.umt.service; import java.util.List; public interface EgovDeptManageService { /** * 부서를 관리하기 위해 등록된 부서목록을 조회한다. * @param deptManageVO - 부서 Vo * @return List - 부서 목록 * * @param deptManageVO */ public List<DeptManageVO> selectDeptManageList(DeptManageVO deptManageVO) throws Exception; /** * 부서목록 총 갯수를 조회한다. * @param deptManageVO - 부서 Vo * @return int - 부서 카운트 수 * * @param deptManageVO */ public int selectDeptManageListTotCnt(DeptManageVO deptManageVO) throws Exception; /** * 등록된 부서의 상세정보를 조회한다. * @param deptManageVO - 부서 Vo * @return deptManageVO - 부서 Vo * * @param deptManageVO */ public DeptManageVO selectDeptManage(DeptManageVO deptManageVO) throws Exception; /** * 부서정보를 신규로 등록한다. * @param deptManageVO - 부서 model * * @param deptManageVO */ public void insertDeptManage(DeptManageVO deptManageVO) throws Exception; /** * 기 등록된 부서정보를 수정한다. * @param deptManageVO - 부서 model * * @param deptManageVO */ public void updateDeptManage(DeptManageVO deptManageVO) throws Exception; /** * 기 등록된 부서정보를 삭제한다. * @param deptManageVO - 부서 model * * @param deptManageVO */ public void deleteDeptManage(DeptManageVO deptManageVO) throws Exception; }
package hdzi.editstarters.ui import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.Project import com.intellij.ui.CollectionComboBoxModel import com.intellij.ui.CollectionListModel import hdzi.editstarters.buildsystem.BuildSystem import hdzi.editstarters.springboot.initializr.SpringInitializr import hdzi.editstarters.springboot.initializr.StarterInfo import org.apache.commons.lang.WordUtils import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.* import javax.swing.* class EditStartersDialog(buildSystem: BuildSystem, initializr: SpringInitializr) { private lateinit var root: JPanel private lateinit var buttonOK: JButton private lateinit var buttonCancel: JButton private lateinit var versionComboBox: JComboBox<String> private lateinit var moduleList: JList<String> private lateinit var starterList: JList<StarterInfo> private lateinit var selectList: JList<StarterInfo> private lateinit var searchField: JTextField private val frame: JFrame private val title = "Edit Starters" private val addStarters = HashSet<StarterInfo>(64) private val removeStarters = HashSet<StarterInfo>(64) private val toolTipTextCache = WeakHashMap<StarterInfo, String>() // 加个缓存 init { this.frame = JFrame(this.title) this.frame.contentPane = this.root // boot版本选框 this.versionComboBox.model = CollectionComboBoxModel( initializr.version.values.map { it.id }, initializr.currentVersionID ) this.versionComboBox.isEnabled = false // 取消按钮 this.buttonCancel.addActionListener { this.frame.dispose() } // ok按钮 this.buttonOK.addActionListener { WriteCommandAction.runWriteCommandAction(buildSystem.context.getData<Project>(CommonDataKeys.PROJECT)) { buildSystem.addStarters(this.addStarters) buildSystem.removeStarters(this.removeStarters) } this.frame.dispose() } val modulesMap = initializr.modulesMap // Module列表 this.moduleList.model = CollectionListModel(modulesMap.keys) this.moduleList.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { searchField.text = "" val name = moduleList.selectedValue starterList.model = CollectionListModel(modulesMap[name] ?: Collections.emptyList()) } }) // 显示详细信息 val showDescAdapter = object : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { @Suppress("unchecked_cast") val list = e.source as JList<StarterInfo> val index = list.locationToIndex(e.point) if (index > -1) { val starter = list.model.getElementAt(index) list.toolTipText = starter.getStarterInfoToolTipText() } } } // Starter列表 this.starterList.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (e.clickCount == 2) { // 按两下选择 val starterInfo = starterList.selectedValue if (starterInfo.exist) { // 对于已存在的starter,添加就是从删除列表里删除 removeStarters.remove(starterInfo) } else { // 对于不存在的starter,添加直接加入添加列表 addStarters.add(starterInfo) } // 去重显示 val listModel = selectList.model as CollectionListModel<StarterInfo> if (!listModel.contains(starterInfo)) { listModel.add(starterInfo) } } } }) this.starterList.addMouseMotionListener(showDescAdapter) // selected列表 this.selectList.model = CollectionListModel(initializr.existStarters) this.selectList.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (e.clickCount == 2) { // 按两下删除 val starterInfo = selectList.selectedValue if (starterInfo.exist) { // 对于已存在的starter,删除就是加入删除列表 removeStarters.add(starterInfo) } else { // 对于不存在的starter,删除是从添加列表里删除 addStarters.remove(starterInfo) } // 显示 (selectList.model as CollectionListModel<StarterInfo>).remove(starterInfo) } } }) this.selectList.addMouseMotionListener(showDescAdapter) // 搜索框 this.searchField.addKeyListener(object : KeyAdapter() { override fun keyReleased(e: KeyEvent) { moduleList.clearSelection() val searchKey = searchField.text.toLowerCase() val result = modulesMap.values.flatMap { starters -> starters.filter { starter -> "${starter.groupId}:${starter.artifactId}\t${starter.name}" .toLowerCase().contains(searchKey) } } starterList.model = CollectionComboBoxModel(result) } }) } fun show() { this.frame.pack() this.frame.setLocationRelativeTo(null) // 中间显示 this.frame.isVisible = true } private fun StarterInfo.getStarterInfoToolTipText(): String = toolTipTextCache.computeIfAbsent(this) { info -> val buffer = StringBuilder() buffer.append("GroupId: ").append(info.groupId).append("<br/>") .append("ArtifactId: ").append(info.artifactId).append("<br/>") .append("Scope: ").append(info.scope).append("<br/>") if (info.version != null) { buffer.append("Version: ").append(info.version).append("<br/>") } if (info.versionRange != null) { buffer.append("Version Range: ").append(info.versionRange).append("<br/>") } buffer.append("<br/>").append(WordUtils.wrap(info.description, 50, "<br/>", false)) buffer.toString() } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.OfficeProPlus.Downloader.Model { public class UpdateChannel { public UpdateChannel() { if (Updates == null) Updates = new List<Update>(); } public string Name { get; set; } public List<Update> Updates { get; set; } } }
using System; using NUnit.Framework; namespace XmlDiff.Tests { [TestFixture] public class DiffValueTests { private readonly string Raw = "theValue"; [Test] [TestCase(null)] [TestCase("")] [ExpectedException(typeof(ArgumentNullException))] public void Ctor_ShouldNotAllowRaw_ToBeNull(string raw) { new DiffValue(DiffAction.Added, raw); } [Test] [TestCase(DiffAction.Added)] [TestCase(DiffAction.Removed)] public void IsChangedProperty_ShouldAlwaysBeTrue(DiffAction action) { var diffVal = new DiffValue(action, Raw); Assert.IsTrue(diffVal.IsChanged); } [Test] public void ToString_ReturnStringRepresentation() { var diffVal = new DiffValue(DiffAction.Added, Raw); string result = diffVal.ToString(); string expected = "+ Value: \"theValue\"\r\n"; Assert.AreEqual(expected, result); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemLibrary { private Dictionary<int, Item> library = new Dictionary<int, Item>(); private Item[] items; public ItemLibrary() { SetLibrary(); } private void SetLibrary() { items = Resources.LoadAll<Item>("Item"); //probably needs to check for duplicates just in case? foreach (var item in items) { library.Add(item.id, item); } } public Item GetItem(int id) { return library[id]; } }
using System; using System.Collections.Generic; using System.Text; namespace ServicePublisher.GeoSpatial { public class SdeServerInfo { private string _server; public string server { get { return _server; } set { _server = value; } } private string _instance; public string instance { get { return _instance; } set { _instance = value; } } private string _database; public string database { get { return _database; } set { _database = value; } } private string _user; public string user { get { return _user; } set { _user = value; } } private string _password; public string password { get { return _password; } set { _password = value; } } private string _version; public string version { get { return _version; } set { _version = value; } } } }
module lagmod !$$$ module documentation block ! . . . . ! module: lagmod ! prgmmr: purser/cucurull org: np23 date: 2005-12-01 ! ! abstract: This module contains routines (including tangent linear and adjoint code) ! to perform basic operations related to Lagrange polynomial interpolation. ! ! program history log: ! 2003 purser - routines for the forward code ! 2005-12-01 cucurull - implement tangent linear and adjoint code ! - adapt the code to GSI standards ! 2008-05-09 safford - complete documentation block ! ! subroutines included: ! setq ! setq_TL ! setq_AD ! lagdw ! lagdw_TL ! lagdw_AD ! slagdw ! slagdw_TL ! slagdw_AD ! ! variables defined: ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ use kinds, only: r_kind,i_kind use constants, only: zero,one implicit none ! set default to private private ! set subroutines to public public :: setq public :: setq_TL public :: setq_AD public :: lagdw public :: lagdw_TL public :: lagdw_AD public :: slagdw public :: slagdw_TL public :: slagdw_AD contains subroutine setq(q,x,n) !$$$ subprogram documentation block ! . . . ! subprogram: setq ! ! prgrmmr: ! ! abstract: Precompute the N constant denominator factors of the N-point ! Lagrange polynomial interpolation formula. ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! X - The N abscissae. ! N - The number of points involved. ! ! output argument list: ! Q - The N denominator constants. ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block IMPLICIT NONE INTEGER(i_kind) ,INTENT(in ) :: n REAL(r_kind),DIMENSION(n),INTENT( out) :: q REAL(r_kind),DIMENSION(n),INTENT(in ) :: x !----------------------------------------------------------------------------- INTEGER(i_kind) :: i,j !============================================================================= DO i=1,n q(i)=one DO j=1,n IF(j /= i)q(i)=q(i)/(x(i)-x(j)) ENDDO ENDDO end subroutine setq !============================================================================ subroutine setq_TL(q,q_TL,x,x_TL,n) !$$$ subprogram documentation block ! . . . ! subprogram: setq_TL ! ! prgrmmr: ! ! abstract: ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! x - ! x_TL - ! n - The number of points involved. ! ! output argument list: ! q - ! Q_TL ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(in ) :: n REAL(r_kind),DIMENSION(n),INTENT( out) :: q,q_TL REAL(r_kind),DIMENSION(n),INTENT(in ) :: x,x_TL !----------------------------------------------------------------------------- INTEGER(i_kind) :: i,j REAL(r_kind) :: rat !============================================================================= DO i=1,n q(i)=one q_TL(i)=zero DO j=1,n IF(j /= i) THEN rat=one/(x(i)-x(j)) q_TL(i)=(q_TL(i)-q(i)*(x_TL(i)-x_TL(j))*rat)*rat q(i)=q(i)*rat ENDIF ENDDO ENDDO end subroutine setq_TL !============================================================================ subroutine setq_AD(q_AD,x,x_AD,n) !$$$ subprogram documentation block ! . . . ! subprogram: setq_AD ! ! prgrmmr: ! ! abstract: ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! q_AD - ! x - ! x_AD - ! n - The number of points involved. ! ! output argument list: ! x_AD - ! q_AD - ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(in ) :: n REAL(r_kind),DIMENSION(n),INTENT(in ) :: x REAL(r_kind),DIMENSION(n),INTENT(inout) :: x_AD REAL(r_kind),DIMENSION(n),INTENT(inout) :: q_AD !----------------------------------------------------------------------------- INTEGER(i_kind) :: i,j REAL(r_kind),DIMENSION(n) :: q REAL(r_kind),DIMENSION(n,n) :: jac !============================================================================= call setq(q,x,n) jac=zero DO i=1,n DO j=1,n IF(j /= i) THEN jac(j,i)=q(i)/(x(i)-x(j)) jac(i,i)=jac(i,i)-jac(j,i) ENDIF ENDDO ENDDO x_AD=x_AD+matmul(jac,q_AD) end subroutine setq_AD !============================================================================ subroutine lagdw(x,xt,q,w,dw,n) !$$$ subprogram documentation block ! . . . ! subprogram: lagdw ! ! prgrmmr: ! ! abstract: Construct the Lagrange weights and their derivatives when ! target abscissa is known and denominators Q have already ! been precomputed ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! X - Grid abscissae ! XT - Target abscissa ! Q - Q factors (denominators of the Lagrange weight formula) ! N - Number of grid points involved in the interpolation ! ! output argument list: ! W - Lagrange weights ! DW - Derivatives, dW/dX, of Lagrange weights W ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(IN ) :: n REAL(r_kind) ,INTENT(IN ) :: xt REAL(r_kind),DIMENSION(n),INTENT(IN ) :: x,q REAL(r_kind),DIMENSION(n),INTENT( OUT) :: w,dw !----------------------------------------------------------------------------- REAL(r_kind),DIMENSION(n) :: d,pa,pb,dpa,dpb INTEGER(i_kind) :: j !============================================================================ pa(1)=one dpa(1)=zero do j=1,n-1 d(j)=xt-x(j) pa (j+1)=pa (j)*d(j) dpa(j+1)=dpa(j)*d(j)+pa(j) enddo d(n)=xt-x(n) pb(n)=one dpb(n)=zero do j=n,2,-1 pb (j-1)=pb (j)*d(j) dpb(j-1)=dpb(j)*d(j)+pb(j) enddo do j=1,n w (j)= pa(j)*pb (j)*q(j) dw(j)=(pa(j)*dpb(j)+dpa(j)*pb(j))*q(j) enddo end subroutine lagdw !============================================================================ subroutine lagdw_TL(x,x_TL,xt,q,q_TL,w,w_TL,dw,dw_TL,n) !$$$ subprogram documentation block ! . . . ! subprogram: lagdw_TL ! ! prgrmmr: ! ! abstract: ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! x - ! xt - ! q - ! q_TL - ! n - The number of points involved. ! ! output argument list: ! w - ! dw - ! w_TL - ! dw_TL - ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(IN ) :: n REAL(r_kind) ,INTENT(IN ) :: xt REAL(r_kind),DIMENSION(n),INTENT(IN ) :: x,q,x_TL,q_TL REAL(r_kind),DIMENSION(n),INTENT( OUT) :: w,dw,w_TL,dw_TL !----------------------------------------------------------------------------- REAL(r_kind),DIMENSION(n) :: d,pa,pb,dpa,dpb REAL(r_kind),DIMENSION(n) :: d_TL,pa_TL,pb_TL,dpa_TL,dpb_TL INTEGER(i_kind) :: j !============================================================================ pa(1)=one dpa(1)=zero pa_TL(1)=zero dpa_TL(1)=zero do j=1,n-1 d(j)=xt-x(j) d_TL(j)=-x_TL(j) pa (j+1)=pa (j)*d(j) pa_TL (j+1)=pa_TL (j)*d(j)+pa(j)*d_TL(j) dpa (j+1)=dpa (j)*d(j)+pa(j) dpa_TL(j+1)=dpa_TL(j)*d(j)+dpa(j)*d_TL(j)+pa_TL(j) enddo d(n)=xt-x(n) d_TL(n)=-x_TL(n) pb(n)=one dpb(n)=zero pb_TL(n)=zero dpb_TL(n)=zero do j=n,2,-1 pb (j-1)=pb (j)*d(j) pb_TL (j-1)=pb_TL (j)*d(j)+pb (j)*d_TL(j) dpb (j-1)=dpb (j)*d(j)+pb (j) dpb_TL(j-1)=dpb_TL(j)*d(j)+dpb(j)*d_TL(j)+pb_TL(j) enddo do j=1,n w (j)= pa (j)*pb (j)*q(j) dw (j)=(pa (j)*dpb(j)+dpa(j)*pb (j))*q(j) w_TL (j)=(pa_TL(j)*pb (j)+pa (j)*pb_TL (j))*q(j)+pa(j)*pb(j)*q_TL(j) dw_TL(j)=(pa_TL(j)*dpb(j)+pa (j)*dpb_TL(j)+dpa_TL(j)*pb(j)+dpa(j)*pb_TL(j))*q(j)+ & (pa (j)*dpb(j)+dpa(j)*pb (j))*q_TL(j) enddo end subroutine lagdw_TL !============================================================================ subroutine lagdw_AD(x,x_AD,xt,q,q_AD,w_AD,dw_AD,n) !$$$ subprogram documentation block ! . . . ! subprogram: lagdw_AD ! ! prgrmmr: ! ! abstract: ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! n - ! xt - ! x - ! q - ! q_AD - ! x_AD - ! w_AD - ! dw_AD - ! ! output argument list: ! q_AD - ! x_AD - ! w_AD - ! dw_AD - ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(IN ) :: n REAL(r_kind) ,INTENT(IN ) :: xt REAL(r_kind),DIMENSION(n),INTENT(IN ) :: x,q REAL(r_kind),DIMENSION(n),INTENT(INOUT) :: q_AD,x_AD,w_AD,dw_AD !----------------------------------------------------------------------------- REAL(r_kind),DIMENSION(n) :: d,pa,pb,dpa,dpb REAL(r_kind),DIMENSION(n) :: d_AD,pa_AD,pb_AD,dpa_AD,dpb_AD INTEGER(i_kind) :: j !============================================================================ pa_AD=zero; dpb_AD=zero; dpa_AD=zero; pb_AD=zero d_AD=zero ! passive variables pa(1)=one dpa(1)=zero do j=1,n-1 d(j)=xt-x(j) pa (j+1)=pa (j)*d(j) dpa(j+1)=dpa(j)*d(j)+pa(j) enddo d(n)=xt-x(n) pb(n)=one dpb(n)=zero do j=n,2,-1 pb (j-1)=pb (j)*d(j) dpb(j-1)=dpb(j)*d(j)+pb(j) enddo ! do j=n,1,-1 pa_AD (j)=pa_AD (j)+ dpb(j)*q (j)*dw_AD(j) dpb_AD(j)=dpb_AD(j)+ pa (j)*q (j)*dw_AD(j) dpa_AD(j)=dpa_AD(j)+ pb (j)*q (j)*dw_AD(j) pb_AD (j)=pb_AD (j)+ dpa(j)*q (j)*dw_AD(j) q_AD (j)=q_AD (j)+(pa (j)*dpb(j)+dpa (j)*pb(j))*dw_AD(j) pa_AD (j)=pa_AD (j)+ pb (j)*q (j)*w_AD (j) pb_AD (j)=pb_AD (j)+ pa (j)*q (j)*w_AD (j) q_AD (j)=q_AD (j)+ pa (j)*pb (j)*w_AD (j) end do do j=2,n dpb_AD(j)=dpb_AD(j)+d (j)*dpb_AD(j-1) d_AD (j)=d_AD (j)+dpb(j)*dpb_AD(j-1) pb_AD (j)=pb_AD (j) +dpb_AD(j-1) pb_AD (j)=pb_AD (j)+d (j)*pb_AD (j-1) d_AD (j)=d_AD (j)+pb (j)*pb_AD (j-1) enddo dpb_AD(n)=zero ! not sure about it pb_AD(n) =zero ! not sure about it x_AD(n)=x_AD(n)-d_AD(n) do j=n-1,1,-1 dpa_AD(j)=dpa_AD(j)+d (j)*dpa_AD(j+1) d_AD (j)=d_AD (j)+dpa(j)*dpa_AD(j+1) pa_AD (j)=pa_AD (j) +dpa_AD(j+1) pa_AD (j)=pa_AD (j)+d (j)*pa_AD (j+1) d_AD (j)=d_AD (j)+pa (j)*pa_AD (j+1) x_AD (j)=x_AD (j) -d_AD (j ) enddo end subroutine lagdw_AD !============================================================================ subroutine slagdw(x,xt,aq,bq,w,dw,n) !$$$ subprogram documentation block ! . . . ! subprogram: slagdw ! ! prgrmmr: ! ! abstract: Construct weights and their derivatives for interpolation ! to a given target based on a linearly weighted mixture of ! the pair of Lagrange interpolators which omit the respective ! end points of the source nodes provided. The number of source ! points provided must be even and the nominal target interval ! is the unique central one. The linear weighting pair is ! determined by the relative location of the target within ! this central interval, or else the extreme values, 0 and 1, ! when target lies outside this interval. The objective is to ! provide an interpolator whose derivative is continuous. ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! X - Grid abscissae (N points) ! XT - Target abscissa ! AQ,BQ - Q factors (denominators of the Lagrange weight formula for ! the two respective consecutive subsets of N-1 grid points) ! N - Even number of grid points involved in the interpolation ! ! output argument list: ! W - Final weights (N values) ! DW - Final derivatives, dW/dX, of weights W (N values) ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(IN ) :: n REAL(r_kind) ,INTENT(IN ) :: xt REAL(r_kind),DIMENSION(n) ,INTENT(IN ) :: x REAL(r_kind),DIMENSION(n-1),INTENT(IN ) :: aq,bq REAL(r_kind),DIMENSION(n) ,INTENT( OUT) :: w,dw !----------------------------------------------------------------------------- REAL(r_kind),DIMENSION(n) :: aw,bw,daw,dbw REAL(r_kind) :: xa,xb,dwb,wb INTEGER(i_kind) :: na !============================================================================ CALL lagdw(x(1:n-1),xt,aq,aw(1:n-1),daw(1:n-1),n-1) CALL lagdw(x(2:n ),xt,bq,bw(2:n ),dbw(2:n ),n-1) aw(n)=zero daw(n)=zero bw(1)=zero dbw(1)=zero na=n/2 IF(na*2 /= n)STOP 'In slagdw; n must be even' xa =x(na ) xb =x(na+1) dwb=one/(xb-xa) wb =(xt-xa)*dwb IF (wb>one )THEN wb =one dwb=zero ELSEIF(wb<zero)THEN wb =zero dwb=zero ENDIF bw =bw -aw dbw=dbw-daw w =aw +wb*bw dw=daw+wb*dbw+dwb*bw end subroutine slagdw !============================================================================ subroutine slagdw_TL(x,x_TL,xt,aq,aq_TL,bq,bq_TL,dw,dw_TL,n) !$$$ subprogram documentation block ! . . . ! subprogram: slagdw_TL ! ! prgrmmr: ! ! abstract: ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! n ! xt ! x,x_TL ! aq,bq,aq_TL,bq_TL ! dw_TL,dw ! ! output argument list: ! dw_TL,dw ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(IN ) :: n REAL(r_kind) ,INTENT(IN ) :: xt REAL(r_kind),DIMENSION(n) ,INTENT(IN ) :: x,x_TL REAL(r_kind),DIMENSION(n-1),INTENT(IN ) :: aq,bq,aq_TL,bq_TL REAL(r_kind),DIMENSION(n) ,INTENT( OUT) :: dw_TL,dw !----------------------------------------------------------------------------- REAL(r_kind),DIMENSION(n) :: aw,bw,daw,dbw REAL(r_kind),DIMENSION(n) :: aw_TL,bw_TL,daw_TL,dbw_TL REAL(r_kind) :: xa,xb,dwb,wb REAL(r_kind) :: xa_TL,xb_TL,dwb_TL,wb_TL INTEGER(i_kind) :: na !============================================================================ CALL lagdw_TL(x(1:n-1),x_TL(1:n-1),xt,aq,aq_TL,aw(1:n-1),aw_TL(1:n-1),& daw(1:n-1),daw_TL(1:n-1),n-1) CALL lagdw_TL(x(2:n ),x_TL(2:n ),xt,bq,bq_TL,bw(2:n ),bw_TL(2:n ),& dbw(2:n ),dbw_TL(2:n ),n-1) aw(n) =zero daw(n)=zero bw(1) =zero dbw(1)=zero ! aw_TL(n) =zero daw_TL(n)=zero bw_TL(1) =zero dbw_TL(1)=zero na=n/2 IF(na*2 /= n)STOP 'In slagdw; n must be even' xa =x (na) xa_TL=x_TL(na) xb =x (na+1) xb_TL=x_TL(na+1) dwb = one /(xb-xa) dwb_TL=-(xb_TL-xa_TL)/(xb-xa)**2 wb = (xt-xa)*dwb wb_TL=(-xa_TL)*dwb+(xt-xa)*dwb_TL IF (wb > one)THEN wb =one dwb =zero wb_TL =zero dwb_TL=zero ELSEIF(wb < zero)THEN wb =zero dwb =zero wb_TL =zero dwb_TL=zero ENDIF bw =bw -aw bw_TL =bw_TL -aw_TL dbw =dbw -daw dbw_TL=dbw_TL-daw_TL !w=aw+wb*bw dw =daw + wb *dbw + dwb *bw dw_TL=daw_TL+(wb_TL*dbw+wb*dbw_TL)+(dwb_TL*bw+dwb*bw_TL) end subroutine slagdw_TL !============================================================================ SUBROUTINE slagdw_AD(x,x_AD,xt,aq,aq_AD,bq,bq_AD,w_AD,dw,dw_AD,n) !$$$ subprogram documentation block ! . . . ! subprogram: slagdw_AD ! ! prgrmmr: ! ! abstract: ! ! program history log: ! 2008-05-09 safford - add subprogram doc block, rm unused uses ! ! input argument list: ! n ! xt ! x ! aq,bq ! aq_AD,bq_AD ! x_AD,dw_AD,w_AD ! ! output argument list: ! aq_AD,bq_AD ! dw ! x_AD,dw_AD,w_AD ! ! attributes: ! language: f90 ! machine: ibm RS/6000 SP ! !$$$ end documentation block !============================================================================ IMPLICIT NONE INTEGER(i_kind) ,INTENT(IN ) :: n REAL(r_kind) ,INTENT(IN ) :: xt REAL(r_kind),DIMENSION(n) ,INTENT(IN ) :: x REAL(r_kind),DIMENSION(n-1),INTENT(IN ) :: aq,bq REAL(r_kind),DIMENSION(n-1),INTENT(INOUT) :: aq_AD,bq_AD REAL(r_kind),DIMENSION(n) ,INTENT( OUT) :: dw REAL(r_kind),DIMENSION(n) ,INTENT(INOUT) :: x_AD,dw_AD,w_AD !----------------------------------------------------------------------------- REAL(r_kind),DIMENSION(n) :: aw,bw,daw,dbw REAL(r_kind),DIMENSION(n) :: aw_AD,bw_AD,daw_AD,dbw_AD REAL(r_kind) :: xa,xb,dwb,wb REAL(r_kind) :: xa_AD,xb_AD,wb_AD,dwb_AD INTEGER(i_kind) :: na !============================================================================ daw_AD=zero;wb_AD=zero;dbw_AD=zero;dwb_AD=zero;bw_AD=zero aw_AD =zero;xb_AD=zero;xa_AD =zero ! passive variables needed (from forward code) CALL lagdw(x(1:n-1),xt,aq,aw(1:n-1),daw(1:n-1),n-1) CALL lagdw(x(2:n ),xt,bq,bw(2:n ),dbw(2:n ),n-1) aw(n) =zero daw(n)=zero bw(1) =zero dbw(1)=zero na=n/2 IF(na*2 /= n)STOP 'In slagdw; n must be even' xa =x(na ) xb =x(na+1) dwb=one/(xb-xa) wb =(xt-xa)*dwb IF (wb>one)THEN wb =one dwb=zero ELSEIF(wb<zero)THEN wb =zero dwb=zero ENDIF bw =bw -aw dbw=dbw-daw !w=aw+wb*bw ! not needed dw=daw+wb*dbw+dwb*bw ! not needed ! ! daw_AD=daw_AD+dw_AD wb_AD =wb_AD +dot_product(dbw,dw_AD) dbw_AD=dbw_AD+wb*dw_AD dwb_AD=dwb_AD+dot_product(bw,dw_AD) bw_AD =bw_AD +dwb*dw_AD aw_AD=aw_AD+w_AD wb_AD=wb_AD+dot_product(bw,w_AD) bw_AD=bw_AD+wb*w_AD daw_AD=daw_AD-dbw_AD aw_AD =aw_AD -bw_AD IF(wb>one)THEN wb_AD =zero dwb_AD=zero ELSEIF(wb<zero)THEN wb_AD =zero dwb_AD=zero ENDIF xa_AD =xa_AD-wb_AD*dwb dwb_AD =dwb_AD+(xt-xa)*wb_AD xb_AD =xb_AD-(dwb_AD/(xb-xa)**2) xa_AD =xa_AD+(dwb_AD/(xb-xa)**2) x_AD(na+1)=x_AD(na+1)+xb_AD x_AD(na )=x_AD(na )+xa_AD dbw_AD(1)=zero;bw_AD(1)=zero daw_AD(n)=zero;aw_AD(n)=zero CALL lagdw_AD(x(2:n ),x_AD(2:n ),xt,bq,bq_AD,bw_AD(2:n ),& dbw_AD(2:n ),n-1) CALL lagdw_AD(x(1:n-1),x_AD(1:n-1),xt,aq,aq_AD,aw_AD(1:n-1),& daw_AD(1:n-1),n-1) end subroutine slagdw_AD !============================================================================ end module lagmod
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpellforceDataEditor.SFLua.LuaDecompiler { public class Executable : Node { public ILValue Name; public Table Arguments; public override void WriteLuaString(StringWriter sw) { Name.WriteLuaString(sw); if (Arguments.IsList) { sw.Write("("); for(int i = 0; i < Arguments.Items.Count; i++) { Arguments.Items[i].WriteLuaString(sw); if (i != Arguments.Items.Count - 1) sw.Write(", "); } sw.Write(")"); } else { Arguments.WriteLuaString(sw); } } } public class Procedure: Executable, IStatement { public int InstructionID { get; set; } public override string ToString() { return "PROCEDURE (" + Arguments.Items.Count.ToString() + ")"; } } public class Function: Executable, ILValue, IRValue { public override string ToString() { return "FUNCTION (" + Arguments.Items.Count.ToString() + ")"; } } public class Closure: Node, IRValue { public List<Identifier> Arguments = new List<Identifier>(); public Chunk ClosureChunk; public override void WriteLuaString(StringWriter sw) { sw.Write("function("); for (int i = 0; i < Arguments.Count; i++) { Arguments[i].WriteLuaString(sw); if (i != Arguments.Count - 1) sw.Write(", "); } sw.WriteLine(")"); Depth += 1; ClosureChunk.WriteLuaString(sw); Depth -= 1; sw.WriteLine(Utility.TabulateString("end", Depth)); } public override string ToString() { return "CLOSURE (" + Arguments.Count.ToString() + ")"; } } }
package models.bench import scala.concurrent.duration.DurationInt import akka.util.Timeout import akka.pattern.ask import models.akka.AbstractActorSpec import models.akka.Messages.GetDSLinkNames import models.akka.local.{ LocalDSLinkFolderActor, LocalDSLinkManager } /** * BenchmarkActor test suite. */ class BenchmarkActorSpec extends AbstractActorSpec { import BenchmarkActor._ import models.Settings._ implicit val timeout = Timeout(3 seconds) val dsId = "link" + "?" * 44 val dslinkMgr = new LocalDSLinkManager() val downstream = system.actorOf(LocalDSLinkFolderActor.props( Paths.Downstream, dslinkMgr.dnlinkProps, "downstream" -> true), Nodes.Downstream) val bench = system.actorOf(BenchmarkActor.props()) "CreateResponders" should { "create a list of responders" in { bench ! CreateResponders(1 to 5, 10, 5 seconds, None, false) val msg = expectMsgType[RespondersReady] msg.responders.size mustBe 5 } } "CreateRequesters" should { "create a list of requesters" in { bench ! CreateAndStartRequesters(false, 1 to 20, 5, 10, 100, 1000, 5 seconds, None, false) val msg = expectMsgType[RequestersStarted] msg.requesters.size mustBe 20 msg.requesters.values foreach { tgt => tgt.rspIndex must (be >= 1 and be <= 5) tgt.nodeIndex must (be >= 1 and be <= 10) } } } "StopApp" should { "kill all requesters and responders" in { bench ! StopAll Thread.sleep(1000) whenReady((downstream ? GetDSLinkNames).mapTo[Iterable[String]]) { _ mustBe empty } } } }
standard_cards = MTG::Card.where(gameFormat: 'standard').all # standard_cards.map {|card| puts "Type: #{card.type} Supertype: #{card.supertypes} Subtypes: #{card.subtypes}"} # puts standard_cards.last.type # puts standard_cards.last.supertypes # puts standard_cards.last.subtypes # puts standard_cards.last.legalities.map {|legality| "#{legality.format}: #{legality.legality}"} standard_cards.each do |card| new_card = Card.new( name: card.name, cmc: card.cmc, mana_cost: card.mana_cost, color_identity: card.color_identity.try(:join), base_type: card.type.split(" — ")[0].gsub("Legendary ", ""), rarity: card.rarity, power: card.power, toughness: card.toughness, text: card.text, img_url: card.image_url, game_format: 'standard' ) new_card.save end
using System; using System.Collections.Generic; using System.IO; using System.Linq; using WebVella.Erp.Api.Models; using WebVella.Erp.Api.Models.AutoMapper; using WebVella.Erp.Database; using WebVella.Erp.Eql; using WebVella.Erp.Utilities; namespace WebVella.Erp.Web.Services { public class UserService : BaseService { public EntityRecordList GetAll() { var projectRecord = new EntityRecord(); var eqlCommand = "SELECT * from user"; var eqlResult = new EqlCommand(eqlCommand).Execute(); return eqlResult; } public EntityRecord Get(Guid userId) { var projectRecord = new EntityRecord(); var eqlCommand = "SELECT * from user WHERE id = @userId"; var eqlParams = new List<EqlParameter>() { new EqlParameter("userId", userId)}; var eqlResult = new EqlCommand(eqlCommand, eqlParams).Execute(); if (!eqlResult.Any()) { return null; } return eqlResult[0]; } } }
<?php namespace app\modules\canteen\models; use Yii; use yii\base\Model; use yii\bootstrap\Html; /** * @property Dish $dish */ class DishForm extends Model { public $name; public $week_day; public $price; public $portion; /** * @var Dish */ private $_dish; /** * @inheritdoc */ public function rules() { $rules = $this->dish->rules(); return $rules; } /** * @inheritdoc */ public function init() { parent::init(); $this->loadFormAttributes(); } public function loadModelAttributes() { if ($this->validate()) { $this->dish->name = $this->name; $this->dish->week_day = $this->week_day; $this->dish->price = $this->price; $this->dish->portion = $this->portion; $valid = $this->dish->validate(); if (!$valid) { Yii::$app->session->addFlash('error', Html::errorSummary($this->dish)); } return $valid; } return false; } public function loadFormAttributes() { $this->name = $this->dish->name; $this->week_day = $this->dish->week_day; $this->price = $this->dish->price; $this->portion = $this->dish->portion; } public function setDish(Dish $dish) { $this->_dish = $dish; } public function getDish() { if ($this->_dish === null) { $this->_dish = new Dish(); } return $this->_dish; } public function attributeLabels() { return $this->dish->attributeLabels(); } }
# # Cookbook Name:: fmw_domain # Resource:: nodemanager_service # # Copyright 2015 Oracle. All Rights Reserved # provides :fmw_domain_nodemanager_service, os: 'solaris2' # Configure the nodemanager service on Solaris actions :configure # Make create the default action default_action :configure # webLogic bin dir path attribute :bin_dir, kind_of: String, required: true # operating system user attribute :os_user, kind_of: String, required: true # tmp folder attribute :tmp_dir, kind_of: String, required: true # service_name to make this unique attribute :service_name, kind_of: String, required: true
using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Threading.Tasks; using Xamarin.App.Models; using Xamarin.App.Repositories.Interfaces; using Xamarin.App.Views; using Xamarin.Forms; namespace Xamarin.App.ViewModels { public class UsersViewModel : BaseViewModel { public IUserRepository Repository => DependencyService.Get<IUserRepository>(); public ObservableCollection<User> Users { get; set; } public Command LoadUsersCommand { get; set; } public UsersViewModel() { Title = "Users"; Users = new ObservableCollection<User>(); LoadUsersCommand = new Command(async () => await ExecuteLoadUsersCommand()); MessagingCenter.Subscribe<NewUserPage, User>(this, "AddUser", async (obj, User) => { var newUser = User as User; await Repository.SaveUser(newUser); await ExecuteLoadUsersCommand(); }); MessagingCenter.Subscribe<UserDetailPage, string>(this, "DeleteUser", async (obj, userId) => { await Repository.DeleteUser(userId); await ExecuteLoadUsersCommand(); }); } async Task ExecuteLoadUsersCommand() { if (IsBusy) return; IsBusy = true; try { Users.Clear(); var response = await Repository.GetUsers(); foreach (var User in response) { Users.Add(User); } } catch (Exception ex) { Debug.WriteLine(ex); } finally { IsBusy = false; } } } }
// WITH_RUNTIME import java.lang.Math.abs fun x() { // comment <caret>abs(5) }
# Copyright 2017 Google, 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. require_relative "../auth" require "rspec" require "google/cloud/storage" describe "Google Cloud Storage buckets sample" do before :all do @bucket_name = ENV["GOOGLE_CLOUD_STORAGE_BUCKET"] @credentials = ENV["GOOGLE_APPLICATION_CREDENTIALS"] @storage = Google::Cloud::Storage.new @project_id = @storage.project end before do @storage.create_bucket @bucket_name unless @storage.bucket @bucket_name end it "implicit auth to list buckets" do expect { implicit project_id: @project_id }.to output( /#{@bucket_name}/ ).to_stdout end it "explicit auth to list buckets" do expect { explicit project_id: @project_id, key_file: @credentials }.to output( /#{@bucket_name}/ ).to_stdout end it "explicit auth in compute engine to list buckets" do env_object = double expect(Google::Cloud).to receive(:env).and_return env_object expect(env_object).to receive(:project_id).and_return @project_id expect(Google::Auth::GCECredentials).to receive(:new).and_return @credentials expect { explicit_compute_engine }.to output( /#{@bucket_name}/ ).to_stdout end end
% 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(couch_views_batch_test). -include_lib("eunit/include/eunit.hrl"). -include_lib("fabric/test/fabric2_test.hrl"). -include_lib("couch_views/include/couch_views.hrl"). batch_test_() -> { "Test view batch sizing", { setup, fun setup/0, fun cleanup/1, with([ ?TDEF(basic), ?TDEF(search_success), ?TDEF(sense_success), ?TDEF(failure), ?TDEF(failure_switches_to_sense) ]) } }. setup() -> test_util:start_couch(). cleanup(Ctx) -> test_util:stop_couch(Ctx). basic(_) -> erase(couch_views_batch), ?assertEqual(100, couch_views_batch:start(#mrst{})). search_success(_) -> erase(couch_views_batch), couch_views_batch:start(#mrst{}), couch_views_batch:success(#mrst{}, ustats(0, 0, 0)), ?assertEqual(600, couch_views_batch:start(#mrst{})). sense_success(_) -> erase(couch_views_batch), couch_views_batch:start(#mrst{}), % Exceeding our threshold switches from search to sense couch_views_batch:success(#mrst{}, ustats(5000, 10000000, 10000)), ?assertEqual(80, couch_views_batch:start(#mrst{})), couch_views_batch:success(#mrst{}, ustats(0, 0, 0)), ?assertEqual(180, couch_views_batch:start(#mrst{})). failure(_) -> erase(couch_views_batch), couch_views_batch:start(#mrst{}), couch_views_batch:failure(#mrst{}), ?assertEqual(50, couch_views_batch:start(#mrst{})). failure_switches_to_sense(_) -> erase(couch_views_batch), couch_views_batch:start(#mrst{}), couch_views_batch:failure(#mrst{}), couch_views_batch:start(#mrst{}), couch_views_batch:success(#mrst{}, ustats(0, 0, 0)), ?assertEqual(150, couch_views_batch:start(#mrst{})). ustats(DocsRead, TxSize, TotalKVs) -> #{ docs_read => DocsRead, tx_size => TxSize, total_kvs => TotalKVs }.
import React, { Component } from "react" import styled from "styled-components" import Img from "gatsby-image" class RecentProjects extends Component { render() { const json = this.props.frontmatter // console.log(json) const some_projects_title = json.some_projects_title const some_projects_description = json.some_projects_description // console.log(json.some_projects); const Projects = json.some_projects.map((item, i) => ( <a href={item.link} target="_blank" rel="noopener noreferrer" key={i} className={ "some-projects-blocks project-block no-padding relative flex flex-column" + i } > <div className="block-wrapper"> <div className="projects-img-container"> {item.image !== null ? ( <Img fluid={item.image.localFile.childImageSharp.fluid} alt="Gatsby Docs are awesome" loading="eager" /> ) : ( "" )} </div> <div className="text-wrap"> <span className="background-colour" /> <div className="text-wrapping"> <h4 className="title">{item.title}</h4> <span className="visit-site">{item.description}</span> </div> </div> </div> </a> )) return ( <RecentSection> <section id="recent-jobs"> <article className="wrapper text-center"> <div> <h2 className="title">{some_projects_title}</h2> </div> <div className="main-description center" dangerouslySetInnerHTML={{ __html: some_projects_description, }} /> </article> </section> <section id="projects"> <div className="flex flex-wrap wrapper no-padding">{Projects}</div> </section> </RecentSection> ) } } // Set here the ID of the home page. const RecentSection = styled.div` background: #fff; @media screen and (min-width: ${props => props.theme.responsive.m}) { padding-bottom: 5px; } @media screen and (min-width: ${props => props.theme.responsive.l}) { padding-bottom: 80px; } article { padding: 80px 0 35px 0; } .main-description { max-width: 800px; margin: auto; } .some-projects-blocks { text-decoration: none; position: relative; cursor: pointer; width: 100%; overflow: hidden; @media screen and (min-width: ${props => props.theme.responsive.l}) { width: 50%; } .cover { z-index: 4; } .background-colour { background: rgba(0, 0, 0, 0.5); } &:hover { .background-colour { opacity: 0; transition: opacity 300ms ease; } .text-wrapping { opacity: 1; transition: opacity 0.35s cubic-bezier(0.4, 0, 0.2, 1); } img { transform: scale(1.05); transition: transform 300ms ease; } } .visit-site { color: #fff; font-size: 18px; line-height: 22px; font-weight: 300; display: block; } .title { position: relative; z-index: 2; color: #fff; font-size: 22px; line-height: 33px; font-weight: 600; letter-spacing: 1px; display: block; } .text-wrapping { position: relative; z-index: 2; opacity: 1; transition: opacity 0.35s cubic-bezier(0.4, 0, 0.2, 1); } .background-colour { position: absolute; left: 0; top: 0; width: 100%; height: 100%; mix-blend-mode: multiply; opacity: 1; transition: opacity 0.35s cubic-bezier(0.4, 0, 0.2, 1); } .gatsby-image-wrapper { // position: absolute; // height: 100%; // width: 100%; max-height: 200px; padding-bottom: 57.7049% !important; } .projects-img-container { width: 100%; position: relative; background: #d1d3d8; box-shadow: 0 0 44px 0 rgba(0, 0, 0, 0.17); img { position: absolute; top: 0; left: 0; width: 100%; height: auto; transform: scale(1); transition: transform 300ms ease; align-self: center; } } .block-wrapper { position: relative; display: flex; flex-grow: 1; margin: 0px 0 5px 0; overflow: hidden; @media screen and (min-width: ${props => props.theme.responsive.m}) { margin: 5px; } @media screen and (min-width: ${props => props.theme.responsive.l}) { margin: 25px; } } .text-wrap { position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; flex-direction: column; padding: 20px; } } ` export default RecentProjects
target datalayout = "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f128:64:128-n32" target triple = "powerpc-apple-darwin9.8" define i32 @main() nounwind { entry: %retval = alloca i32 %0 = alloca i32 %"alloca point" = bitcast i32 0 to i32 store i32 0, i32* %0, align 4 %1 = load i32, i32* %0, align 4 store i32 %1, i32* %retval, align 4 br label %return return: %retval1 = load i32, i32* %retval ret i32 %retval1 }
//! Bitwise operators. use crate::{ arch::word::Word, buffer::Buffer, ibig::IBig, math, ops::{AndNot, NextPowerOfTwo, UnsignedAbs}, primitive::{double_word, WORD_BITS_USIZE}, sign::Sign::*, ubig::{Repr::*, UBig}, }; use core::{ mem, ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not}, }; impl UBig { /// Returns true if the `n`-th bit is set. /// /// # Examples /// /// ``` /// # use ibig::ubig; /// assert_eq!(ubig!(0b10010).bit(1), true); /// assert_eq!(ubig!(0b10010).bit(3), false); /// assert_eq!(ubig!(0b10010).bit(100), false); /// ``` pub fn bit(&self, n: usize) -> bool { match self.repr() { Small(word) => n < WORD_BITS_USIZE && word & 1 << n != 0, Large(buffer) => { let idx = n / WORD_BITS_USIZE; idx < buffer.len() && buffer[idx] & 1 << (n % WORD_BITS_USIZE) != 0 } } } /// Set the `n`-th bit. /// /// # Examples /// /// ``` /// # use ibig::ubig; /// let mut a = ubig!(0b100); /// a.set_bit(0); /// assert_eq!(a, ubig!(0b101)); /// a.set_bit(10); /// assert_eq!(a, ubig!(0b10000000101)); /// ``` pub fn set_bit(&mut self, n: usize) { match mem::take(self).into_repr() { Small(word) => { if n < WORD_BITS_USIZE { *self = UBig::from_word(word | 1 << n) } else { *self = UBig::with_bit_word_slow(word, n) } } Large(buffer) => *self = UBig::with_bit_large(buffer, n), } } fn with_bit_word_slow(word: Word, n: usize) -> UBig { debug_assert!(n >= WORD_BITS_USIZE); let idx = n / WORD_BITS_USIZE; let mut buffer = Buffer::allocate(idx + 1); buffer.push(word); buffer.extend((1..idx).map(|_| 0)); buffer.push(1 << (n % WORD_BITS_USIZE)); buffer.into() } fn with_bit_large(mut buffer: Buffer, n: usize) -> UBig { let idx = n / WORD_BITS_USIZE; if idx < buffer.len() { buffer[idx] |= 1 << (n % WORD_BITS_USIZE); } else { buffer.ensure_capacity(idx + 1); buffer.push_zeros(idx - buffer.len()); buffer.push(1 << (n % WORD_BITS_USIZE)); } buffer.into() } /// Clear the `n`-th bit. /// /// # Examples /// /// ``` /// # use ibig::ubig; /// let mut a = ubig!(0b101); /// a.clear_bit(0); /// assert_eq!(a, ubig!(0b100)); /// ``` pub fn clear_bit(&mut self, n: usize) { match mem::take(self).into_repr() { Small(word) => { if n < WORD_BITS_USIZE { *self = UBig::from_word(word & !(1 << n)) } } Large(buffer) => *self = UBig::without_bit_large(buffer, n), } } fn without_bit_large(mut buffer: Buffer, n: usize) -> UBig { let idx = n / WORD_BITS_USIZE; if idx < buffer.len() { buffer[idx] &= !(1 << (n % WORD_BITS_USIZE)); } buffer.into() } /// Returns the number of trailing zeros in the binary representation. /// /// In other words, it is the smallest `n` such that 2 to the power of `n` divides the number. /// /// For 0, it returns `None`. /// /// # Examples /// /// ``` /// # use ibig::ubig; /// assert_eq!(ubig!(17).trailing_zeros(), Some(0)); /// assert_eq!(ubig!(48).trailing_zeros(), Some(4)); /// assert_eq!(ubig!(0b101000000).trailing_zeros(), Some(6)); /// assert_eq!(ubig!(0).trailing_zeros(), None); /// ``` pub fn trailing_zeros(&self) -> Option<usize> { match self.repr() { Small(0) => None, Small(word) => Some(word.trailing_zeros() as usize), Large(buffer) => Some(UBig::trailing_zeros_large(buffer)), } } fn trailing_zeros_large(words: &[Word]) -> usize { debug_assert!(*words.last().unwrap() != 0); for (idx, word) in words.iter().enumerate() { if *word != 0 { return idx * WORD_BITS_USIZE + word.trailing_zeros() as usize; } } panic!("trailing_zeros_large(0)") } /// Bit length. /// /// The length of the binary representation of the number. /// /// For 0, the length is 0. /// /// For non-zero numbers it is: /// * `in_radix(2).to_string().len()` /// * the index of the top 1 bit plus one /// * the floor of the logarithm base 2 of the number plus one. /// /// /// /// # Examples /// /// ``` /// # use ibig::ubig; /// assert_eq!(ubig!(17).bit_len(), 5); /// assert_eq!(ubig!(0b101000000).bit_len(), 9); /// assert_eq!(ubig!(0).bit_len(), 0); /// let x = ubig!(_0x90ffff3450897234); /// assert_eq!(x.bit_len(), x.in_radix(2).to_string().len()); /// ``` pub fn bit_len(&self) -> usize { match self.repr() { Small(word) => math::bit_len(*word) as usize, Large(buffer) => { buffer.len() * WORD_BITS_USIZE - buffer.last().unwrap().leading_zeros() as usize } } } /// True if the number is a power of 2. /// /// # Examples /// /// ``` /// # use ibig::ubig; /// assert_eq!(ubig!(0).is_power_of_two(), false); /// assert_eq!(ubig!(8).is_power_of_two(), true); /// assert_eq!(ubig!(9).is_power_of_two(), false); /// ``` pub fn is_power_of_two(&self) -> bool { match self.repr() { Small(word) => word.is_power_of_two(), Large(buffer) => UBig::is_power_of_two_large(buffer), } } fn is_power_of_two_large(words: &[Word]) -> bool { debug_assert!(*words.last().unwrap() != 0); words[..words.len() - 1].iter().all(|x| *x == 0) && words.last().unwrap().is_power_of_two() } } impl IBig { /// Returns the number of trailing zeros in the two's complement binary representation. /// /// In other words, it is the smallest `n` such that 2 to the power of `n` divides the number. /// /// For 0, it returns `None`. /// /// # Examples /// /// ``` /// # use ibig::ibig; /// assert_eq!(ibig!(17).trailing_zeros(), Some(0)); /// assert_eq!(ibig!(-48).trailing_zeros(), Some(4)); /// assert_eq!(ibig!(-0b101000000).trailing_zeros(), Some(6)); /// assert_eq!(ibig!(0).trailing_zeros(), None); /// ``` pub fn trailing_zeros(&self) -> Option<usize> { self.magnitude().trailing_zeros() } } impl NextPowerOfTwo for UBig { type Output = UBig; fn next_power_of_two(self) -> UBig { match self.into_repr() { Small(word) => match word.checked_next_power_of_two() { Some(p) => UBig::from_word(p), None => UBig::from(double_word(0, 1)), }, Large(buffer) => UBig::next_power_of_two_large(buffer), } } } impl NextPowerOfTwo for &UBig { type Output = UBig; fn next_power_of_two(self) -> UBig { self.clone().next_power_of_two() } } impl UBig { fn next_power_of_two_large(mut buffer: Buffer) -> UBig { debug_assert!(*buffer.last().unwrap() != 0); let n = buffer.len(); let mut iter = buffer[..n - 1].iter_mut().skip_while(|x| **x == 0); let carry = match iter.next() { None => 0, Some(x) => { *x = 0; for x in iter { *x = 0; } 1 } }; let last = buffer.last_mut().unwrap(); match last .checked_add(carry) .and_then(|x| x.checked_next_power_of_two()) { Some(p) => *last = p, None => { *last = 0; buffer.ensure_capacity(n + 1); buffer.push(1); } } buffer.into() } } impl BitAnd<UBig> for UBig { type Output = UBig; fn bitand(self, rhs: UBig) -> UBig { match (self.into_repr(), rhs.into_repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 & word1), (Small(word0), Large(buffer1)) => UBig::from_word(word0 & buffer1.first().unwrap()), (Large(buffer0), Small(word1)) => UBig::from_word(buffer0.first().unwrap() & word1), (Large(buffer0), Large(buffer1)) => { if buffer0.len() <= buffer1.len() { UBig::bitand_large(buffer0, &buffer1) } else { UBig::bitand_large(buffer1, &buffer0) } } } } } impl BitAnd<&UBig> for UBig { type Output = UBig; fn bitand(self, rhs: &UBig) -> UBig { match self.into_repr() { Small(word0) => match rhs.repr() { Small(word1) => UBig::from_word(word0 & word1), Large(buffer1) => UBig::from_word(word0 & buffer1.first().unwrap()), }, Large(buffer0) => match rhs.repr() { Small(word1) => UBig::from_word(buffer0.first().unwrap() & word1), Large(buffer1) => UBig::bitand_large(buffer0, &buffer1), }, } } } impl BitAnd<UBig> for &UBig { type Output = UBig; fn bitand(self, rhs: UBig) -> UBig { rhs.bitand(self) } } impl BitAnd<&UBig> for &UBig { type Output = UBig; fn bitand(self, rhs: &UBig) -> UBig { match (self.repr(), rhs.repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 & word1), (Small(word0), Large(buffer1)) => UBig::from_word(word0 & buffer1.first().unwrap()), (Large(buffer0), Small(word1)) => UBig::from_word(buffer0.first().unwrap() & word1), (Large(buffer0), Large(buffer1)) => { if buffer0.len() <= buffer1.len() { UBig::bitand_large(buffer0.clone(), buffer1) } else { UBig::bitand_large(buffer1.clone(), buffer0) } } } } } impl BitAndAssign<UBig> for UBig { fn bitand_assign(&mut self, rhs: UBig) { *self = mem::take(self) & rhs; } } impl BitAndAssign<&UBig> for UBig { fn bitand_assign(&mut self, rhs: &UBig) { *self = mem::take(self) & rhs; } } impl UBig { fn bitand_large(mut buffer: Buffer, rhs: &[Word]) -> UBig { if buffer.len() > rhs.len() { buffer.truncate(rhs.len()); } for (x, y) in buffer.iter_mut().zip(rhs.iter()) { *x &= *y; } buffer.into() } } impl BitOr<UBig> for UBig { type Output = UBig; fn bitor(self, rhs: UBig) -> UBig { match (self.into_repr(), rhs.into_repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 | word1), (Small(word0), Large(buffer1)) => UBig::bitor_large_word(buffer1, word0), (Large(buffer0), Small(word1)) => UBig::bitor_large_word(buffer0, word1), (Large(buffer0), Large(buffer1)) => { if buffer0.len() >= buffer1.len() { UBig::bitor_large(buffer0, &buffer1) } else { UBig::bitor_large(buffer1, &buffer0) } } } } } impl BitOr<&UBig> for UBig { type Output = UBig; fn bitor(self, rhs: &UBig) -> UBig { match self.into_repr() { Small(word0) => match rhs.repr() { Small(word1) => UBig::from_word(word0 | word1), Large(buffer1) => UBig::bitor_large_word(buffer1.clone(), word0), }, Large(buffer0) => match rhs.repr() { Small(word1) => UBig::bitor_large_word(buffer0, *word1), Large(buffer1) => UBig::bitor_large(buffer0, buffer1), }, } } } impl BitOr<UBig> for &UBig { type Output = UBig; fn bitor(self, rhs: UBig) -> UBig { rhs.bitor(self) } } impl BitOr<&UBig> for &UBig { type Output = UBig; fn bitor(self, rhs: &UBig) -> UBig { match (self.repr(), rhs.repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 | word1), (Small(word0), Large(buffer1)) => UBig::bitor_large_word(buffer1.clone(), *word0), (Large(buffer0), Small(word1)) => UBig::bitor_large_word(buffer0.clone(), *word1), (Large(buffer0), Large(buffer1)) => { if buffer0.len() >= buffer1.len() { UBig::bitor_large(buffer0.clone(), buffer1) } else { UBig::bitor_large(buffer1.clone(), buffer0) } } } } } impl BitOrAssign<UBig> for UBig { fn bitor_assign(&mut self, rhs: UBig) { *self = mem::take(self) | rhs; } } impl BitOrAssign<&UBig> for UBig { fn bitor_assign(&mut self, rhs: &UBig) { *self = mem::take(self) | rhs; } } impl UBig { fn bitor_large_word(mut buffer: Buffer, rhs: Word) -> UBig { debug_assert!(buffer.len() >= 2); *buffer.first_mut().unwrap() |= rhs; buffer.into() } fn bitor_large(mut buffer: Buffer, rhs: &[Word]) -> UBig { for (x, y) in buffer.iter_mut().zip(rhs.iter()) { *x |= *y; } if rhs.len() > buffer.len() { buffer.ensure_capacity(rhs.len()); buffer.extend(&rhs[buffer.len()..]); } buffer.into() } } impl BitXor<UBig> for UBig { type Output = UBig; fn bitxor(self, rhs: UBig) -> UBig { match (self.into_repr(), rhs.into_repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 ^ word1), (Small(word0), Large(buffer1)) => UBig::bitxor_large_word(buffer1, word0), (Large(buffer0), Small(word1)) => UBig::bitxor_large_word(buffer0, word1), (Large(buffer0), Large(buffer1)) => { if buffer0.len() >= buffer1.len() { UBig::bitxor_large(buffer0, &buffer1) } else { UBig::bitxor_large(buffer1, &buffer0) } } } } } impl BitXor<&UBig> for UBig { type Output = UBig; fn bitxor(self, rhs: &UBig) -> UBig { match self.into_repr() { Small(word0) => match rhs.repr() { Small(word1) => UBig::from_word(word0 ^ word1), Large(buffer1) => UBig::bitxor_large_word(buffer1.clone(), word0), }, Large(buffer0) => match rhs.repr() { Small(word1) => UBig::bitxor_large_word(buffer0, *word1), Large(buffer1) => UBig::bitxor_large(buffer0, buffer1), }, } } } impl BitXor<UBig> for &UBig { type Output = UBig; fn bitxor(self, rhs: UBig) -> UBig { rhs.bitxor(self) } } impl BitXor<&UBig> for &UBig { type Output = UBig; fn bitxor(self, rhs: &UBig) -> UBig { match (self.repr(), rhs.repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 ^ word1), (Small(word0), Large(buffer1)) => UBig::bitxor_large_word(buffer1.clone(), *word0), (Large(buffer0), Small(word1)) => UBig::bitxor_large_word(buffer0.clone(), *word1), (Large(buffer0), Large(buffer1)) => { if buffer0.len() >= buffer1.len() { UBig::bitxor_large(buffer0.clone(), buffer1) } else { UBig::bitxor_large(buffer1.clone(), buffer0) } } } } } impl BitXorAssign<UBig> for UBig { fn bitxor_assign(&mut self, rhs: UBig) { *self = mem::take(self) ^ rhs; } } impl BitXorAssign<&UBig> for UBig { fn bitxor_assign(&mut self, rhs: &UBig) { *self = mem::take(self) ^ rhs; } } impl UBig { fn bitxor_large_word(mut buffer: Buffer, rhs: Word) -> UBig { debug_assert!(buffer.len() >= 2); *buffer.first_mut().unwrap() ^= rhs; buffer.into() } fn bitxor_large(mut buffer: Buffer, rhs: &[Word]) -> UBig { for (x, y) in buffer.iter_mut().zip(rhs.iter()) { *x ^= *y; } if rhs.len() > buffer.len() { buffer.ensure_capacity(rhs.len()); buffer.extend(&rhs[buffer.len()..]); } buffer.into() } } impl AndNot<UBig> for UBig { type Output = UBig; fn and_not(self, rhs: UBig) -> UBig { match (self.into_repr(), rhs.into_repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 & !word1), (Small(word0), Large(buffer1)) => UBig::from_word(word0 & !buffer1.first().unwrap()), (Large(buffer0), Small(word1)) => UBig::and_not_large_word(buffer0, word1), (Large(buffer0), Large(buffer1)) => UBig::and_not_large(buffer0, &buffer1), } } } impl AndNot<&UBig> for UBig { type Output = UBig; fn and_not(self, rhs: &UBig) -> UBig { match self.into_repr() { Small(word0) => match rhs.repr() { Small(word1) => UBig::from_word(word0 & !word1), Large(buffer1) => UBig::from_word(word0 & !buffer1.first().unwrap()), }, Large(buffer0) => match rhs.repr() { Small(word1) => UBig::and_not_large_word(buffer0, *word1), Large(buffer1) => UBig::and_not_large(buffer0, buffer1), }, } } } impl AndNot<UBig> for &UBig { type Output = UBig; fn and_not(self, rhs: UBig) -> UBig { match self.repr() { Small(word0) => match rhs.into_repr() { Small(word1) => UBig::from_word(word0 & !word1), Large(buffer1) => UBig::from_word(word0 & !buffer1.first().unwrap()), }, Large(buffer0) => match rhs.into_repr() { Small(word1) => UBig::and_not_large_word(buffer0.clone(), word1), Large(buffer1) => UBig::and_not_large(buffer0.clone(), &buffer1), }, } } } impl AndNot<&UBig> for &UBig { type Output = UBig; fn and_not(self, rhs: &UBig) -> UBig { match (self.repr(), rhs.repr()) { (Small(word0), Small(word1)) => UBig::from_word(word0 & !word1), (Small(word0), Large(buffer1)) => UBig::from_word(word0 & !buffer1.first().unwrap()), (Large(buffer0), Small(word1)) => UBig::and_not_large_word(buffer0.clone(), *word1), (Large(buffer0), Large(buffer1)) => UBig::and_not_large(buffer0.clone(), buffer1), } } } impl UBig { fn and_not_large_word(mut buffer: Buffer, rhs: Word) -> UBig { debug_assert!(buffer.len() >= 2); *buffer.first_mut().unwrap() &= !rhs; buffer.into() } fn and_not_large(mut buffer: Buffer, rhs: &[Word]) -> UBig { for (x, y) in buffer.iter_mut().zip(rhs.iter()) { *x &= !*y; } buffer.into() } } impl Not for IBig { type Output = IBig; fn not(self) -> IBig { -(self + IBig::from(1u8)) } } impl Not for &IBig { type Output = IBig; fn not(self) -> IBig { -(self + IBig::from(1u8)) } } impl BitAnd<IBig> for IBig { type Output = IBig; fn bitand(self, rhs: IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs() & rhs.unsigned_abs()), (Positive, Negative) => IBig::from(self.unsigned_abs().and_not((!rhs).unsigned_abs())), (Negative, Positive) => IBig::from(rhs.unsigned_abs().and_not((!self).unsigned_abs())), (Negative, Negative) => !IBig::from((!self).unsigned_abs() | (!rhs).unsigned_abs()), } } } impl BitAnd<&IBig> for IBig { type Output = IBig; fn bitand(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs() & rhs.magnitude()), (Positive, Negative) => IBig::from(self.unsigned_abs().and_not((!rhs).unsigned_abs())), (Negative, Positive) => IBig::from(rhs.magnitude().and_not((!self).unsigned_abs())), (Negative, Negative) => !IBig::from((!self).unsigned_abs() | (!rhs).unsigned_abs()), } } } impl BitAnd<IBig> for &IBig { type Output = IBig; fn bitand(self, rhs: IBig) -> IBig { rhs.bitand(self) } } impl BitAnd<&IBig> for &IBig { type Output = IBig; fn bitand(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.magnitude() & rhs.magnitude()), (Positive, Negative) => IBig::from(self.magnitude().and_not((!rhs).unsigned_abs())), (Negative, Positive) => IBig::from(rhs.magnitude().and_not((!self).unsigned_abs())), (Negative, Negative) => !IBig::from((!self).unsigned_abs() | (!rhs).unsigned_abs()), } } } impl BitAndAssign<IBig> for IBig { fn bitand_assign(&mut self, rhs: IBig) { *self = mem::take(self) & rhs; } } impl BitAndAssign<&IBig> for IBig { fn bitand_assign(&mut self, rhs: &IBig) { *self = mem::take(self) & rhs; } } impl BitOr<IBig> for IBig { type Output = IBig; fn bitor(self, rhs: IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs() | rhs.unsigned_abs()), (Positive, Negative) => !IBig::from((!rhs).unsigned_abs().and_not(self.unsigned_abs())), (Negative, Positive) => !IBig::from((!self).unsigned_abs().and_not(rhs.unsigned_abs())), (Negative, Negative) => !IBig::from((!self).unsigned_abs() & (!rhs).unsigned_abs()), } } } impl BitOr<&IBig> for IBig { type Output = IBig; fn bitor(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs() | rhs.magnitude()), (Positive, Negative) => !IBig::from((!rhs).unsigned_abs().and_not(self.unsigned_abs())), (Negative, Positive) => !IBig::from((!self).unsigned_abs().and_not(rhs.magnitude())), (Negative, Negative) => !IBig::from((!self).unsigned_abs() & (!rhs).unsigned_abs()), } } } impl BitOr<IBig> for &IBig { type Output = IBig; fn bitor(self, rhs: IBig) -> IBig { rhs.bitor(self) } } impl BitOr<&IBig> for &IBig { type Output = IBig; fn bitor(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.magnitude() | rhs.magnitude()), (Positive, Negative) => !IBig::from((!rhs).unsigned_abs().and_not(self.magnitude())), (Negative, Positive) => !IBig::from((!self).unsigned_abs().and_not(rhs.magnitude())), (Negative, Negative) => !IBig::from((!self).unsigned_abs() & (!rhs).unsigned_abs()), } } } impl BitOrAssign<IBig> for IBig { fn bitor_assign(&mut self, rhs: IBig) { *self = mem::take(self) | rhs; } } impl BitOrAssign<&IBig> for IBig { fn bitor_assign(&mut self, rhs: &IBig) { *self = mem::take(self) | rhs; } } impl BitXor<IBig> for IBig { type Output = IBig; fn bitxor(self, rhs: IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs() ^ rhs.unsigned_abs()), (Positive, Negative) => !IBig::from(self.unsigned_abs() ^ (!rhs).unsigned_abs()), (Negative, Positive) => !IBig::from((!self).unsigned_abs() ^ rhs.unsigned_abs()), (Negative, Negative) => IBig::from((!self).unsigned_abs() ^ (!rhs).unsigned_abs()), } } } impl BitXor<&IBig> for IBig { type Output = IBig; fn bitxor(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs() ^ rhs.magnitude()), (Positive, Negative) => !IBig::from(self.unsigned_abs() ^ (!rhs).unsigned_abs()), (Negative, Positive) => !IBig::from((!self).unsigned_abs() ^ rhs.magnitude()), (Negative, Negative) => IBig::from((!self).unsigned_abs() ^ (!rhs).unsigned_abs()), } } } impl BitXor<IBig> for &IBig { type Output = IBig; fn bitxor(self, rhs: IBig) -> IBig { rhs.bitxor(self) } } impl BitXor<&IBig> for &IBig { type Output = IBig; fn bitxor(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.magnitude() ^ rhs.magnitude()), (Positive, Negative) => !IBig::from(self.magnitude() ^ (!rhs).unsigned_abs()), (Negative, Positive) => !IBig::from((!self).unsigned_abs() ^ rhs.magnitude()), (Negative, Negative) => IBig::from((!self).unsigned_abs() ^ (!rhs).unsigned_abs()), } } } impl BitXorAssign<IBig> for IBig { fn bitxor_assign(&mut self, rhs: IBig) { *self = mem::take(self) ^ rhs; } } impl BitXorAssign<&IBig> for IBig { fn bitxor_assign(&mut self, rhs: &IBig) { *self = mem::take(self) ^ rhs; } } impl AndNot<IBig> for IBig { type Output = IBig; fn and_not(self, rhs: IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs().and_not(rhs.unsigned_abs())), (Positive, Negative) => IBig::from(self.unsigned_abs() & (!rhs).unsigned_abs()), (Negative, Positive) => !IBig::from((!self).unsigned_abs() | rhs.unsigned_abs()), (Negative, Negative) => { IBig::from((!rhs).unsigned_abs().and_not((!self).unsigned_abs())) } } } } impl AndNot<&IBig> for IBig { type Output = IBig; fn and_not(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.unsigned_abs().and_not(rhs.magnitude())), (Positive, Negative) => IBig::from(self.unsigned_abs() & (!rhs).unsigned_abs()), (Negative, Positive) => !IBig::from((!self).unsigned_abs() | rhs.magnitude()), (Negative, Negative) => { IBig::from((!rhs).unsigned_abs().and_not((!self).unsigned_abs())) } } } } impl AndNot<IBig> for &IBig { type Output = IBig; fn and_not(self, rhs: IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.magnitude().and_not(rhs.unsigned_abs())), (Positive, Negative) => IBig::from(self.magnitude() & (!rhs).unsigned_abs()), (Negative, Positive) => !IBig::from((!self).unsigned_abs() | rhs.unsigned_abs()), (Negative, Negative) => { IBig::from((!rhs).unsigned_abs().and_not((!self).unsigned_abs())) } } } } impl AndNot<&IBig> for &IBig { type Output = IBig; fn and_not(self, rhs: &IBig) -> IBig { match (self.sign(), rhs.sign()) { (Positive, Positive) => IBig::from(self.magnitude().and_not(rhs.magnitude())), (Positive, Negative) => IBig::from(self.magnitude() & (!rhs).unsigned_abs()), (Negative, Positive) => !IBig::from((!self).unsigned_abs() | rhs.magnitude()), (Negative, Negative) => { IBig::from((!rhs).unsigned_abs().and_not((!self).unsigned_abs())) } } } } impl UBig { /// low n bits or'd pub(crate) fn are_low_bits_nonzero(&self, n: usize) -> bool { match self.repr() { Small(word) => { let n = n.min(WORD_BITS_USIZE) as u32; word & math::ones::<Word>(n) != 0 } Large(buffer) => { let n_words = n / WORD_BITS_USIZE; if n_words >= buffer.len() { true } else { let n_top = (n % WORD_BITS_USIZE) as u32; buffer[..n_words].iter().any(|x| *x != 0) || buffer[n_words] & math::ones::<Word>(n_top) != 0 } } } } }
Dust core unit-tests ------------------------ core tests run on node, use the following command node test/server.js Dust unit-tests using jasmine ----------------------------- In the current distribution of dust, we have unit tests in jasmine for both the client and the nodejs version. If you want to run the client version just open the html page called specRunner.html located in test/jasmine-test/client/specRunner.html Pre-requisites for tests on node server version: ---------------------------------- * install nodejs 0.6 or greater * install npm * install jasmine test framework : npm install -g jasmine-node In order to run the node.js version of dust, run this command in the terminal node test/jasmine-test/server/specRunner.js Run tests with make ------------------- * core unit tests: make test * jasmine unit test make jasmine Note: the above commands has to be run in the project root folder. Code coverage report ----------------------------- We are using a tool called node-cover, it can be installed by npm with the following command: npm install cover -g Once you have installed cover, you can use it to generate the code coverage results Run Cover -------------- cover run test/jasmine-test/server/specRunner.js // runs all the test and creates a folder with results. cover report // shows you a table with % code covered, missed lines, #lines, %blocks, missed blocks and # blocks. cover report html //creates a folder the location where you run the command and the report is in html. Cover creates one html file per js file used by the test. The lines that are not covered are shown on red.
<!-- Id Field --> <div class="col-md-12"> {!! Form::label('id', 'Id:') !!} <p>{!! $product->id !!}</p> </div> <!-- Company Id Field --> <div class="col-md-12"> {!! Form::label('company_id', 'Company Id:') !!} <p>{!! $product->company_id !!}</p> </div> <!-- Code Field --> <div class="col-md-12"> {!! Form::label('code', 'Code:') !!} <p>{!! $product->code !!}</p> </div> <!-- Description Field --> <div class="col-md-12"> {!! Form::label('description', 'Description:') !!} <p>{!! $product->description !!}</p> </div> <!-- Status Field --> <div class="col-md-12"> {!! Form::label('status', 'Status:') !!} <p>{!! $product->status !!}</p> </div> <!-- Product Type Code Field --> <div class="col-md-12"> {!! Form::label('product_type_code', 'Product Type Code:') !!} <p>{!! $product->product_type_code !!}</p> </div> <!-- Group Code Field --> <div class="col-md-12"> {!! Form::label('group_code', 'Group Code:') !!} <p>{!! $product->group_code !!}</p> </div> <!-- Subgroup Code Field --> <div class="col-md-12"> {!! Form::label('subgroup_code', 'Subgroup Code:') !!} <p>{!! $product->subgroup_code !!}</p> </div> <!-- Margin Div Field --> <div class="col-md-12"> {!! Form::label('margin_div', 'Margin Div:') !!} <p>{!! $product->margin_div !!}</p> </div> <!-- Cost Field --> <div class="col-md-12"> {!! Form::label('cost', 'Cost:') !!} <p>{!! $product->cost !!}</p> </div> <!-- Phase Code Field --> <div class="col-md-12"> {!! Form::label('phase_code', 'Phase Code:') !!} <p>{!! $product->phase_code !!}</p> </div> <!-- Abz Code Field --> <div class="col-md-12"> {!! Form::label('abz_code', 'Abz Code:') !!} <p>{!! $product->abz_code !!}</p> </div> <!-- Inventory Date Field --> <div class="col-md-12"> {!! Form::label('inventory_date', 'Inventory Date:') !!} <p>{!! $product->inventory_date !!}</p> </div> <!-- Due Date Field --> <div class="col-md-12"> {!! Form::label('due_date', 'Due Date:') !!} <p>{!! $product->due_date !!}</p> </div> <!-- Critical Date1 Field --> <div class="col-md-12"> {!! Form::label('critical_date1', 'Critical Date1:') !!} <p>{!! $product->critical_date1 !!}</p> </div> <!-- Critical Date2 Field --> <div class="col-md-12"> {!! Form::label('critical_date2', 'Critical Date2:') !!} <p>{!! $product->critical_date2 !!}</p> </div> <!-- Critical Date3 Field --> <div class="col-md-12"> {!! Form::label('critical_date3', 'Critical Date3:') !!} <p>{!! $product->critical_date3 !!}</p> </div> <!-- Ripeness Date Field --> <div class="col-md-12"> {!! Form::label('ripeness_date', 'Ripeness Date:') !!} <p>{!! $product->ripeness_date !!}</p> </div> <!-- Obs1 Field --> <div class="col-md-12"> {!! Form::label('obs1', 'Obs1:') !!} <p>{!! $product->obs1 !!}</p> </div> <!-- Obs2 Field --> <div class="col-md-12"> {!! Form::label('obs2', 'Obs2:') !!} <p>{!! $product->obs2 !!}</p> </div> <!-- Obs3 Field --> <div class="col-md-12"> {!! Form::label('obs3', 'Obs3:') !!} <p>{!! $product->obs3 !!}</p> </div> <!-- Obs4 Field --> <div class="col-md-12"> {!! Form::label('obs4', 'Obs4:') !!} <p>{!! $product->obs4 !!}</p> </div> <!-- Obs5 Field --> <div class="col-md-12"> {!! Form::label('obs5', 'Obs5:') !!} <p>{!! $product->obs5 !!}</p> </div> <!-- Created At Field --> <div class="col-md-12"> {!! Form::label('created_at', 'Created At:') !!} <p>{!! $product->created_at !!}</p> </div> <!-- Updated At Field --> <div class="col-md-12"> {!! Form::label('updated_at', 'Updated At:') !!} <p>{!! $product->updated_at !!}</p> </div>
**Deprecation Notice:** I've switched from this repo to deploying static sites on S3 and Cloudfront. dock0/nginx ======= [![Automated Build](https://img.shields.io/docker/build/dock0/nginx.svg)](https://hub.docker.com/r/dock0/nginx/) [![Build Status](https://img.shields.io/travis/com/dock0/nginx.svg)](https://travis-ci.com/dock0/nginx) [![MIT Licensed](http://img.shields.io/badge/license-MIT-green.svg)](https://tldrlegal.com/license/mit-license) Base nginx container, used as a base for my various sites. ## License This repo is released under the MIT License. See the bundled LICENSE file for details.
import React from 'react'; import './Arrecode.css'; import './wordsPosition.css'; const Arrecode = () => { return ( <div className="principal"> <div className="containerArrecode"> <span id="a" className="principal_word" >a</span> <span id="r1" className="principal_word">r</span> <span id="r2" className="principal_word">r</span> <span id="e1" className="principal_word">e</span> <span id="openBr" className="principal_word">[</span> <span id="c" className="principal_word code">c</span> <span id="o" className="principal_word code">o</span> <span id="d" className="principal_word code">d</span> <span id="e2" className="principal_word code">e</span> <span id="closeBr" className="principal_word">]</span> <span id="x" className="axel ">x</span> <span id="e" className="axel ">e</span> <span id="l" className="axel ">l</span> <span id="e" className="rene ">e</span> <span id="n" className="rene ">n</span> <span id="e2" className="rene ">é</span> <span id="reneShape"></span> <span id="o" className="romero ">o</span> <span id="m" className="romero ">m</span> <span id="e" className="romero ">e</span> <span id="r" className="romero ">r</span> <span id="o2" className="romero ">o</span> <span id="s" className="esquivel ">s</span> <span id="q" className="esquivel ">q</span> <span id="u" className="esquivel ">u</span> <span id="i" className="esquivel ">i</span> <span id="v" className="esquivel ">v</span> <span id="e" className="esquivel ">e</span> <span id="l" className="esquivel ">l</span> <span id="esquivelShape"></span> <span id="fullstack"><i>Fullstack Web</i></span> <span id="andand"><i>&&</i></span> <span id="software"><i>Python Developer</i></span> </div> </div> ) } export default Arrecode
<?php namespace Electro\WebServer\Config; use Electro\Interfaces\DI\InjectorInterface; use Electro\Interfaces\Http\MiddlewareAssemblerInterface; use Electro\Interfaces\KernelInterface; use Electro\Interfaces\ModuleInterface; use Electro\Kernel\Lib\ModuleInfo; use Electro\Profiles\ApiProfile; use Electro\Profiles\WebProfile; use Electro\WebServer\DefaultMiddlewareAssembler; use Electro\WebServer\WebServer; class WebServerModule implements ModuleInterface { static function getCompatibleProfiles () { return [WebProfile::class, ApiProfile::class]; } static function startUp (KernelInterface $kernel, ModuleInfo $moduleInfo) { $kernel ->onRegisterServices ( function (InjectorInterface $injector) { $injector ->share (WebServer::class) // The middleware assembler may be overridden later, usually by a private application module. ->alias (MiddlewareAssemblerInterface::class, DefaultMiddlewareAssembler::class); }) // Create the PSR-7 ServerRequest ->onConfigure (function (WebServer $webServer) { $webServer->setup (); }) // ->onRun (function (WebServer $webServer) { $webServer->run (); }); } }
import * as _ from 'lodash'; import code from './code'; import remove from './remove'; import list from './list'; import report from './report'; import allow from './allow'; import deny from './deny'; import owner from './owner'; import help from './help'; import lock from './lock'; import unlock from './unlock'; type smsHandler = (to: string, from: string, args: string[], message: string) => Promise<string>; const commands: { [cmd: string]: smsHandler } = { code, remove, list, report, allow, deny, owner, help, lock, unlock, }; /** * Handles an incoming SMS. * * @param {string} to The number that received the sms (the callbox handler) * @param {string} from The number that sent the sms (the manager or permitted user) * @param {string} message The SMS command */ export default async function handleSms(to: string, from: string, message: string): Promise<string> { let parts: string[] = message.trim().split(' '); parts = _.filter(_.map(parts, p => p.trim())); parts[0] = parts[0].toLowerCase(); let cmd: smsHandler; if (commands.hasOwnProperty(parts[0])) { cmd = commands[parts[0]]; } else { cmd = help; } return cmd(to, from, parts, message); }
% The "AlfTheHawk" Program % ALF THE HAWK % The program controls two infrared receivers and one stepper % motor. The IR receivers react, in this case, to light from a. % flashlight As light is shone in one receiver the motor turns % clockwise. When light is shone in the other receiver the % motor turns counter-clockwise. If no light is present the % motor continually scans through 180 degrees. % If light is shone into both receivers the motor stops. % % The receivers are set up as "eyes" in a paper-mache hawk % resembling the TV character Alf. The hawk scans through 180 % degrees looking for light. When light is sensed the hawk % follows the light. When the exit button on the screen is % clicked with the mouse the program is terminated and the hawk % returns to the home position. % % The following chart indicates the parallelget values assigned % by a specific computer for input pins 10 and 11. % % pin number open/closed parallelget % 10 & 11 both open 127 % 10 10 closed 63 % 11 11 closed 255 % 10 & 11 both closed 191 % % The motor has four steps controlled by pins 2, 3, 4, and 5 % using parallelput(2 ** counter) where counter loops through % the whole numbers 0, 1, 2, and 3. setscreen ("graphics") % Outputs the value. procedure OutputValue (value : int) locate (maxrow div 2 + 5, maxcol div 2 - 8) colour (cyan) put "Value = " .. colour (brightblue) put value end OutputValue % Hides the mouse. procedure Hide mousehide locate (maxrow div 2 + 8, maxcol div 2 - 8) colour (white) put repeat (" ", 20) end Hide % Outputs the degrees. procedure OutputDegree (degrees : int) locate (maxrow div 2 + 6, maxcol div 2 - 10) colour (cyan) put "Degrees = " .. colour (brightblue) put degrees, " " end OutputDegree % Outputs the direction. procedure OutputDirection (direction : string) locate (maxrow div 2 + 7, maxcol div 2 - 12) colour (cyan) put "Direction = " .. colour (brightblue) put direction if direction = "Clockwise" then drawfill (190, 310, blue, cyan) drawfill (400, 310, white, cyan) drawfilloval (300, 310, 30, 30, green) elsif direction = "Counter Clockwise" then drawfill (400, 310, blue, cyan) drawfill (200, 310, white, cyan) drawfilloval (300, 310, 30, 30, green) else drawfill (400, 310, white, cyan) drawfill (200, 310, white, cyan) drawfilloval (300, 310, 30, 30, red) end if end OutputDirection % Draws the arrows. procedure DrawGraphicsArrows % Draws clockwise arrow. drawarc (200, 200, 100, 100, 90, 180, cyan) drawarc (200, 200, 120, 120, 90, 180, cyan) drawline (80, 201, 100, 201, cyan) drawline (200, 320, 200, 340, cyan) drawline (200, 300, 200, 280, cyan) drawline (230, 310, 200, 340, cyan) drawline (230, 310, 200, 280, cyan) % Draws counter-clockwise arrow. drawarc (400, 200, 100, 100, 0, 90, cyan) drawarc (400, 200, 120, 120, 0, 90, cyan) drawline (500, 200, 520, 200, cyan) drawline (400, 320, 400, 340, cyan) drawline (400, 300, 400, 280, cyan) drawline (370, 310, 400, 340, cyan) drawline (370, 310, 400, 280, cyan) end DrawGraphicsArrows % Draws the title. procedure DrawGraphicsTitle % Advanced programmers may want to use Turing's Font module. % Draws the box and the shadow. drawfillbox (145, 345, 475, 395, blue) drawbox (145, 345, 475, 395, yellow) drawfillbox (150, 340, 480, 390, brightblue) drawbox (150, 340, 480, 390, yellow) % Draws the "T". drawline (155, 385, 185, 385, yellow) drawline (170, 385, 170, 345, yellow) % Draws the "H". drawline (200, 385, 200, 345, yellow) drawline (230, 385, 230, 345, yellow) drawline (200, 365, 230, 365, yellow) % Draws the "E". drawline (245, 385, 245, 345, yellow) drawline (245, 385, 275, 385, yellow) drawline (245, 345, 275, 345, yellow) drawline (245, 365, 275, 365, yellow) % Draws the "H". drawline (310, 385, 310, 345, yellow) drawline (310, 365, 340, 365, yellow) drawline (340, 385, 340, 345, yellow) % Draws the "A". drawline (355, 365, 355, 345, yellow) drawline (385, 365, 385, 345, yellow) drawline (355, 365, 385, 365, yellow) drawline (355, 365, 370, 385, yellow) drawline (385, 365, 370, 385, yellow) % Draws the "W". drawline (400, 385, 400, 345, yellow) drawline (400, 345, 415, 365, yellow) drawline (415, 365, 430, 345, yellow) drawline (430, 345, 430, 385, yellow) % Draws the "K". drawline (445, 345, 445, 385, yellow) drawline (445, 365, 475, 385, yellow) drawline (445, 365, 475, 345, yellow) end DrawGraphicsTitle % Draws the exit sign. procedure DrawGraphicsExitSign % Draws the box and the shadow. drawfillbox (635, 5, 570, 40, blue) drawbox (635, 5, 570, 40, yellow) drawfillbox (639, 0, 575, 35, brightblue) drawbox (639, 0, 575, 35, yellow) % Draws the "E". drawline (580, 5, 580, 30, yellow) drawline (580, 5, 590, 5, yellow) drawline (580, 30, 590, 30, yellow) drawline (580, 18, 590, 18, yellow) % Draws the "X". drawline (595, 30, 605, 5, yellow) drawline (605, 30, 595, 5, yellow) % Draws the "I". drawline (612, 30, 612, 5, yellow) % Draws the "T". drawline (625, 30, 625, 5, yellow) drawline (618, 30, 632, 30, yellow) end DrawGraphicsExitSign % Returns to starting position. procedure ReturnToHomePosition (var degrees, value : int) OutputDirection ("Counter Clockwise") value := parallelget OutputValue (value) if degrees > 0 then loop for decreasing count : 3 .. 0 parallelput (2 ** count) delay (50) degrees -= 2 OutputDegree (degrees) end for exit when degrees <= 0 end loop end if end ReturnToHomePosition % Detects to see if the 3D button was pushed. If it was, this % procedure returns Alf to the home position and sets flag = 1. procedure CheckForQuit (var degrees, value, flag : int) var xmouse, ymouse, button : int mousewhere (xmouse, ymouse, button) if 575 <= xmouse and xmouse <= 639 and 0 <= ymouse and ymouse <= 35 and button = 1 then Hide drawfillbox (570, 40, maxx, 0, white) flag := 1 color (darkgray) locate (maxrow - 1, 1) put "Please wait while the hawk returns home." ReturnToHomePosition (degrees, value) end if end CheckForQuit % When light is shone in Alf's right eye, he rotates % clockwise until light is acquired in both eyes. procedure RotateClockwise (var degrees, value, flag : int) value := parallelget OutputValue (value) OutputDirection ("Clockwise") loop CheckForQuit (degrees, value, flag) for count : 0 .. 3 parallelput (2 ** count) delay (70) value := parallelget OutputValue (value) degrees += 2 OutputDegree (degrees) end for exit when value = 127 or value = 191 or value = 255 end loop end RotateClockwise % When light is shone in Alf's left eye, he rotates counter- % clockwise until light is acquired in both eyes. procedure RotateCounterClockwise (var degrees, value, flag : int) value := parallelget OutputValue (value) OutputDirection ("Counter-Clockwise") loop CheckForQuit (degrees, value, flag) for decreasing count : 3 .. 0 parallelput (2 ** count) delay (70) value := parallelget OutputValue (value) degrees -= 2 OutputDegree (degrees) end for exit when value = 127 or value = 191 or value = 63 end loop end RotateCounterClockwise % When light is shone in both eyes, Alf stops. procedure StopRotation parallelput (0) OutputDirection ("Stopped") end StopRotation % This procedure scans back and forth through the 180 degree % arc until a light is acquired in Alf's eyes. procedure ScanForLight (var degrees, value, flag : int) var xmouse, ymouse, button : int value := parallelget OutputValue (value) mousewhere (xmouse, ymouse, button) loop OutputDirection ("Clockwise") loop CheckForQuit (degrees, value, flag) % This for loop runs through the sequence of steps to % turn the stepper motor clockwise. for count : 0 .. 3 parallelput (2 ** count) delay (70) value := parallelget OutputValue (value) degrees += 2 OutputDegree (degrees) end for exit when degrees >= 180 or value not= 127 or flag = 1 end loop exit when value not= 127 or flag = 1 loop OutputDirection ("Counter Clockwise") % This for loop runs through the sequence of steps % required to turn the stepper motor counter-clockwise. loop CheckForQuit (degrees, value, flag) for decreasing count : 3 .. 0 parallelput (2 ** count) delay (70) value := parallelget OutputValue (value) degrees -= 2 OutputDegree (degrees) end for exit when degrees <= 4 or value not= 127 or flag = 1 end loop if button = 1 and xmouse > 100 and xmouse < 300 and ymouse > 100 and ymouse < 300 then CheckForQuit (degrees, value, flag) end if exit when degrees <= 0 or value not= 127 or flag = 1 end loop exit when value not= 127 or flag = 1 end loop end ScanForLight % Main program var degrees, value, flag : int var xmouse, ymouse, button : int cls degrees := 0 OutputDegree (degrees) flag := 0 color (cyan) DrawGraphicsArrows OutputDirection ("Stopped") DrawGraphicsExitSign DrawGraphicsTitle loop mousewhere (xmouse, ymouse, button) value := parallelget OutputValue (value) CheckForQuit (degrees, value, flag) if value = 127 then ScanForLight (degrees, value, flag) elsif value = 63 then RotateClockwise (degrees, value, flag) elsif value = 255 then RotateCounterClockwise (degrees, value, flag) elsif value = 191 then StopRotation end if if value = 127 and degrees > 0 then ReturnToHomePosition (degrees, value) end if exit when flag = 1 end loop Hide degrees := 0 OutputDegree (degrees) OutputDirection ("Stopped") parallelput (0)
describe Spaceship::ConnectAPI::AppStoreVersion do before { Spaceship::Tunes.login } describe "AppStoreVersion object" do describe "reverse maps attributes" do let(:app_store_version) { Spaceship::ConnectAPI::AppStoreVersion.new('id', {}) } let(:attribute_attributes) do { contact_first_name: "", contact_last_name: "", contact_phone: "", contact_email: "", demo_account_name: "", demo_account_password: "", demo_account_required: "", notes: "" } end it "maps attributes names to API names" do resp = double allow(resp).to receive(:to_models).and_return([]) expect(Spaceship::ConnectAPI).to receive(:post_app_store_review_detail).with(app_store_version_id: 'id', attributes: { "contactFirstName" => "", "contactLastName" => "", "contactPhone" => "", "contactEmail" => "", "demoAccountName" => "", "demoAccountPassword" => "", "demoAccountRequired" => "", "notes" => "" }).and_return(resp) app_store_version.create_app_store_review_detail(attributes: attribute_attributes) end end end end
# Globals [Bancor SDK](./) › [Globals](globals.md) ## Bancor SDK ### Index #### Enumerations * [BlockchainType](enums/blockchaintype.md) #### Classes * [History](classes/history.md) * [Pricing](classes/pricing.md) * [SDK](classes/sdk.md) * [Utils](classes/utils.md) #### Interfaces * [ConversionEvent](interfaces/conversionevent.md) * [Converter](interfaces/converter.md) * [Settings](interfaces/settings.md) * [Token](interfaces/token.md)
import { CalendarProps as CP } from "react-calendar"; import { Omit } from "utility-types"; interface TileDot { timeStamp?: number | Date; colors?: string[]; } interface CommonCalendarProps extends Omit<CP, "onChange"> { hideShadow?: boolean; className?: string; onClear?: () => void; tileDots: TileDot[]; disabledDays?: Array<number | Date>; } export interface DateSingle extends CommonCalendarProps { range?: false; selected?: Date; onChange: (value: Date) => void; onApply?: (value?: Date) => void; } export interface DateRange extends CommonCalendarProps { range: true; maxRange?: number; // number of days selected?: [Date, Date]; onChange: (value: [Date, Date]) => void; onApply?: (value?: [Date, Date]) => void; } export type CalendarProps = DateSingle | DateRange; export interface CalendarState { value?: [Date, Date] | Date; singleSelectedDate?: [Date, Date] | null; maxRangeDates?: { future: Date; past: Date; }; }
val artifactIdVal = "dag-command" val versionVal = "1.5.3" val publicationName="dagCommand" group = "com.github.leandroborgesferreira" version = versionVal fun getNexusUserName(): String? = System.getenv("SONATYPE_NEXUS_USERNAME") fun getNexusPassword(): String? = System.getenv("SONATYPE_NEXUS_PASSWORD") plugins { kotlin("jvm") version ("1.3.72") id("java-gradle-plugin") id("maven-publish") signing `maven-publish` id("io.codearte.nexus-staging") version ("0.21.2") } java { withJavadocJar() withSourcesJar() } repositories { mavenCentral() } dependencies { implementation(kotlin("stdlib-jdk8")) implementation("com.google.code.gson:gson:2.8.6") testImplementation("org.jetbrains.kotlin:kotlin-test-junit") testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0") testImplementation("org.mockito:mockito-core:3.3.3") } gradlePlugin { plugins { register(rootProject.name) { id = "$group.$artifactIdVal" displayName = "Unit tests following the DAG" description = "Unit tests only the changed modules in the dependencies graph" implementationClass = "$group.dagcommand.DagCommandPlugin" } } } nexusStaging { username = getNexusUserName() password = getNexusPassword() } publishing { publications { create<MavenPublication>(publicationName) { groupId = group.toString() artifactId = artifactIdVal version = versionVal from(components["java"]) pom { name.set("Dag Command") description.set("Affected gradle modules by branch") url.set("https://github.com/leandroBorgesFerreira/dag-command/") packaging = "jar" licenses { license { name.set("The Apache License, Version 2.0") url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") } } developers { developer { id.set("leandroBorgesFerreira") name.set("Leandro Borges Ferreira") email.set("lehen01@gmail.com") } } scm { connection.set("scm:git:git://github.com/leandroBorgesFerreira/dag-command.git") developerConnection.set("scm:git:ssh://github.com/leandroBorgesFerreira/dag-command.git") url.set("https://github.com/leandroBorgesFerreira/dag-command") } } } } repositories { maven { credentials { username = getNexusUserName() password = getNexusPassword() } val releasesRepoUrl = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2") val snapshotsRepoUrl = uri("https://oss.sonatype.org/content/repositories/snapshots") url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl } } } signing { sign(publishing.publications[publicationName]) }
namespace StirlingLabs.LsQuic.Native { public unsafe partial struct lsquic_out_spec { [NativeTypeName("struct iovec *")] public iovec* iov; [NativeTypeName("size_t")] public nuint iovlen; [NativeTypeName("const struct sockaddr *")] public sockaddr* local_sa; [NativeTypeName("const struct sockaddr *")] public sockaddr* dest_sa; public void* peer_ctx; [NativeTypeName("lsquic_conn_ctx_t *")] public lsquic_conn_ctx* conn_ctx; public int ecn; } }
# frozen_string_literal: true module Faker class Aircraft < Base class << self # Generates random aircraft manufacturer # # @return [String] a manufacturer of aircrafts def manufacturer fetch('aircraft.manufacturer') end # Generates a random model of aircraft based on a manufacturer # # @param [String] manufacturer_of_model The specific manufacturer # Uses a random manufacturer if not provided # # @return [String] a model of aircraft def model(manufacturer_of_model = '') manufacturer_of_model = manufacturer if manufacturer_of_model.empty? fetch("aircraft.model_by_manufacturer.#{manufacturer_of_model}") end # Generates a random aircraft prefix # # @return [String] a prefix def prefix regexify(bothify(fetch('aircraft.prefix'))) end # Generates a random airline name # # @return [String] an airline def airline fetch('aircraft.airline') end end end end
<?php namespace App\Repositories\Posts; use Exception; use Illuminate\Support\Facades\Http; class PostsRepository implements PostsRepositoryInterface { public function get(string $url): object { $response = Http::get($url); if ($response->failed()) { throw new Exception($response->status()); } return (object)$response->object(); } public function find(string $url, int $id): object { $response = Http::get($url . $id); if ($response->failed()) { throw new Exception($response->status()); } return (object)$response->object(); } }
package elementary.pipeline import akka.stream.{ActorMaterializer, OverflowStrategy} import akka.stream.scaladsl.{Source, Sink, FlowGraph, Broadcast, Merge, Flow, RunnableGraph, Keep} import elementary.util.common.Communication._ import elementary.pipeline.PipeCommunication._ import elementary.pipeline.analysis.AnalysisPipeline import elementary.pipeline.extraction.ExtractionPipeline import elementary.pipeline.ranking.RankingPipeline import elementary.pipeline.answer.AnswerPipeline import elementary.pipeline.candidates.CandidatePipeline object RootPipeline { val reporter = StatisticsActor.get // init databases (might make optional) elementary.util.data.Transcript.client val flow = Flow() { implicit b => import FlowGraph.Implicits._ val bcast = b.add(Broadcast[QueryRef](1)) val merge = b.add(Merge[AnswerRef](1)) val reportFlow = Flow[QueryRef].map(q => { reporter ! ProcessReportMessage(q.id, "insert", pipeline.build.BuildInfo.toJson, System.currentTimeMillis) q }) bcast ~> reportFlow ~> AnalysisPipeline.flow ~> ExtractionPipeline.flow ~> CandidatePipeline.flow ~> RankingPipeline.flow ~> AnswerPipeline.flow ~> merge (bcast.in, merge.out) } }
// Copyright 2015-2021 Swim.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 type {Mutable, Proto, ObserverType} from "@swim/util"; import type {FastenerOwner, FastenerFlags} from "@swim/component"; import type {AnyModel, Model} from "./Model"; import {ModelRelationInit, ModelRelationClass, ModelRelation} from "./ModelRelation"; /** @internal */ export type ModelSetType<F extends ModelSet<any, any>> = F extends ModelSet<any, infer M> ? M : never; /** @public */ export interface ModelSetInit<M extends Model = Model> extends ModelRelationInit<M> { extends?: {prototype: ModelSet<any, any>} | string | boolean | null; key?(model: M): string | undefined; compare?(a: M, b: M): number; sorted?: boolean; willSort?(parent: Model | null): void; didSort?(parent: Model | null): void; sortChildren?(parent: Model): void; compareChildren?(a: Model, b: Model): number; } /** @public */ export type ModelSetDescriptor<O = unknown, M extends Model = Model, I = {}> = ThisType<ModelSet<O, M> & I> & ModelSetInit<M> & Partial<I>; /** @public */ export interface ModelSetClass<F extends ModelSet<any, any> = ModelSet<any, any>> extends ModelRelationClass<F> { /** @internal */ readonly SortedFlag: FastenerFlags; /** @internal @override */ readonly FlagShift: number; /** @internal @override */ readonly FlagMask: FastenerFlags; } /** @public */ export interface ModelSetFactory<F extends ModelSet<any, any> = ModelSet<any, any>> extends ModelSetClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ModelSetFactory<F> & I; define<O, M extends Model = Model>(className: string, descriptor: ModelSetDescriptor<O, M>): ModelSetFactory<ModelSet<any, M>>; define<O, M extends Model = Model>(className: string, descriptor: {observes: boolean} & ModelSetDescriptor<O, M, ObserverType<M>>): ModelSetFactory<ModelSet<any, M>>; define<O, M extends Model = Model, I = {}>(className: string, descriptor: {implements: unknown} & ModelSetDescriptor<O, M, I>): ModelSetFactory<ModelSet<any, M> & I>; define<O, M extends Model = Model, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ModelSetDescriptor<O, M, I & ObserverType<M>>): ModelSetFactory<ModelSet<any, M> & I>; <O, M extends Model = Model>(descriptor: ModelSetDescriptor<O, M>): PropertyDecorator; <O, M extends Model = Model>(descriptor: {observes: boolean} & ModelSetDescriptor<O, M, ObserverType<M>>): PropertyDecorator; <O, M extends Model = Model, I = {}>(descriptor: {implements: unknown} & ModelSetDescriptor<O, M, I>): PropertyDecorator; <O, M extends Model = Model, I = {}>(descriptor: {implements: unknown; observes: boolean} & ModelSetDescriptor<O, M, I & ObserverType<M>>): PropertyDecorator; } /** @public */ export interface ModelSet<O = unknown, M extends Model = Model> extends ModelRelation<O, M> { (model: AnyModel<M>): O; /** @override */ get fastenerType(): Proto<ModelSet<any, any>>; /** @internal */ readonly models: {readonly [modelId: number]: M | undefined}; readonly modelCount: number; hasModel(model: Model): boolean; addModel(model?: AnyModel<M>, target?: Model | null, key?: string): M; attachModel(model?: AnyModel<M>, target?: Model | null): M; detachModel(model: M): M | null; insertModel(parent?: Model | null, model?: AnyModel<M>, target?: Model | null, key?: string): M; removeModel(model: M): M | null; deleteModel(model: M): M | null; /** @internal @override */ bindModel(model: Model, target: Model | null): void; /** @internal @override */ unbindModel(model: Model): void; /** @override */ detectModel(model: Model): M | null; /** @internal @protected */ key(model: M): string | undefined; get sorted(): boolean; /** @internal */ initSorted(sorted: boolean): void; sort(sorted?: boolean): this; /** @protected */ willSort(parent: Model | null): void; /** @protected */ onSort(parent: Model | null): void; /** @protected */ didSort(parent: Model | null): void; /** @internal @protected */ sortChildren(parent: Model): void; /** @internal */ compareChildren(a: Model, b: Model): number; /** @internal @protected */ compare(a: M, b: M): number; } /** @public */ export const ModelSet = (function (_super: typeof ModelRelation) { const ModelSet: ModelSetFactory = _super.extend("ModelSet"); Object.defineProperty(ModelSet.prototype, "fastenerType", { get: function (this: ModelSet): Proto<ModelSet<any, any>> { return ModelSet; }, configurable: true, }); ModelSet.prototype.hasModel = function (this: ModelSet, model: Model): boolean { return this.models[model.uid] !== void 0; }; ModelSet.prototype.addModel = function <M extends Model>(this: ModelSet<unknown, M>, newModel?: AnyModel<M>, target?: Model | null, key?: string): M { if (newModel !== void 0 && newModel !== null) { newModel = this.fromAny(newModel); } else { newModel = this.createModel(); } if (target === void 0) { target = null; } let parent: Model | null; if (this.binds && (parent = this.parentModel, parent !== null)) { if (key === void 0) { key = this.key(newModel); } this.insertChild(parent, newModel, target, key); } const models = this.models as {[modelId: number]: M | undefined}; if (models[newModel.uid] === void 0) { this.willAttachModel(newModel, target); models[newModel.uid] = newModel; (this as Mutable<typeof this>).modelCount += 1; this.onAttachModel(newModel, target); this.initModel(newModel); this.didAttachModel(newModel, target); } return newModel; }; ModelSet.prototype.attachModel = function <M extends Model>(this: ModelSet<unknown, M>, newModel?: AnyModel<M>, target?: Model | null): M { if (newModel !== void 0 && newModel !== null) { newModel = this.fromAny(newModel); } else { newModel = this.createModel(); } const models = this.models as {[modelId: number]: M | undefined}; if (models[newModel.uid] === void 0) { if (target === void 0) { target = null; } this.willAttachModel(newModel, target); models[newModel.uid] = newModel; (this as Mutable<typeof this>).modelCount += 1; this.onAttachModel(newModel, target); this.initModel(newModel); this.didAttachModel(newModel, target); } return newModel; }; ModelSet.prototype.detachModel = function <M extends Model>(this: ModelSet<unknown, M>, oldModel: M): M | null { const models = this.models as {[modelId: number]: M | undefined}; if (models[oldModel.uid] !== void 0) { this.willDetachModel(oldModel); (this as Mutable<typeof this>).modelCount -= 1; delete models[oldModel.uid]; this.onDetachModel(oldModel); this.deinitModel(oldModel); this.didDetachModel(oldModel); return oldModel; } return null; }; ModelSet.prototype.insertModel = function <M extends Model>(this: ModelSet<unknown, M>, parent?: Model | null, newModel?: AnyModel<M>, target?: Model | null, key?: string): M { if (newModel !== void 0 && newModel !== null) { newModel = this.fromAny(newModel); } else { newModel = this.createModel(); } if (parent === void 0 || parent === null) { parent = this.parentModel; } if (target === void 0) { target = null; } if (key === void 0) { key = this.key(newModel); } if (parent !== null && (newModel.parent !== parent || newModel.key !== key)) { this.insertChild(parent, newModel, target, key); } const models = this.models as {[modelId: number]: M | undefined}; if (models[newModel.uid] === void 0) { this.willAttachModel(newModel, target); models[newModel.uid] = newModel; (this as Mutable<typeof this>).modelCount += 1; this.onAttachModel(newModel, target); this.initModel(newModel); this.didAttachModel(newModel, target); } return newModel; }; ModelSet.prototype.removeModel = function <M extends Model>(this: ModelSet<unknown, M>, model: M): M | null { if (this.hasModel(model)) { model.remove(); return model; } return null; }; ModelSet.prototype.deleteModel = function <M extends Model>(this: ModelSet<unknown, M>, model: M): M | null { const oldModel = this.detachModel(model); if (oldModel !== null) { oldModel.remove(); } return oldModel; }; ModelSet.prototype.bindModel = function <M extends Model>(this: ModelSet<unknown, M>, model: Model, target: Model | null): void { if (this.binds) { const newModel = this.detectModel(model); const models = this.models as {[modelId: number]: M | undefined}; if (newModel !== null && models[newModel.uid] === void 0) { this.willAttachModel(newModel, target); models[newModel.uid] = newModel; (this as Mutable<typeof this>).modelCount += 1; this.onAttachModel(newModel, target); this.initModel(newModel); this.didAttachModel(newModel, target); } } }; ModelSet.prototype.unbindModel = function <M extends Model>(this: ModelSet<unknown, M>, model: Model): void { if (this.binds) { const oldModel = this.detectModel(model); const models = this.models as {[modelId: number]: M | undefined}; if (oldModel !== null && models[oldModel.uid] !== void 0) { this.willDetachModel(oldModel); (this as Mutable<typeof this>).modelCount -= 1; delete models[oldModel.uid]; this.onDetachModel(oldModel); this.deinitModel(oldModel); this.didDetachModel(oldModel); } } }; ModelSet.prototype.detectModel = function <M extends Model>(this: ModelSet<unknown, M>, model: Model): M | null { if (typeof this.type === "function" && model instanceof this.type) { return model as M; } return null; }; ModelSet.prototype.key = function <M extends Model>(this: ModelSet<unknown, M>, model: M): string | undefined { return void 0; }; Object.defineProperty(ModelSet.prototype, "sorted", { get(this: ModelSet): boolean { return (this.flags & ModelSet.SortedFlag) !== 0; }, configurable: true, }); ModelSet.prototype.initInherits = function (this: ModelSet, sorted: boolean): void { if (sorted) { (this as Mutable<typeof this>).flags = this.flags | ModelSet.SortedFlag; } else { (this as Mutable<typeof this>).flags = this.flags & ~ModelSet.SortedFlag; } }; ModelSet.prototype.sort = function (this: ModelSet, sorted?: boolean): typeof this { if (sorted === void 0) { sorted = true; } const flags = this.flags; if (sorted && (flags & ModelSet.SortedFlag) === 0) { const parent = this.parentModel; this.willSort(parent); this.setFlags(flags | ModelSet.SortedFlag); this.onSort(parent); this.didSort(parent); } else if (!sorted && (flags & ModelSet.SortedFlag) !== 0) { this.setFlags(flags & ~ModelSet.SortedFlag); } return this; }; ModelSet.prototype.willSort = function (this: ModelSet, parent: Model | null): void { // hook }; ModelSet.prototype.onSort = function (this: ModelSet, parent: Model | null): void { if (parent !== null) { this.sortChildren(parent); } }; ModelSet.prototype.didSort = function (this: ModelSet, parent: Model | null): void { // hook }; ModelSet.prototype.sortChildren = function <M extends Model>(this: ModelSet<unknown, M>, parent: Model): void { parent.sortChildren(this.compareChildren.bind(this)); }; ModelSet.prototype.compareChildren = function <M extends Model>(this: ModelSet<unknown, M>, a: Model, b: Model): number { const models = this.models; const x = models[a.uid]; const y = models[b.uid]; if (x !== void 0 && y !== void 0) { return this.compare(x, y); } else { return x !== void 0 ? 1 : y !== void 0 ? -1 : 0; } }; ModelSet.prototype.compare = function <M extends Model>(this: ModelSet<unknown, M>, a: M, b: M): number { return a.uid < b.uid ? -1 : a.uid > b.uid ? 1 : 0; }; ModelSet.construct = function <F extends ModelSet<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { if (fastener === null) { fastener = function (newModel: AnyModel<ModelSetType<F>>): FastenerOwner<F> { fastener!.addModel(newModel); return fastener!.owner; } as F; delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name Object.setPrototypeOf(fastener, fastenerClass.prototype); } fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).models = {}; (fastener as Mutable<typeof fastener>).modelCount = 0; return fastener; }; ModelSet.define = function <O, M extends Model>(className: string, descriptor: ModelSetDescriptor<O, M>): ModelSetFactory<ModelSet<any, M>> { let superClass = descriptor.extends as ModelSetFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const sorted = descriptor.sorted; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.sorted; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: ModelSet<any, any>}, fastener: ModelSet<O, M> | null, owner: O): ModelSet<O, M> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (sorted !== void 0) { fastener.initSorted(sorted); } return fastener; }; return fastenerClass; }; (ModelSet as Mutable<typeof ModelSet>).SortedFlag = 1 << (_super.FlagShift + 0); (ModelSet as Mutable<typeof ModelSet>).FlagShift = _super.FlagShift + 1; (ModelSet as Mutable<typeof ModelSet>).FlagMask = (1 << ModelSet.FlagShift) - 1; return ModelSet; })(ModelRelation);
import {inject} from '@loopback/core'; import {PgdbDataSource} from '../datasources'; import {Role} from '../models'; import {DefaultSoftCrudRepository} from './default-soft-crud.repository.base'; import {DataObject, Options} from '@loopback/repository'; export class RoleRepository extends DefaultSoftCrudRepository< Role, typeof Role.prototype.id > { constructor(@inject('datasources.pgdb') dataSource: PgdbDataSource) { super(Role, dataSource); } async create(entity: DataObject<Role>, options?: Options): Promise<Role> { //const role = await super.create(entity, options); const permissions = `{${ entity.permissions ? entity.permissions.join() : '' }}`; const query = `INSERT INTO admin.roles( permissions, name, deleted, role_key) VALUES ('${permissions}', '${entity.name}', '${entity.deleted}', '${ entity.roleKey }')`; await super.execute(query, []); return (await this.findOne({ order: ['createdOn DESC'], })) as Role; } async updateById(id: number, entity: DataObject<Role>): Promise<void> { const permissions = `{${ entity.permissions ? entity.permissions.join() : '' }}`; const query = `UPDATE admin.roles SET permissions='${permissions}', name='${entity.name}', deleted='${entity.deleted}',role_key='${entity.roleKey}' WHERE id=${id}`; await super.execute(query, []); } async replaceById(id: number, entity: DataObject<Role>): Promise<void> { const permissions = `{${ entity.permissions ? entity.permissions.join() : '' }}`; const query = `UPDATE admin.roles SET permissions='${permissions}', name='${entity.name}', deleted='${entity.deleted}',role_key='${entity.roleKey}' WHERE id=${id}`; await super.execute(query, []); } }
package com.ip192.spring.service.executors; import com.ip192.spring.entity.User; import com.ip192.spring.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class BusinessOneAsyncTask { @Autowired private UserMapper userMapper; /** * Scheduled注解默认是单线程,可实现SchedulingConfigurer使用线程池 * 异常:可以在定义线程池处定义ExceptionHandler,或对有返回值的get进行try/catch * * Async 注解与 Transactional 注解连用,则调用此方法时只会回滚异步方法 */ // @Async("businessOne") @Transactional // @Scheduled(cron = "0/10 * * * * ?") public void doAsyncTask() { System.out.println(Thread.currentThread().getName()); // while (true) { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } User user = new User(); user.setAge(25); user.setName("four"); userMapper.insertOne(user); System.out.println(1/0); } }
import 'package:test/test.dart'; import 'package:youtube_explode_dart/youtube_explode_dart.dart'; void main() { YoutubeExplode yt; setUpAll(() { yt = YoutubeExplode(); }); tearDownAll(() { yt.close(); }); test('Get comments of a video', () async { var videoUrl = 'https://www.youtube.com/watch?v=AI7ULzgf8RU'; var video = await yt.videos.get(VideoId(videoUrl)); var comments = await yt.videos.commentsClient.getComments(video).toList(); expect(comments.length, greaterThanOrEqualTo(1)); }, skip: 'This may fail on some environments'); }
DROP TABLE purchase; DROP TABLE loan; DROP TABLE sale_artwork; DROP TABLE loan_artwork; DROP TABLE owner; DROP TABLE member; DROP TABLE purchase_status_lov; DROP TABLE artwork_state_lov;
import { Component, OnInit } from '@angular/core'; import {Post} from "../../post/model/post.model"; import {LazyLoadEvent, SelectItem} from "primeng/primeng"; import {PostTableService} from "./services/post-table.service"; import {CategoryTableService} from "app/manage/category-table/services/category-table.service"; import {ToastrService} from "ngx-toastr"; import {flyIn} from "../../animations/fly-in"; @Component({ selector: 'app-post-table', templateUrl: './post-table.component.html', styleUrls: ['./post-table.component.css'], animations: [ flyIn ] }) export class PostTableComponent implements OnInit { public posts:Post[]; public totalRecords:number; public postTypeOptions:SelectItem[]; public enableCommentOptions:SelectItem[]; public statusOptions:SelectItem[]; public categoryOptions:SelectItem[]; //记录分页信息 public pageNum:number; public rowNum:number; constructor(public postTableService:PostTableService, public categoryTableService:CategoryTableService, public toastr: ToastrService) { } ngOnInit() { this.postTypeOptions=[ {label: "原创", value: 0}, {label: "转载", value: 1}, {label: "翻译", value: 2} ] this.enableCommentOptions=[ {label: "开启评论", value: true}, {label: "关闭评论", value: false}, ] this.statusOptions=[ {label: "草稿", value: 0}, {label: "发布", value: 1}, {label: "置顶", value: 2}, {label: "删除", value: 3} ] this.categoryTableService.queryCategory().subscribe( res=>{ let options=[]; for(let data of res) { let option={label: data.categoryName, value: data} options.push(option) } this.categoryOptions=options; }, error=>console.log(error) ) } loadPostsLazy(event: LazyLoadEvent) { //in a real application, make a remote request to load data using state metadata from event //event.first = First row offset //event.rows = Number of rows per page //event.sortField = Field name to sort with //event.sortOrder = Sort order as number, 1 for asc and -1 for dec //filters: FilterMetadata object having field as key and filter value, filter matchMode as value //imitate db connection over a network this.pageNum=1+event.first/event.rows; this.rowNum=event.rows this.queryPosts(this.pageNum,this.rowNum); } queryPosts(pageNum:number,rowNum:number){ this.postTableService.getPostTable(pageNum,rowNum).subscribe( res=>{ this.posts=res.rows; this.totalRecords=res.total; }, error=>{ this.toastr.error(error.json()["msg"]?error.json()["msg"]:"未知错误",'系统提示'); }, ()=>{} ) } saveDrop(event){ this.postTableService.attributeModification(event).subscribe( res=>{ if(res&&res.success){ //修改成功什么也不做 }else{ this.toastr.error(res.msg,"系统提示"); this.queryPosts(this.pageNum,this.rowNum); } }, error=>{ this.toastr.error(error.json()["msg"]?error.json()["msg"]:"未知错误",'系统提示'); }, ()=>{} ) } setStyles(){ let styles={ 'text-align':'center' } return styles; } setEditorStyles(){ let styles={ 'text-align':'center', 'overflow':'visible' } return styles; } }
import 'package:open_cx/networking/model/person_found.dart'; import 'known_person.dart'; class AppState { Map content = Map<String, dynamic>(); Map getInitialContent() { return { "counter": 0, "scanning_on": false, "bluetooth_devices": Map<String, PersonFound>(), "friends": Set<KnownPerson>(), "current_filters": Set<String>(), "user_id": "5dd82f004073ad3bb92b80dc", "person_query_url": "http://www.mocky.io/v2/5da74a162f00002a003683f0", "current_device": "" }; } AppState(Map content) { if (content != null) { this.content = content; } else { this.content = this.getInitialContent(); } } AppState cloneAndUpdateValue(key, value) { return new AppState(Map.from(this.content)..[key] = value); } AppState getInitialState() { return new AppState(null); } }
using System; using System.Collections.Generic; namespace Deconstruction.DeconstructMethod { class Program { static void Main() { var pair = new KeyValuePair<string, int>("one", 1); var (k, v) = pair; // 以下のようなコードに展開される // string k; // int v; // pair.Deconstruct(out k, out v); var tuple = Tuple.Create("abc", 100); var (x, y) = tuple; // 以下のようなコードに展開される // string x; // int y; // tuple.Deconstruct(out x, out y); } } }
#include "UEImgui.h" #define LOCTEXT_NAMESPACE "FUEImguiModule" void FUEImguiModule::StartupModule() { } void FUEImguiModule::ShutdownModule() { } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FUEImguiModule, UEImgui)
/** * 项目名称:quickstart-javase * 文件名:HelloListener.java * 版本信息: * 日期:2018年6月11日 * Copyright yangzl Corporation 2018 * 版权所有 * */ package org.quickstart.javase.jmx.example; import javax.management.Notification; import javax.management.NotificationListener; /** * HelloListener * * @author:youngzil@163.com * @2018年6月11日 下午6:56:46 * @since 1.0 */ public class HelloListener implements NotificationListener { public void handleNotification(Notification notification, Object handback) { if (handback instanceof HelloWorld) { HelloWorld hello = (HelloWorld) handback; hello.printHello(notification.getMessage()); } } }
<?php namespace App\Interfaces\Data; interface ProfileDataInterface { /** * Takes in a model * Inserts model into the database if no model exists * @param $model Model information to create * @return true or false for create */ public function create($model); /** * Takes in a user * Updates user information into the database * @param $user user information to update * @return $model updated information */ public function update($user); /**. * Takes in a user's id * Selects models from the database * @param $user's id * @return $array of model information */ public function readall($users_id); /**. * Takes in a user's id * Deletes model information from the database * @param $user's id * @return true or false for delete */ public function delete($id); /**. * Takes in a user's id * Selects model from the database * @param $user's id * @return $model information */ public function read($id); }
function left_side(side) return HorizonSide(mod(Int(side) + 1 + 4, 4)) end function right_side(side) return HorizonSide(mod(Int(side) - 1 + 4, 4)) end function inverse(side) return HorizonSide(mod(Int(side) + 2, 4)) end function mark_line(r, side, dif) res = 0 while !isborder(r, side) res += dif move!(r, side) putmarker!(r) end return res end function get_to_start(r, side, x, y) for i in (1:x) move!(r, inverse(side)) end y = abs(y) for i in (1:y) move!(r, inverse(right_side(side))) end end function complete_side(r, side) x = 0 while(!isborder(r, side)) x += 1 move!(r, side) end putmarker!(r) y = 0 y += mark_line(r, left_side(side), 1) y += mark_line(r, right_side(side), -1) get_to_start(r, side, x, y) end for i in (0:3) complete_side(r, HorizonSide(i)) end show(r)
import System.Environment (getArgs) import System.Exit (exitSuccess) import qualified Year2015.Day1.Solution as Y2015D1 import qualified Year2015.Day2.Solution as Y2015D2 import qualified Year2015.Day3.Solution as Y2015D3 import qualified Year2015.Day4.Solution as Y2015D4 import qualified Year2021.Day1.Solution as Y2021D1 import qualified Year2015.Day5.Solution as Y2015D5 import qualified Year2021.Day2.Solution as Y2021D2 main :: IO () main = getArgs >>= parse >>= resolve resolve :: (String, String) -> IO () resolve (year, day) = do content <- loadInput year day case year of "2015" -> case day of "1" -> Y2015D1.solve content "2" -> Y2015D2.solve content "3" -> Y2015D3.solve content "4" -> Y2015D4.solve content "5" -> Y2015D5.solve content _ -> print "dunno yet" "2021" -> case day of "1" -> Y2021D1.solve content "2" -> Y2021D2.solve content _ -> print "dunno yet" _ -> print "NIY" parse :: [String] -> IO (String, String) parse ["-h"] = usage >> exitSuccess parse ["-v"] = version >> exitSuccess parse (year : day : _) = return (year, day) parse _ = usage >> exitSuccess usage :: IO () usage = putStrLn "Usage: advent [-vh] year day" version :: IO () version = putStrLn "advent ov code 0.1" -- need to check for file eistence loadInput :: String -> String -> IO String loadInput year day = readFile $ "library/Year" ++ year ++ "/Day" ++ day ++ "/input.txt"
using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.SwaggerToPostman.PostmanSchema.Common; using System; using System.Collections.Generic; using System.Text; namespace Swashbuckle.SwaggerToPostman.Converters { public interface IHeaderParameterObjectConverter { List<PostmanHeader> Convert(List<NonBodyParameter> parameterCollection); } }
# http-petitioner - Generador de peticiones HTTP Resources: - Vue2 - http://ionicons.com/ - Bootstrap4
# Copyright 2016, Juan I. Gesino. # Licensed under MIT license: https://github.com/juangesino/algebra/blob/master/LICENSE # This script requires the Matrix Ruby class (https://ruby-doc.org/stdlib-2.2.0/libdoc/matrix/rdoc/Matrix.html) require 'matrix' class Algebra # Returns the best approximation for an incompatible system ax=b. # Where a and b are matrices. def self.least_squares(a, b) # Make sure the parameters are of class Matrix. raise 'Type error: parameters must be from class Matrix' if a.class != Matrix || b.class != Matrix # Calculate and return the approximation using projections. (a.t * a).inv * a.t * b end end
import Colourista (errorMessage, successMessage) import Fbpmn.Analysis.Alloy.IO.Alloy as BGAlloy (writer) import Fbpmn.Analysis.Tla.IO.Dot as LogDot (writer) import Fbpmn.Analysis.Tla.IO.Html as LogHtml (writer, Extension (Communication, Space)) import Fbpmn.Analysis.Tla.IO.Json as LogJson (writer) import Fbpmn.Analysis.Tla.IO.Log as LogLog (reader) import Fbpmn.Analysis.Tla.IO.Tla as BGTla (writer, writerS) import Fbpmn.Analysis.Tla.Model (filterLog, isValidLog) import Fbpmn.BpmnGraph.IO.Bpmn as BG (reader, readerS) import Fbpmn.BpmnGraph.IO.Dot as BGDot (writer) import Fbpmn.BpmnGraph.IO.Json as BGJson (reader, writer) import Fbpmn.BpmnGraph.Model (isValidGraph) import Fbpmn.BpmnGraph.SpaceModel (isValidSGraph) import Fbpmn.Helper (FReader (..), FWriter (..)) import Options.Applicative fversion :: Text fversion = "0.3.8" toolversion :: Text toolversion = fversion newtype Options = Options Command data Command = CVersion | -- transformations from JSON (regular BPMN models) CJson2Dot Text Text | CJson2Tla Text Text | CJson2Alloy Text Text | -- transformations from regular BPMN models CBpmn2Json Text Text | CBpmn2Tla Text Text | CBpmn2Alloy Text Text | -- transformations from space BPMN models CSBpmn2Tla Text Text | -- transformations from TLA+ logs CLog2Json Text Text | CLog2Dot Text Text | CLog2Html Text Text | CSLog2Html Text Text parserOptions :: Parser Options parserOptions = Options <$> subparser ( command "version" (info (pure CVersion) (progDesc "prints the version")) <> command "json2dot" ( info parserJson2Dot (progDesc "transforms a model from JSON to DOT") ) <> command "json2tla" ( info parserJson2Tla (progDesc "transforms a model from JSON to TLA+") ) <> command "json2alloy" ( info parserJson2Alloy (progDesc "transforms a model from JSON to Alloy") ) <> command "bpmn2json" ( info parserBpmn2Json (progDesc "transforms a model from BPMN to JSON") ) <> command "bpmn2tla" ( info parserBpmn2Tla (progDesc "transforms a model from BPMN to TLA+") ) <> command "bpmn2alloy" ( info parserBpmn2Alloy (progDesc "transforms a model from BPMN to Alloy") ) <> command "sbpmn2tla" ( info parserSBpmn2Tla (progDesc "transforms a model from space BPMN to TLA+") ) <> command "log2json" ( info parserLog2Json (progDesc "transforms a TLA+ log from LOG to JSON") ) <> command "log2dot" (info parserLog2Dot (progDesc "transforms a TLA+ log from LOG to DOT")) <> command "log2html" ( info parserLog2Html (progDesc "transforms a TLA+ log from LOG to HTML") ) <> command "slog2html" ( info parserSLog2Html (progDesc "transforms a TLA+ space log from LOG to HTML") ) ) parserJson2Dot :: Parser Command parserJson2Dot = CJson2Dot <$> argument str ( metavar "INPUT-PATH" <> help "path to the input model in JSON format (without .json suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in DOT format (without .dot suffix)" ) parserJson2Tla :: Parser Command parserJson2Tla = CJson2Tla <$> argument str ( metavar "INPUT-PATH" <> help "path to the input model in JSON format (without .json suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in TLA+ format (without .tla suffix)" ) parserJson2Alloy :: Parser Command parserJson2Alloy = CJson2Alloy <$> argument str ( metavar "INPUT-PATH" <> help "path to the input model in JSON format (without .json suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in Alloy format (without .als suffix)" ) parserBpmn2Json :: Parser Command parserBpmn2Json = CBpmn2Json <$> argument str ( metavar "INPUT-PATH" <> help "path to the input model in BPMN format (without .bpmn suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in JSON format (without .json suffix)" ) parserBpmn2Tla :: Parser Command parserBpmn2Tla = CBpmn2Tla <$> argument str ( metavar "INPUT-PATH" <> help "path to the input model in BPMN format (without .bpmn suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in TLA+ format (without .tla suffix)" ) parserBpmn2Alloy :: Parser Command parserBpmn2Alloy = CBpmn2Alloy <$> argument str ( metavar "INPUT-PATH" <> help "path to the input model in BPMN format (without .bpmn suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in Alloy format (without .als suffix)" ) parserSBpmn2Tla :: Parser Command parserSBpmn2Tla = CSBpmn2Tla <$> argument str ( metavar "INPUT-PATH" <> help "path to the input model in space BPMN format (without .bpmn suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in TLA+ format (without .tla suffix)" ) parserLog2Json :: Parser Command parserLog2Json = CLog2Json <$> argument str ( metavar "INPUT-PATH" <> help "path to the input TLA+ log in textual format (without .log suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output TLA+ log in JSON format (without .json suffix)" ) parserLog2Dot :: Parser Command parserLog2Dot = CLog2Dot <$> argument str ( metavar "INPUT-PATH" <> help "path to the input TLA+ log in textual format (without .log suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in DOT format (without .dot suffix)" ) parserLog2Html :: Parser Command parserLog2Html = CLog2Html <$> argument str ( metavar "INPUT-PATH" <> help "path to the input TLA+ log in textual format (without .log suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in HTML format (without .html suffix)" ) parserSLog2Html :: Parser Command parserSLog2Html = CSLog2Html <$> argument str ( metavar "INPUT-PATH" <> help "path to the input TLA+ log in textual format (without .log suffix)" ) <*> argument str ( metavar "OUTPUT-PATH" <> help "path to the output file in HTML format (without .html suffix)" ) -- no validation needed from BPMN since we build the graph ourselves run :: Options -> IO () run (Options CVersion) = putStrLn . toString $ toolversion run (Options (CJson2Dot pin pout)) = json2dot True pin pout run (Options (CJson2Tla pin pout)) = json2tla True pin pout run (Options (CJson2Alloy pin pout)) = json2alloy True pin pout run (Options (CBpmn2Json pin pout)) = bpmn2json False pin pout run (Options (CBpmn2Tla pin pout)) = bpmn2tla False pin pout run (Options (CBpmn2Alloy pin pout)) = bpmn2alloy False pin pout run (Options (CSBpmn2Tla pin pout)) = sbpmn2tla False pin pout run (Options (CLog2Json pin pout)) = log2json False pin pout run (Options (CLog2Dot pin pout)) = log2dot False pin pout run (Options (CLog2Html pin pout)) = log2html False pin pout run (Options (CSLog2Html pin pout)) = slog2html False pin pout transform2 :: FReader a -> -- reader (from input file to model) FWriter a -> -- writer (from model to output file) (a -> Bool) -> -- model validator (a -> a) -> -- model filtering Bool -> -- should validation be done? Text -> -- input file (without suffix) Text -> -- output file (without suffix) IO () transform2 r w modelValidator modelFilter withValidation inputPath outputPath = do loadres <- read r (toString $ inputPath <> rsuffix r) case loadres of Left err -> errorMessage err Right model -> if not withValidation || modelValidator model then do write w (toString $ outputPath <> wsuffix w) (modelFilter model) successMessage "transformation done" else errorMessage "model is incorrect" json2dot :: Bool -> Text -> Text -> IO () json2dot = transform2 BGJson.reader BGDot.writer isValidGraph id json2tla :: Bool -> Text -> Text -> IO () json2tla = transform2 BGJson.reader BGTla.writer isValidGraph id json2alloy :: Bool -> Text -> Text -> IO () json2alloy = transform2 BGJson.reader BGAlloy.writer isValidGraph id bpmn2json :: Bool -> Text -> Text -> IO () bpmn2json = transform2 BG.reader BGJson.writer isValidGraph id bpmn2tla :: Bool -> Text -> Text -> IO () bpmn2tla = transform2 BG.reader BGTla.writer isValidGraph id bpmn2alloy :: Bool -> Text -> Text -> IO () bpmn2alloy = transform2 BG.reader BGAlloy.writer isValidGraph id sbpmn2tla :: Bool -> Text -> Text -> IO () sbpmn2tla = transform2 BG.readerS BGTla.writerS isValidSGraph id log2json :: Bool -> Text -> Text -> IO () log2json = transform2 LogLog.reader LogJson.writer isValidLog filterLog log2dot :: Bool -> Text -> Text -> IO () log2dot = transform2 LogLog.reader LogDot.writer isValidLog filterLog log2html :: Bool -> Text -> Text -> IO () log2html = transform2 LogLog.reader (LogHtml.writer [Communication]) isValidLog filterLog slog2html :: Bool -> Text -> Text -> IO () slog2html = transform2 LogLog.reader (LogHtml.writer [Communication, Space]) isValidLog filterLog main :: IO () main = run =<< execParser opts where opts = info (parserOptions <**> helper) ( fullDesc <> progDesc "formal transformations for BPMN models" <> header (toString toolversion) )
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/tether/wifi_hotspot_connector.h" #include <memory> #include <sstream> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/simple_test_clock.h" #include "base/test/task_environment.h" #include "base/test/test_simple_task_runner.h" #include "base/timer/mock_timer.h" #include "base/values.h" #include "chromeos/network/network_connect.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_state_test_helper.h" #include "chromeos/network/shill_property_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/shill/dbus-constants.h" namespace chromeos { namespace tether { namespace { const char kSsid[] = "ssid"; const char kPassword[] = "password"; const char kOtherWifiServiceGuid[] = "otherWifiServiceGuid"; const char kTetherNetworkGuid[] = "tetherNetworkGuid"; const char kTetherNetworkGuid2[] = "tetherNetworkGuid2"; constexpr base::TimeDelta kConnectionToHotspotTime = base::TimeDelta::FromSeconds(20); std::string CreateConfigurationJsonString(const std::string& guid) { std::stringstream ss; ss << "{" << " \"GUID\": \"" << guid << "\"," << " \"Type\": \"" << shill::kTypeWifi << "\"," << " \"State\": \"" << shill::kStateIdle << "\"" << "}"; return ss.str(); } } // namespace class WifiHotspotConnectorTest : public testing::Test { public: class TestNetworkConnect : public NetworkConnect { public: explicit TestNetworkConnect(NetworkStateTestHelper* helper) : helper_(helper) {} ~TestNetworkConnect() override = default; void set_is_running_in_test_task_runner( bool is_running_in_test_task_runner) { is_running_in_test_task_runner_ = is_running_in_test_task_runner; } base::DictionaryValue* last_configuration() { return last_configuration_.get(); } std::string last_service_path_created() { return last_service_path_created_; } std::string network_id_to_connect() { return network_id_to_connect_; } std::string network_id_to_disconnect() { return network_id_to_disconnect_; } uint32_t num_connection_attempts() { return num_connection_attempts_; } uint32_t num_disconnection_attempts() { return num_disconnection_attempts_; } // Finish configuring the last specified Wi-Fi network config. void ConfigureServiceWithLastNetworkConfig() { std::string wifi_guid; EXPECT_TRUE( last_configuration_->GetString(shill::kGuidProperty, &wifi_guid)); last_service_path_created_ = helper_->ConfigureService(CreateConfigurationJsonString(wifi_guid)); } // NetworkConnect: void SetTechnologyEnabled(const chromeos::NetworkTypePattern& technology, bool enabled_state) override {} void ShowMobileSetup(const std::string& network_id) override {} void ConfigureNetworkIdAndConnect( const std::string& network_id, const base::DictionaryValue& shill_properties, bool shared) override {} void CreateConfigurationAndConnect(base::DictionaryValue* shill_properties, bool shared) override {} void CreateConfiguration(base::DictionaryValue* shill_properties, bool shared) override { EXPECT_FALSE(shared); last_configuration_ = shill_properties->CreateDeepCopy(); // Prevent nested RunLoops when ConfigureServiceWithLastNetworkConfig() // calls NetworkStateTestHelper::ConfigureService(); that causes threading // issues. If |test_task_runner_| is causing this function to be run, the // client which triggered this call can manually call // ConfigureServiceWithLastNetworkConfig() once done. if (!is_running_in_test_task_runner_) ConfigureServiceWithLastNetworkConfig(); } void ConnectToNetworkId(const std::string& network_id) override { num_connection_attempts_++; network_id_to_connect_ = network_id; } void DisconnectFromNetworkId(const std::string& network_id) override { num_disconnection_attempts_++; network_id_to_disconnect_ = network_id; } private: NetworkStateTestHelper* helper_; std::unique_ptr<base::DictionaryValue> last_configuration_; std::string last_service_path_created_; std::string network_id_to_connect_; std::string network_id_to_disconnect_; uint32_t num_connection_attempts_ = 0; uint32_t num_disconnection_attempts_ = 0; bool is_running_in_test_task_runner_ = false; }; WifiHotspotConnectorTest() = default; ~WifiHotspotConnectorTest() override = default; void SetUp() override { other_wifi_service_path_.clear(); connection_callback_responses_.clear(); helper_.network_state_handler()->SetTetherTechnologyState( NetworkStateHandler::TechnologyState::TECHNOLOGY_ENABLED); helper_.network_state_handler()->SetTechnologyEnabled( NetworkTypePattern::WiFi(), true /* enabled */, chromeos::network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); SetUpShillState(); test_network_connect_ = base::WrapUnique(new TestNetworkConnect(&helper_)); helper_.network_state_handler()->AddTetherNetworkState( kTetherNetworkGuid, "tetherNetworkName" /* name */, "tetherNetworkCarrier" /* carrier */, 100 /* full battery */, 100 /* full signal strength */, false /* has_connected_to_host */); helper_.network_state_handler()->AddTetherNetworkState( kTetherNetworkGuid2, "tetherNetworkName2" /* name */, "tetherNetworkCarrier2" /* carrier */, 100 /* full battery */, 100 /* full signal strength */, false /* has_connected_to_host */); wifi_hotspot_connector_ = base::WrapUnique(new WifiHotspotConnector( helper_.network_state_handler(), test_network_connect_.get())); mock_timer_ = new base::MockOneShotTimer(); test_clock_.SetNow(base::Time::UnixEpoch()); test_task_runner_ = base::MakeRefCounted<base::TestSimpleTaskRunner>(); wifi_hotspot_connector_->SetTestDoubles(base::WrapUnique(mock_timer_), &test_clock_, test_task_runner_); } void SetUpShillState() { // Add a Wi-Fi service unrelated to the one under test. In some tests, a // connection from another device is tested. other_wifi_service_path_ = helper_.ConfigureService( CreateConfigurationJsonString(std::string(kOtherWifiServiceGuid))); } void TearDown() override { wifi_hotspot_connector_.reset(); } void VerifyTimerSet() { EXPECT_TRUE(mock_timer_->IsRunning()); EXPECT_EQ(base::TimeDelta::FromSeconds( WifiHotspotConnector::kConnectionTimeoutSeconds), mock_timer_->GetCurrentDelay()); } void VerifyTimerStopped() { EXPECT_FALSE(mock_timer_->IsRunning()); } void InvokeTimerTask() { VerifyTimerSet(); mock_timer_->Fire(); } void RunTestTaskRunner() { test_network_connect_->set_is_running_in_test_task_runner(true); test_task_runner_->RunUntilIdle(); test_network_connect_->set_is_running_in_test_task_runner(false); } void NotifyConnectable(const std::string& service_path) { helper_.SetServiceProperty(service_path, std::string(shill::kConnectableProperty), base::Value(true)); RunTestTaskRunner(); } void NotifyConnected(const std::string& service_path) { helper_.SetServiceProperty(service_path, std::string(shill::kStateProperty), base::Value(shill::kStateReady)); RunTestTaskRunner(); } void VerifyConnectionToHotspotDurationRecorded(bool expected) { if (expected) { histogram_tester_.ExpectTimeBucketCount( "InstantTethering.Performance.ConnectToHotspotDuration", kConnectionToHotspotTime, 1); } else { histogram_tester_.ExpectTotalCount( "InstantTethering.Performance.ConnectToHotspotDuration", 0); } } // Verifies the last configuration has the expected SSID and password, and // returns the Wi-Fi GUID for the configuration. std::string VerifyLastConfiguration(const std::string& expected_ssid, const std::string& expected_password) { base::DictionaryValue* last_configuration = test_network_connect_->last_configuration(); EXPECT_TRUE(last_configuration); std::string ssid = shill_property_util::GetSSIDFromProperties( *last_configuration, false, nullptr); EXPECT_EQ(expected_ssid, ssid); if (expected_password.empty()) { std::string security; EXPECT_TRUE(last_configuration->GetString(shill::kSecurityClassProperty, &security)); EXPECT_EQ(std::string(shill::kSecurityNone), security); } else { std::string security; EXPECT_TRUE(last_configuration->GetString(shill::kSecurityClassProperty, &security)); EXPECT_EQ(std::string(shill::kSecurityPsk), security); std::string password; EXPECT_TRUE( last_configuration->GetString(shill::kPassphraseProperty, &password)); EXPECT_EQ(expected_password, password); } std::string wifi_guid; EXPECT_TRUE( last_configuration->GetString(shill::kGuidProperty, &wifi_guid)); return wifi_guid; } void VerifyTetherAndWifiNetworkAssociation( const std::string& wifi_guid, const std::string& tether_guid, uint32_t expected_num_connection_attempts) { const NetworkState* wifi_network_state = helper_.network_state_handler()->GetNetworkStateFromGuid(wifi_guid); ASSERT_TRUE(wifi_network_state); EXPECT_EQ(tether_guid, wifi_network_state->tether_guid()); const NetworkState* tether_network_state = helper_.network_state_handler()->GetNetworkStateFromGuid(tether_guid); ASSERT_TRUE(tether_network_state); EXPECT_EQ(wifi_guid, tether_network_state->tether_guid()); EXPECT_EQ(expected_num_connection_attempts, test_network_connect_->num_connection_attempts()); } void VerifyNetworkNotAssociated(const std::string& guid) { const NetworkState* network_state = helper_.network_state_handler()->GetNetworkStateFromGuid(guid); ASSERT_TRUE(network_state); EXPECT_TRUE(network_state->tether_guid().empty()); } void WifiConnectionCallback(const std::string& wifi_guid) { connection_callback_responses_.push_back(wifi_guid); } NetworkStateHandler* network_state_handler() { return helper_.network_state_handler(); } base::test::SingleThreadTaskEnvironment task_environment_; NetworkStateTestHelper helper_{true /* use_default_devices_and_services */}; std::string other_wifi_service_path_; std::vector<std::string> connection_callback_responses_; base::MockOneShotTimer* mock_timer_; base::SimpleTestClock test_clock_; scoped_refptr<base::TestSimpleTaskRunner> test_task_runner_; std::unique_ptr<TestNetworkConnect> test_network_connect_; std::unique_ptr<WifiHotspotConnector> wifi_hotspot_connector_; base::HistogramTester histogram_tester_; private: DISALLOW_COPY_AND_ASSIGN(WifiHotspotConnectorTest); }; TEST_F(WifiHotspotConnectorTest, TestConnect_NetworkDoesNotBecomeConnectable) { wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid = VerifyLastConfiguration(std::string(kSsid), std::string(kPassword)); EXPECT_FALSE(wifi_guid.empty()); // Network does not become connectable. EXPECT_TRUE(test_network_connect_->network_id_to_connect().empty()); // Timeout timer fires. EXPECT_EQ(0u, connection_callback_responses_.size()); InvokeTimerTask(); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_TRUE(connection_callback_responses_[0].empty()); VerifyConnectionToHotspotDurationRecorded(false /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_AnotherNetworkBecomesConnectable) { wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid = VerifyLastConfiguration(std::string(kSsid), std::string(kPassword)); EXPECT_FALSE(wifi_guid.empty()); // Another network becomes connectable. This should not cause the connection // to start. NotifyConnectable(other_wifi_service_path_); VerifyNetworkNotAssociated(wifi_guid); std::string other_wifi_guid = network_state_handler() ->GetNetworkState(other_wifi_service_path_) ->guid(); VerifyNetworkNotAssociated(other_wifi_guid); EXPECT_TRUE(test_network_connect_->network_id_to_connect().empty()); // Timeout timer fires. EXPECT_EQ(0u, connection_callback_responses_.size()); InvokeTimerTask(); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_TRUE(connection_callback_responses_[0].empty()); VerifyConnectionToHotspotDurationRecorded(false /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_CannotConnectToNetwork) { wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid = VerifyLastConfiguration(std::string(kSsid), std::string(kPassword)); EXPECT_FALSE(wifi_guid.empty()); // Network becomes connectable. NotifyConnectable(test_network_connect_->last_service_path_created()); VerifyTetherAndWifiNetworkAssociation( wifi_guid, kTetherNetworkGuid, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_connect()); // Network connection does not occur. EXPECT_EQ(0u, connection_callback_responses_.size()); // Timeout timer fires. InvokeTimerTask(); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_TRUE(connection_callback_responses_[0].empty()); EXPECT_EQ(1u, test_network_connect_->num_disconnection_attempts()); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_disconnect()); VerifyConnectionToHotspotDurationRecorded(false /* expected */); } TEST_F(WifiHotspotConnectorTest, TestConnect_DeletedWhileConnectionPending) { wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid = VerifyLastConfiguration(std::string(kSsid), std::string(kPassword)); EXPECT_FALSE(wifi_guid.empty()); // Network becomes connectable. NotifyConnectable(test_network_connect_->last_service_path_created()); VerifyTetherAndWifiNetworkAssociation( wifi_guid, kTetherNetworkGuid, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_connect()); EXPECT_EQ(0u, connection_callback_responses_.size()); // Delete the connector; this should trigger a disconnection attempt. wifi_hotspot_connector_.reset(); EXPECT_EQ(1u, test_network_connect_->num_disconnection_attempts()); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_disconnect()); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_EQ(std::string(), connection_callback_responses_[0]); VerifyConnectionToHotspotDurationRecorded(false /* expected */); } TEST_F(WifiHotspotConnectorTest, TestConnect_Success) { wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid = VerifyLastConfiguration(std::string(kSsid), std::string(kPassword)); EXPECT_FALSE(wifi_guid.empty()); // Network becomes connectable. NotifyConnectable(test_network_connect_->last_service_path_created()); VerifyTetherAndWifiNetworkAssociation( wifi_guid, kTetherNetworkGuid, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_connect()); EXPECT_EQ(0u, connection_callback_responses_.size()); test_clock_.Advance(kConnectionToHotspotTime); // Connection to network successful. NotifyConnected(test_network_connect_->last_service_path_created()); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_EQ(wifi_guid, connection_callback_responses_[0]); VerifyTimerStopped(); VerifyConnectionToHotspotDurationRecorded(true /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_Success_EmptyPassword) { wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string() /* password */, kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid = VerifyLastConfiguration(kSsid, std::string()); EXPECT_FALSE(wifi_guid.empty()); // Network becomes connectable. NotifyConnectable(test_network_connect_->last_service_path_created()); VerifyTetherAndWifiNetworkAssociation( wifi_guid, kTetherNetworkGuid, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_connect()); EXPECT_EQ(0u, connection_callback_responses_.size()); test_clock_.Advance(kConnectionToHotspotTime); // Connection to network successful. NotifyConnected(test_network_connect_->last_service_path_created()); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_EQ(wifi_guid, connection_callback_responses_[0]); VerifyTimerStopped(); VerifyConnectionToHotspotDurationRecorded(true /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_SecondConnectionWhileWaitingForFirstToBecomeConnectable) { wifi_hotspot_connector_->ConnectToWifiHotspot( "ssid1", "password1", "tetherNetworkGuid1", base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid1 = VerifyLastConfiguration("ssid1", "password1"); EXPECT_FALSE(wifi_guid1.empty()); std::string service_path1 = test_network_connect_->last_service_path_created(); EXPECT_FALSE(service_path1.empty()); // Pass some arbitrary time -- this should not affect the // recorded duration because the start time should be reset // for a new network attempt. test_clock_.Advance(base::TimeDelta::FromSeconds(13)); // Before network becomes connectable, start the new connection. EXPECT_EQ(0u, connection_callback_responses_.size()); wifi_hotspot_connector_->ConnectToWifiHotspot( "ssid2", "password2", kTetherNetworkGuid2, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); std::string wifi_guid2 = VerifyLastConfiguration("ssid2", "password2"); EXPECT_FALSE(wifi_guid2.empty()); std::string service_path2 = test_network_connect_->last_service_path_created(); EXPECT_FALSE(service_path2.empty()); VerifyNetworkNotAssociated(wifi_guid1); EXPECT_NE(service_path1, service_path2); // The original connection attempt should have gotten an empty response. EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_TRUE(connection_callback_responses_[0].empty()); // First network becomes connectable. NotifyConnectable(service_path1); // A connection should not have started to that GUID. EXPECT_TRUE(test_network_connect_->network_id_to_connect().empty()); EXPECT_EQ(1u, connection_callback_responses_.size()); test_clock_.Advance(kConnectionToHotspotTime); // Second network becomes connectable. NotifyConnectable(service_path2); VerifyTetherAndWifiNetworkAssociation( wifi_guid2, kTetherNetworkGuid2, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid2, test_network_connect_->network_id_to_connect()); EXPECT_EQ(1u, connection_callback_responses_.size()); // Connection to network successful. NotifyConnected(service_path2); EXPECT_EQ(2u, connection_callback_responses_.size()); EXPECT_EQ(wifi_guid2, connection_callback_responses_[1]); VerifyTimerStopped(); VerifyConnectionToHotspotDurationRecorded(true /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_SecondConnectionWhileWaitingForFirstToConnect) { wifi_hotspot_connector_->ConnectToWifiHotspot( "ssid1", "password1", kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); // Pass some arbitrary time -- this should not affect the // recorded duration because the start time should be reset // for a new network attempt. test_clock_.Advance(base::TimeDelta::FromSeconds(13)); std::string wifi_guid1 = VerifyLastConfiguration("ssid1", "password1"); EXPECT_FALSE(wifi_guid1.empty()); std::string service_path1 = test_network_connect_->last_service_path_created(); EXPECT_FALSE(service_path1.empty()); // First network becomes connectable. NotifyConnectable(service_path1); VerifyTetherAndWifiNetworkAssociation( wifi_guid1, kTetherNetworkGuid, 1u /* expected_num_connection_attempts */); // After network becomes connectable, request a connection to second network. wifi_hotspot_connector_->ConnectToWifiHotspot( "ssid2", "password2", kTetherNetworkGuid2, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); // The first Tether and Wi-Fi networks should no longer be associated. VerifyNetworkNotAssociated(kTetherNetworkGuid); VerifyNetworkNotAssociated(wifi_guid1); // The original connection attempt should have gotten an empty response. EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_TRUE(connection_callback_responses_[0].empty()); // A disconnection attempt should have been initiated to the other network. EXPECT_EQ(1u, test_network_connect_->num_disconnection_attempts()); EXPECT_EQ(wifi_guid1, test_network_connect_->network_id_to_disconnect()); std::string wifi_guid2 = VerifyLastConfiguration("ssid2", "password2"); EXPECT_FALSE(wifi_guid2.empty()); std::string service_path2 = test_network_connect_->last_service_path_created(); EXPECT_FALSE(service_path2.empty()); EXPECT_NE(service_path1, service_path2); test_clock_.Advance(kConnectionToHotspotTime); // Second network becomes connectable. NotifyConnectable(service_path2); VerifyTetherAndWifiNetworkAssociation( wifi_guid2, kTetherNetworkGuid2, 2u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid2, test_network_connect_->network_id_to_connect()); EXPECT_EQ(1u, connection_callback_responses_.size()); // Connection to network successful. NotifyConnected(service_path2); EXPECT_EQ(2u, connection_callback_responses_.size()); EXPECT_EQ(wifi_guid2, connection_callback_responses_[1]); VerifyTimerStopped(); VerifyConnectionToHotspotDurationRecorded(true /* expected */); } TEST_F(WifiHotspotConnectorTest, TestConnect_WifiDisabled_Success) { network_state_handler()->SetTechnologyEnabled( NetworkTypePattern::WiFi(), false /* enabled */, chromeos::network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); // Allow the asyncronous call to NetworkStateHandler::SetTechnologyEnabled() // within WifiHotspotConnector::ConnectToWifiHotspot() to synchronously // run. After this call, Wi-Fi should be enabled and WifiHotspotConnector // will have called TestNetworkConnect::CreateConfiguration(). base::RunLoop().RunUntilIdle(); EXPECT_TRUE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); // Run the task and manually invoke ConfigureServiceWithLastNetworkConfig() to // prevent nested RunLoop errors. RunTestTaskRunner(); test_network_connect_->ConfigureServiceWithLastNetworkConfig(); std::string wifi_guid = VerifyLastConfiguration(std::string(kSsid), std::string(kPassword)); EXPECT_FALSE(wifi_guid.empty()); test_clock_.Advance(kConnectionToHotspotTime); // Network becomes connectable. NotifyConnectable(test_network_connect_->last_service_path_created()); VerifyTetherAndWifiNetworkAssociation( wifi_guid, kTetherNetworkGuid, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_connect()); EXPECT_EQ(0u, connection_callback_responses_.size()); // Connection to network successful. NotifyConnected(test_network_connect_->last_service_path_created()); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_EQ(wifi_guid, connection_callback_responses_[0]); VerifyTimerStopped(); VerifyConnectionToHotspotDurationRecorded(true /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_WifiDisabled_Success_OtherDeviceStatesChange) { network_state_handler()->SetTechnologyEnabled( NetworkTypePattern::WiFi(), false /* enabled */, chromeos::network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); // Ensure that WifiHotspotConnector only begins configuring the Wi-Fi network // once Wi-Fi is enabled. wifi_hotspot_connector_->DeviceListChanged(); wifi_hotspot_connector_->DeviceListChanged(); EXPECT_FALSE(test_network_connect_->last_configuration()); // Allow the asyncronous call to NetworkStateHandler::SetTechnologyEnabled() // within WifiHotspotConnector::ConnectToWifiHotspot() to synchronously // run. After this call, Wi-Fi should be enabled and WifiHotspotConnector // will have called TestNetworkConnect::CreateConfiguration(). base::RunLoop().RunUntilIdle(); EXPECT_TRUE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); // Run the task and manually invoke ConfigureServiceWithLastNetworkConfig() to // prevent nested RunLoop errors. RunTestTaskRunner(); test_network_connect_->ConfigureServiceWithLastNetworkConfig(); std::string wifi_guid = VerifyLastConfiguration(std::string(kSsid), std::string(kPassword)); EXPECT_FALSE(wifi_guid.empty()); // Network becomes connectable. NotifyConnectable(test_network_connect_->last_service_path_created()); VerifyTetherAndWifiNetworkAssociation( wifi_guid, kTetherNetworkGuid, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid, test_network_connect_->network_id_to_connect()); EXPECT_EQ(0u, connection_callback_responses_.size()); test_clock_.Advance(kConnectionToHotspotTime); // Connection to network successful. NotifyConnected(test_network_connect_->last_service_path_created()); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_EQ(wifi_guid, connection_callback_responses_[0]); VerifyTimerStopped(); VerifyConnectionToHotspotDurationRecorded(true /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_WifiDisabled_AttemptTimesOut) { network_state_handler()->SetTechnologyEnabled( NetworkTypePattern::WiFi(), false /* enabled */, chromeos::network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); wifi_hotspot_connector_->ConnectToWifiHotspot( std::string(kSsid), std::string(kPassword), kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); // Timeout timer fires. InvokeTimerTask(); EXPECT_EQ(1u, connection_callback_responses_.size()); EXPECT_TRUE(connection_callback_responses_[0].empty()); // Allow the asyncronous call to NetworkStateHandler::SetTechnologyEnabled() // within WifiHotspotConnector::ConnectToWifiHotspot() to synchronously // run. After this call, Wi-Fi should be enabled, but the connection attempt // has timed out and therefore a new Wi-Fi configuration should not exist. base::RunLoop().RunUntilIdle(); EXPECT_TRUE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); // No configuration should have been created since the connection attempt // timed out before Wi-Fi was successfully enabled. EXPECT_FALSE(test_network_connect_->last_configuration()); VerifyConnectionToHotspotDurationRecorded(false /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } TEST_F(WifiHotspotConnectorTest, TestConnect_WifiDisabled_SecondConnectionWhileWaitingForWifiEnabled) { network_state_handler()->SetTechnologyEnabled( NetworkTypePattern::WiFi(), false /* enabled */, chromeos::network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); wifi_hotspot_connector_->ConnectToWifiHotspot( "ssid1", "password1", kTetherNetworkGuid, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); // Pass some arbitrary time -- this should not affect the // recorded duration because the start time should be reset // for a new network attempt. test_clock_.Advance(base::TimeDelta::FromSeconds(13)); EXPECT_FALSE(test_network_connect_->last_configuration()); wifi_hotspot_connector_->ConnectToWifiHotspot( "ssid2", "password2", kTetherNetworkGuid2, base::BindOnce(&WifiHotspotConnectorTest::WifiConnectionCallback, base::Unretained(this))); // Allow the asyncronous call to NetworkStateHandler::SetTechnologyEnabled() // within WifiHotspotConnector::ConnectToWifiHotspot() to synchronously // run. After this call, Wi-Fi should be enabled and WifiHotspotConnector // will have called TestNetworkConnect::CreateConfiguration(). base::RunLoop().RunUntilIdle(); EXPECT_TRUE( network_state_handler()->IsTechnologyEnabled(NetworkTypePattern::WiFi())); // Run the task and manually invoke ConfigureServiceWithLastNetworkConfig() to // prevent nested RunLoop errors. RunTestTaskRunner(); test_network_connect_->ConfigureServiceWithLastNetworkConfig(); std::string wifi_guid2 = VerifyLastConfiguration("ssid2", "password2"); EXPECT_FALSE(wifi_guid2.empty()); std::string service_path2 = test_network_connect_->last_service_path_created(); EXPECT_FALSE(service_path2.empty()); // Second network becomes connectable. NotifyConnectable(service_path2); VerifyTetherAndWifiNetworkAssociation( wifi_guid2, kTetherNetworkGuid2, 1u /* expected_num_connection_attempts */); EXPECT_EQ(wifi_guid2, test_network_connect_->network_id_to_connect()); EXPECT_EQ(1u, connection_callback_responses_.size()); test_clock_.Advance(kConnectionToHotspotTime); // Connection to network successful. NotifyConnected(service_path2); EXPECT_EQ(2u, connection_callback_responses_.size()); EXPECT_EQ(wifi_guid2, connection_callback_responses_[1]); VerifyTimerStopped(); VerifyConnectionToHotspotDurationRecorded(true /* expected */); EXPECT_EQ(0u, test_network_connect_->num_disconnection_attempts()); } } // namespace tether } // namespace chromeos
namespace Swan.Test { using NUnit.Framework; using Swan.Utilities; using System; using System.Text; using System.Threading.Tasks; [TestFixture] public class GetProcessOutputAsync { [Test] public void WithInValidParams_ThrowsArgumentNullException() { Assert.ThrowsAsync<ArgumentNullException>(async () => await ProcessRunner.GetProcessOutputAsync(null)); } [Test] public async Task WithValidParams_ReturnsProcessOutput() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "--help"); Assert.IsNotEmpty(data); Assert.IsTrue(data.StartsWith(".NET")); } [Test] public async Task WithValidParamsAndTempDirectory_ReturnsProcessOutput() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "--help", System.IO.Path.GetTempPath()); Assert.IsNotEmpty(data); Assert.IsTrue(data.StartsWith(".NET")); } [Test] public async Task WithInvalidParams_ReturnsProcessError() { var data = await ProcessRunner.GetProcessOutputAsync("dotnet", "lol"); Assert.IsNotEmpty(data); } } [TestFixture] public class GetProcessEncodedOutputAsync { [Test] public void WithInValidParams_ThrowsArgumentNullException() { Assert.ThrowsAsync<ArgumentNullException>(async () => await ProcessRunner.GetProcessEncodedOutputAsync(null)); } [Test] public async Task WithValidParams_ReturnsProcessOutput() { var data = await ProcessRunner.GetProcessEncodedOutputAsync("dotnet", "--help", Encoding.UTF8); Assert.IsNotEmpty(data); Assert.IsTrue(data.StartsWith(".NET")); } } [TestFixture] public class RunProcessAsync { [Test] public void WithInValidParams_ThrowsArgumentNullException() { Assert.ThrowsAsync<ArgumentNullException>(async () => await ProcessRunner.RunProcessAsync(null, null, null, null)); } [Test] public async Task WithNullOnErrorData_ValidRunProcess() { const int resultCode = 0; string output = null; var result = await ProcessRunner.RunProcessAsync( "dotnet", "--help", (data, proc) => { if (output == null) output = Encoding.GetEncoding(0).GetString(data); }, null); Assert.IsTrue(result == resultCode); Assert.IsNotNull(output); } [Test] public async Task WithNullOnOutputData_InvalidRunProcess() { const int errorCode = 1; string output = null; var result = await ProcessRunner.RunProcessAsync("dotnet", "lol", null, (data, proc) => { if (output == null) output = Encoding.GetEncoding(0).GetString(data); }); Assert.IsTrue(result == errorCode); Assert.IsNotNull(output); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SamSeifert.Utilities.Timing { public class RateTracker { private float _AverageElapsed = 0; private bool _First = true; private bool _Second = true; private DateTime _Last = DateTime.Now; private readonly float _Alpha; int _VisbibleChangeCount = 0; public RateTracker(float alpha = 0.1f) { this._Alpha = alpha; } public float Update() { var now = DateTime.Now; var elapsed = (float)((now - this._Last).TotalSeconds); this._Last = now; if (this._First) { this._First = false; return 0; } if (this._Second) { this._AverageElapsed = elapsed; this._Second = false; } else { this._AverageElapsed *= (1 - this._Alpha); this._AverageElapsed += this._Alpha * elapsed; } if (this._AverageElapsed < 0.0001f) return -1; // Can't track more than 10,000 Hz float fps = 1 / this._AverageElapsed; /// The problem with this is approach is, FPS won't change if the Update() method is never called. /// So, have the value always change slightly when it is updating to indicate a live feed. switch (_VisbibleChangeCount++ % 3) { case 1: return fps + 0.01f; case 2: return fps - 0.01f; default: return fps; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PseudoInternationalization { abstract class BaseProcessor : IProcessor { public void Process(string path) { using(var fs = new FileStream(path, FileMode.Open)) { Load(fs); } var outputPath = GenerateOutputPath(path); using (var fs = new FileStream(outputPath, FileMode.Create)) { Save(fs); } } private string GenerateOutputPath(string path) { if (Program.Overwrite) return path; else return Path.Combine(Program.Output, Path.GetFileName(path)); } protected abstract void Load(Stream input); protected abstract void Save(Stream output); } }
# Search for a Correlation between Very-high-energy Gamma Rays and Giant Radio Pulses in the Crab Pulsar Reference: Aliu, E. et al. (The VERITAS Collaboration), The Astrophysical Journal, 760, 136 (2012) - ADS: [2012ApJ...760..136A](http://adsabs.harvard.edu/abs/2012ApJ...760..136A) - DOI: [10.1088/0004-637X/760/2/136](https://doi.org/10.1088/0004-637X/760/2/136) ## PKS 0447-439 ### Data files (no data files)
// tslint:disable import { DocumentNode } from 'graphql'; import * as ReactApollo from 'react-apollo'; import * as ReactApolloHooks from 'react-apollo-hooks'; export type Maybe<T> = T | null; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; }; export type Mutation = { upVote: Scalars['String']; register: UserEntity; }; export type MutationUpVoteArgs = { vote: Scalars['String']; }; export type MutationRegisterArgs = { newUserInput: NewUserInpunt; }; export type NewUserInpunt = { firstName: Scalars['String']; email: Scalars['String']; password: Scalars['String']; }; export type Query = { helloWorld: Scalars['String']; allVotes: Array<VoteEntity>; allUsers: Array<UserEntity>; }; export type Subscription = { userAdded: UserEntity; }; export type UserEntity = { id: Scalars['ID']; firstName: Scalars['String']; email: Scalars['String']; }; export type VoteEntity = { id: Scalars['ID']; vote?: Maybe<Scalars['String']>; downVote: Scalars['Float']; info: Scalars['String']; }; export type HelloWorldQueryVariables = {}; export type HelloWorldQuery = { __typename?: 'Query' } & Pick< Query, 'helloWorld' >; export type AllVotesQueryVariables = {}; export type AllVotesQuery = { __typename?: 'Query' } & { allVotes: Array< { __typename?: 'VoteEntity' } & Pick<VoteEntity, 'id' | 'vote'> >; }; export type AllUsersQueryVariables = {}; export type AllUsersQuery = { __typename?: 'Query' } & { allUsers: Array< { __typename?: 'UserEntity' } & Pick<UserEntity, 'id' | 'firstName'> >; }; export type RegisterUserMutationVariables = { firstName: Scalars['String']; password: Scalars['String']; email: Scalars['String']; }; export type RegisterUserMutation = { __typename?: 'Mutation' } & { register: { __typename?: 'UserEntity' } & Pick< UserEntity, 'id' | 'firstName' | 'email' >; }; export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>; export const HelloWorldDocument: DocumentNode = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'helloWorld' }, variableDefinitions: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'helloWorld' }, arguments: [], directives: [], }, ], }, }, ], }; export function useHelloWorldQuery( baseOptions?: ReactApolloHooks.QueryHookOptions<HelloWorldQueryVariables>, ) { return ReactApolloHooks.useQuery<HelloWorldQuery, HelloWorldQueryVariables>( HelloWorldDocument, baseOptions, ); } export const AllVotesDocument: DocumentNode = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'allVotes' }, variableDefinitions: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'allVotes' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [], }, { kind: 'Field', name: { kind: 'Name', value: 'vote' }, arguments: [], directives: [], }, ], }, }, ], }, }, ], }; export function useAllVotesQuery( baseOptions?: ReactApolloHooks.QueryHookOptions<AllVotesQueryVariables>, ) { return ReactApolloHooks.useQuery<AllVotesQuery, AllVotesQueryVariables>( AllVotesDocument, baseOptions, ); } export const AllUsersDocument: DocumentNode = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'query', name: { kind: 'Name', value: 'allUsers' }, variableDefinitions: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'allUsers' }, arguments: [], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [], }, { kind: 'Field', name: { kind: 'Name', value: 'firstName' }, arguments: [], directives: [], }, ], }, }, ], }, }, ], }; export function useAllUsersQuery( baseOptions?: ReactApolloHooks.QueryHookOptions<AllUsersQueryVariables>, ) { return ReactApolloHooks.useQuery<AllUsersQuery, AllUsersQueryVariables>( AllUsersDocument, baseOptions, ); } export const RegisterUserDocument: DocumentNode = { kind: 'Document', definitions: [ { kind: 'OperationDefinition', operation: 'mutation', name: { kind: 'Name', value: 'registerUser' }, variableDefinitions: [ { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'firstName' }, }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' }, }, }, directives: [], }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'password' }, }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' }, }, }, directives: [], }, { kind: 'VariableDefinition', variable: { kind: 'Variable', name: { kind: 'Name', value: 'email' }, }, type: { kind: 'NonNullType', type: { kind: 'NamedType', name: { kind: 'Name', value: 'String' }, }, }, directives: [], }, ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'register' }, arguments: [ { kind: 'Argument', name: { kind: 'Name', value: 'newUserInput' }, value: { kind: 'ObjectValue', fields: [ { kind: 'ObjectField', name: { kind: 'Name', value: 'firstName' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'firstName' }, }, }, { kind: 'ObjectField', name: { kind: 'Name', value: 'password' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'password' }, }, }, { kind: 'ObjectField', name: { kind: 'Name', value: 'email' }, value: { kind: 'Variable', name: { kind: 'Name', value: 'email' }, }, }, ], }, }, ], directives: [], selectionSet: { kind: 'SelectionSet', selections: [ { kind: 'Field', name: { kind: 'Name', value: 'id' }, arguments: [], directives: [], }, { kind: 'Field', name: { kind: 'Name', value: 'firstName' }, arguments: [], directives: [], }, { kind: 'Field', name: { kind: 'Name', value: 'email' }, arguments: [], directives: [], }, ], }, }, ], }, }, ], }; export type RegisterUserMutationFn = ReactApollo.MutationFn< RegisterUserMutation, RegisterUserMutationVariables >; export function useRegisterUserMutation( baseOptions?: ReactApolloHooks.MutationHookOptions< RegisterUserMutation, RegisterUserMutationVariables >, ) { return ReactApolloHooks.useMutation< RegisterUserMutation, RegisterUserMutationVariables >(RegisterUserDocument, baseOptions); }
#if CHRONOS_PLAYMAKER using HutongGames.PlayMaker; using UnityEngine; namespace Chronos.PlayMaker { public abstract class ChronosComponentAction<T> : FsmStateAction where T : Component { private GameObject cachedGameObject; protected T component; protected Timeline timeline { get { return component as Timeline; } } protected Clock clock { get { return component as Clock; } } protected GlobalClock globalClock { get { return component as GlobalClock; } } protected LocalClock localClock { get { return component as LocalClock; } } protected IAreaClock areaClock { get { return component as IAreaClock; } } protected AreaClock3D areaClock3D { get { return component as AreaClock3D; } } protected AreaClock2D areaClock2D { get { return component as AreaClock2D; } } protected bool UpdateCache(GameObject go) { if (go == null) { return false; } if (component == null || cachedGameObject != go) { component = go.GetComponent<T>(); cachedGameObject = go; if (component == null) { LogWarning("Missing component: " + typeof(T).FullName + " on: " + go.name); } } return component != null; } } } #endif
#ifndef CPLUSPLUS10_DISCRETEMETRIC_H #define CPLUSPLUS10_DISCRETEMETRIC_H #include "MetricI.h" struct DiscreteMetric : MetricI{ virtual double distance(const Point& first, const Point& second); }; #endif //CPLUSPLUS10_DISCRETEMETRIC_H
import { z, ZodType } from 'zod'; import { CpuGeneratedSchema, GpuGeneratedSchema } from './generated'; export const CpuSchema = CpuGeneratedSchema.omit({ id: true, updatedAt: true, createdAt: true, }); export const GpuSchema = GpuGeneratedSchema.omit({ id: true, updatedAt: true, createdAt: true, }); export type FromSchema<T extends ZodType<any, any, any>> = z.infer<T>;
# hzDesktop A web desktop FOR FUN [demo](https://lionzhunter.github.io/hzDesktop/)
#### Description This is a program to find the distinct permutations of the string ### Author [wjyeap123](https://github.com/wjyeap123/)
<?php /** * Created by PhpStorm. * User: carlos_pambo * Date: 3/17/18 * Time: 8:30 AM */ namespace App\Http\Controllers\Address; use App\Address; use App\Http\Controllers\ApiController; use Carbon\Carbon; use Validator; use Illuminate\Http\Request; /** * Class DeviceController * * @package App\Http\Controllers\Device */ class AddressController extends ApiController { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $addresses = []; $result = Address::all(); foreach($result as $item){ $addresses [] = Address::model($item); } //return return $this->showList(collect($addresses)); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validator = Validator::make($request->all(), Address::createRules()); if ($validator->fails()) { return $this->errorResponse($validator->errors(), 400); } $address = new Address(); $address->house_no = $request->house_number; $address->street_no = $request->street_number; $address->street_name = $request->street_name; $address->suburb = $request->suburb; $address->city = $request->city; $address->province = $request->province; $address->country = $request->country; $address->postal_code = $request->postal_code; $address->created_by = $request->user()->id; $address->created_at = Carbon::now('CAT'); $address->updated_at = null; $address->save(); //return return $this->showList(collect(Address::model($address))); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $address = Address::model(Address::where('id', $id)->firstOrFail()); return $this->showOne(collect($address)); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id){ $address = Address::where('id', $id)->firstOrFail(); $validator = Validator::make($request->all(), Address::updateRules($id)); if ($validator->fails()) { return $this->errorResponse($validator->errors(), 400); } $address->house_no = $request->house_number; $address->street_no = $request->street_number; $address->street_name = $request->street_name; $address->suburb = $request->suburb; $address->city = $request->city; $address->province = $request->province; $address->country = $request->country; $address->postal_code = $request->postal_code; if($address->isClean()){ //if the site has not changed return $this->errorResponse('You need to specify a different value to update',400); } $address->updated_by = $request->user()->id; $address->updated_at = Carbon::now('CAT'); $address->save(); //return return $this->showOne(collect(Address::model($address))); } /** * Remove the specified resource from storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { $address = Address::where('id', $id)->firstOrFail(); $address->deleted_by = $request->user()->id; $address->save(); $address->delete(); //return return $this->showOne(collect(Address::model($address))); } }
package com.acrylic.ui import java.awt.Dimension import java.awt.Image import java.awt.Toolkit import javax.swing.JFrame import javax.swing.WindowConstants interface BaseUI { val jFrame: JFrame fun render() fun setupJFrame() { val jFrame = jFrame jFrame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE jFrame.isResizable = true jFrame.isVisible = true jFrame.pack() } fun setIcon(image: Image?): BaseUI? { jFrame.iconImage = image return this } fun setDimension(dimension: Dimension?): BaseUI? { val jFrame = jFrame jFrame.size = dimension jFrame.preferredSize = dimension jFrame.minimumSize = dimension jFrame.maximumSize = dimension return this } fun setDimension(width: Int, height: Int): BaseUI? { return setDimension(Dimension(width, height)) } fun setRelativeSize(): BaseUI? { return setRelativeSize(1f) } fun setRelativeSize(scale: Float): BaseUI? { val dimension = Toolkit.getDefaultToolkit().screenSize setDimension((dimension.getWidth() * scale).toInt(), (dimension.getHeight() * scale).toInt()) return this } }