text
stringlengths
27
775k
var util = require('util'); var Stream = require('stream'); // Use node 0.10's setImmediate for asynchronous operations, otherwise for // older versions of node use process.nextTick. var async = (typeof setImmediate === 'function') ? setImmediate : process.nextTick; module.exports = BufferedStream; /** * A readable/writable Stream subclass that buffers data until next tick. The * maxSize determines the number of bytes the buffer can hold before it is * considered "full". This argument may be omitted to indicate this stream has * no maximum size. * * The source and sourceEncoding arguments may be used to easily wrap this * stream around another, or a simple string. If the source is another stream, * it is piped to this stream. If it's a string, it is used as the entire * contents of this stream and passed to end. * * NOTE: The maxSize is a soft limit that is only used to determine when calls * to write will return false, indicating to streams that are writing to this * stream that they should pause. In any case, calls to write will still append * to the buffer so that no data is lost. */ function BufferedStream(maxSize, source, sourceEncoding) { if (!(this instanceof BufferedStream)) { return new BufferedStream(maxSize, source, sourceEncoding); } Stream.call(this); if (typeof maxSize !== 'number') { sourceEncoding = source; source = maxSize; maxSize = Infinity; } // Public interface. this.maxSize = maxSize; this.size = 0; this.encoding = null; this.paused = false; this.ended = false; this.readable = true; this.writable = true; this._buffer = []; this._flushing = false; this._wasFull = false; if (typeof source !== 'undefined') { if (source instanceof Stream) { source.pipe(this); } else { this.end(source, sourceEncoding); } } } util.inherits(BufferedStream, Stream); /** * A read-only property that returns true if this stream has no data to emit. */ BufferedStream.prototype.__defineGetter__('empty', function () { return this._buffer == null || this._buffer.length === 0; }); /** * A read-only property that returns true if this stream's buffer is full. */ BufferedStream.prototype.__defineGetter__('full', function () { return this.maxSize < this.size; }); /** * Sets this stream's encoding. If an encoding is set, this stream will emit * strings using that encoding. Otherwise, it emits Buffer objects. */ BufferedStream.prototype.setEncoding = function (encoding) { this.encoding = encoding; }; /** * Prevents this stream from emitting data events until resume is called. * Note: This does not prevent writes to this stream. */ BufferedStream.prototype.pause = function () { this.paused = true; }; /** * Resumes emitting data events. */ BufferedStream.prototype.resume = function () { if (this.paused) flushOnNextTick(this); this.paused = false; }; /** * Writes the given chunk of data to this stream. Returns false if this * stream is full and should not be written to further until drained, true * otherwise. */ BufferedStream.prototype.write = function (chunk, encoding) { if (!this.writable) throw new Error('Stream is not writable'); if (this.ended) throw new Error('Stream is already ended'); if (typeof chunk === 'string') chunk = new Buffer(chunk, encoding); this._buffer.push(chunk); this.size += chunk.length; flushOnNextTick(this); if (this.full) { this._wasFull = true; return false; } return true; }; /** * Writes the given chunk to this stream and queues the end event to be * called as soon as soon as possible. If the stream is not currently * scheduled to be flushed, the end event will fire immediately. Otherwise, it * will fire after the next flush. */ BufferedStream.prototype.end = function (chunk, encoding) { if (this.ended) throw new Error('Stream is already ended'); if (chunk != null) this.write(chunk, encoding); this.ended = true; // Trigger the flush cycle one last time to emit any data that // was written before end was called. flushOnNextTick(this); }; function flushOnNextTick(stream) { if (stream._flushing) return; stream._flushing = true; async(function tick() { if (stream.paused) { stream._flushing = false; return; } flush(stream); if (stream.empty) { stream._flushing = false; } else { async(tick); } }); } function flush(stream) { if (!stream._buffer) return; var chunk; while (stream._buffer.length) { chunk = stream._buffer.shift(); stream.size -= chunk.length; if (stream.encoding) { stream.emit('data', chunk.toString(stream.encoding)); } else { stream.emit('data', chunk); } // If the stream was paused in a data event handler, break. if (stream.paused) break; } if (stream.ended && !stream.paused) { stream._buffer = null; stream.emit('end'); } else if (stream._wasFull && !stream.full) { stream._wasFull = false; stream.emit('drain'); } }
## Implementation `live edit`的时候. 貌似最好实现一套`raw -> processed markdown html`的机制, 当然最后导出的时候还是从store中导出raw的内容. 为什么要自己实现`raw -> processed markdown html`呢~? 这样可以更好的保持对`.tc-line`中内容展现的控制. 控制好之后, dom结构应该是这样的: <div class="tc-line heading-2">some header</div> <div class="tc-line p">some paragrapha</div> <div class="tc-line quote">quote someone's words</div> <Ineo /> 这样就可以通过对`.tc-line`进行样式扩展(当然怎么实现把class赋给render的node还得去实现), 去展示不同的文本级别. 同时方便后续的操作: * 点击进入编辑状态 * 上下键跨越Ineo和`.tc-line` * 等等 而如果直接用现有的markdown直接去makeHtml然后dangerouslySetInnerHtml的话, 就会形成这样的情形: <div class="tc-line"><h2>some header</h2></div> <div class="tc-line"><p>some paragrapha</p></div> <div class="tc-line"><blockquote><p>quote someone's words</p></blockquote></div> <Ineo /> 这样就不好控制了...
package com.setapi.sparkDemo.spark_sql_demo import com.mongodb.spark.MongoSpark import com.stratio.datasource.mongodb._ import com.stratio.datasource.mongodb.config.MongodbConfig._ import com.stratio.datasource.mongodb.config.MongodbConfigBuilder import org.apache.log4j.{Level, Logger} import org.apache.spark.sql.SparkSession /** * * Created by ShellMount on 2019/8/25 * 使用SparkSQL实现 MongoDb 读写 * * https://blog.csdn.net/qq_33689414/article/details/83421766 * https://docs.mongodb.com/spark-connector/current/scala-api/ * * 程序调试未成功 **/ object SparkSessionReadMongoDb { // 日志设置 Logger.getRootLogger.setLevel(Level.WARN) val logger = Logger.getLogger(this.getClass) def main(args: Array[String]): Unit = { // 创建 SparkSession val sparkSession = SparkSession.builder() .appName("SparkSessionReadMongoDb") .master("local[2]") .config("spark.sql.warehouse.dir", "file:///E:\\APP\\BigData\\api\\spark-warehouse") .config("spark.mongodb.input.uri", "mongodb://192.168.0.110:27017/vnpy.db_tick_data") .getOrCreate() val df = MongoSpark.load(sparkSession) df.show /** * 程序结束 */ Thread.sleep(10000 * 1000) } }
<?php namespace Gf\Auth; //use Crossjoin\Browscap\Browscap; use Fuel\Core\Session; use Gf\Exception\AppException; use Gf\Platform; use Gf\Utils; /** * Makes a record of the current users login! * When using multiple logins and cookie based sessions, we lose control of the users login. because the session is * stored in the users browser. Using database sessions help to solve that problem by tracking each session with the * userid. This class fills in the gap between sessions and login history. * * @package Nb */ class SessionManager { public $sessionTable = 'sessions'; public $historyTable = 'user_login_history'; public $db = 'default'; public static $instance; /** * @return SessionManager */ public static function instance () { if (null === static::$instance) { static::$instance = new static(); } return static::$instance; } protected function __construct () { } /** * Creates snapshot for the current user's session and login details. * $session that is passed into as the first argument should be the returned array of LOGIN * for medium and medium_os * The user will be shown, you logged in from medium on medium_os * * @param $session * @param null $medium -> Browser * @param null $medium_os -> Operating system * @param null $platform -> the platform used. * * @return int * @throws \Exception */ public function create_snapshot (Array $session, $medium = null, $medium_os = null, $platform = null) { list($user_id, $user, $session_id) = $session; $platform = Platform::$web; if (Utils::phpVersion() >= 5.6) { $medium_os = 'Unknown'; $medium = 'Unknown'; } else { $medium_os = 'Unknown'; $medium = 'Unknown'; } $exists = $this->get([ 'user_id' => $user_id, 'session_id' => $session_id, ]); if ($exists) return 0; return $this->insert([ 'user_id' => $user_id, 'session_id' => $session_id, 'medium' => $medium, 'medium_os' => $medium_os, 'platform' => $platform, 'ip_address' => \Input::real_ip(), 'login_at' => Utils::timeNow(), 'active' => 1, ]); } public function get ($where, $select = null) { $data = \DB::select_array($select) ->from($this->historyTable) ->where($where) ->execute($this->db) ->as_array(); return (count($data)) ? $data : false; } public function get_one ($where, $select = null) { $data = $this->get($where, $select); return count($data) ? $data[0] : false; } public function logout_from_everywhere ($user_id) { $active_sessions = $this->get([ 'user_id' => $user_id, 'active' => 1, ]); if (!$active_sessions) return true; return $this->update([ 'user_id' => $user_id, 'active' => 1, ], [ 'active' => 0, ]); } /** * Sets the session as inactive. and removes the session. * thus results in a logout. * IMPORTANT: This function should be called after \Nb\Auth\Auth::logout is called. * * NOTE: session is already removed When Fuel's Auth::logout is called. * This function sets the session has inactive. * but also removes the session if it exists. * * @param $session_id * @param null $user_id * * @return object * @throws \Exception */ public function discard_session ($session_id = null, $user_id = null) { $session_id = Session::key(); $where = [ 'session_id' => $session_id, ]; if (!is_null($user_id)) $where['user_id'] = $user_id; return $this->update($where, [ 'active' => false, ]); } private function remove ($where) { return \DB::delete($this->historyTable) ->where($where) ->execute($this->db); } private function insert ($set) { list($id) = \DB::insert($this->historyTable) ->set($set) ->execute($this->db); return $id; } private function update ($where, $fields) { return \DB::update($this->historyTable) ->set($fields) ->where($where) ->execute($this->db); } }
#!/usr/bin/env bash conda env update -n py36zl -f environment.yml conda info --envs
{-# LANGUAGE OverloadedStrings, BangPatterns #-} module Network.Wai.Handler.Warp.PackInt where import Foreign.Ptr (Ptr, plusPtr) import Foreign.Storable (poke) import qualified Network.HTTP.Types as H import qualified Data.ByteString as B (cons, empty, unfoldr, reverse) import Network.Wai.Handler.Warp.Imports -- $setup -- >>> import Data.ByteString.Char8 as B -- >>> import Test.QuickCheck (Large(..)) -- | -- -- prop> packIntegral (abs n) == B.pack (show (abs n)) -- prop> \(Large n) -> let n' = fromIntegral (abs n :: Int) in packIntegral n' == B.pack (show n') packIntegral :: Integral a => a -> ByteString packIntegral 0 = "0" packIntegral n | n < 0 = error "packIntegral" packIntegral n = B.unfoldr ana n where ana :: Integral a => a -> Maybe (Word8, a) ana 0 = Nothing ana n = Just . first (fromIntegral . (+) 48) $ firstDigit n firstDigit n = divMod n (10 ^ (floor . logBase 10 . fromIntegral $ n)) first f (x,y) = (f x, y) {-# SPECIALIZE packIntegral :: Int -> ByteString #-} {-# SPECIALIZE packIntegral :: Integer -> ByteString #-} -- | -- -- >>> packStatus H.status200 -- "200" -- >>> packStatus H.preconditionFailed412 -- "412" packStatus :: H.Status -> ByteString packStatus status = foldr B.cons B.empty [r2,r1,r0] where !s = fromIntegral $ H.statusCode status (!q0,!r0) = s `divMod` 10 (!q1,!r1) = q0 `divMod` 10 !r2 = q1 `mod` 10
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT mod harness; mod vtable; pub use harness::*; pub use vtable::*; use serde::{Deserialize, Serialize}; /// The structure of `.kani-metadata.json` files, which are emitted for each crate #[derive(Serialize, Deserialize)] pub struct KaniMetadata { pub proof_harnesses: Vec<HarnessMetadata>, }
package org.neutrinocms.core.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.neutrinocms.core.exception.ControllerException; import org.neutrinocms.core.exception.ResourceNotFoundException; import org.neutrinocms.core.exception.UtilException; import org.neutrinocms.core.model.independant.Folder; import org.neutrinocms.core.util.CommonUtil; import org.springframework.context.annotation.Scope; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class LoginController extends AbstractController { public static final String LOGINPAGE = "login"; public static final String BACKFOLDER = "back"; @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView view(Folder folder) throws ControllerException, ResourceNotFoundException { ModelAndView modelAndView = null; try { try { modelAndView = baseView(LOGINPAGE, null, folder); } catch (ResourceNotFoundException e1) { folder = common.getFolder(CommonUtil.BACK); modelAndView = baseView(LOGINPAGE, null, folder); } return modelAndView; } catch (UtilException e) { throw new ControllerException(e); } } @RequestMapping(value="/logout", method = RequestMethod.GET) public String logoutPage (HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null){ new SecurityContextLogoutHandler().logout(request, response, auth); } return "redirect:/login?logout"; } }
unit Prototype.Cloneable; interface uses System.Classes; type TCloneable = class strict private FData: TStream; FIsBar: boolean; FName: string; public constructor Create; constructor CreateFrom(baseObj: TCloneable); destructor Destroy; override; procedure Assign(baseObj: TCloneable); function Clone: TCloneable; function FooBar: string; property Data: TStream read FData; property Name: string read FName write FName; end; implementation uses System.SysUtils, System.StrUtils; constructor TCloneable.Create; begin inherited Create; FData := TMemoryStream.Create; end; constructor TCloneable.CreateFrom(baseObj: TCloneable); begin Create; Assign(baseObj); end; destructor TCloneable.Destroy; begin FreeAndNil(FData); inherited; end; procedure TCloneable.Assign(baseObj: TCloneable); var dataPos: int64; begin // make copy of published data Name := baseObj.Name; // clone state of owned objects // make sure not to destroy the state of owned objects during the process! dataPos := baseObj.Data.Position; Data.CopyFrom(baseObj.Data, 0); baseObj.Data.Position := dataPos; Data.Position := dataPos; // clone private state FIsBar := baseObj.FIsBar; end; function TCloneable.Clone: TCloneable; var dataPos: int64; begin Result := TCloneable.Create; // make copy of published data Result.Name := Name; // clone state of owned objects // make sure not to destroy the state of owned objects during the process! dataPos := Data.Position; Result.Data.CopyFrom(Data, 0); Data.Position := dataPos; Result.Data.Position := dataPos; // clone private state Result.FIsBar := FIsBar; end; function TCloneable.FooBar: string; begin Result := IfThen(FIsBar, 'Bar', 'Foo'); FIsBar := not FIsBar; end; end.
# encoding: utf-8 require 'test_helper' class TokenManagerTest < Minitest::Test def test_eof token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('')))::get_next_token assert_equal(Koara::TokenManager::EOF, token.kind) end def test_asterisk token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('*'))).get_next_token assert_equal(Koara::TokenManager::ASTERISK, token.kind) assert_equal('*', token.image) end def test_backslash token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('\\'))).get_next_token assert_equal(Koara::TokenManager::BACKSLASH, token.kind) assert_equal('\\', token.image) end def test_backtick token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('`'))).get_next_token assert_equal(Koara::TokenManager::BACKTICK, token.kind) assert_equal('`', token.image) end def test_char_sequence_lowercase token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('m'))).get_next_token assert_equal(Koara::TokenManager::CHAR_SEQUENCE, token.kind) assert_equal('m', token.image) end def test_char_sequence_uppercase token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('C'))).get_next_token assert_equal(Koara::TokenManager::CHAR_SEQUENCE, token.kind) assert_equal('C', token.image) end def test_colon token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new(':'))).get_next_token assert_equal(Koara::TokenManager::COLON, token.kind) assert_equal(':', token.image) end def test_dash token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('-'))).get_next_token assert_equal(Koara::TokenManager::DASH, token.kind) assert_equal('-', token.image) end def test_digits token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('4'))).get_next_token assert_equal(Koara::TokenManager::DIGITS, token.kind) assert_equal('4', token.image) end def test_dot token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('.'))).get_next_token assert_equal(Koara::TokenManager::DOT, token.kind) assert_equal('.', token.image) end def test_eol token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new("\n"))).get_next_token assert_equal(Koara::TokenManager::EOL, token.kind) assert_equal("\n", token.image) end def test_eol_with_spaces token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new(" \n"))).get_next_token assert_equal(Koara::TokenManager::EOL, token.kind) assert_equal(" \n", token.image) end def test_eq token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('='))).get_next_token assert_equal(Koara::TokenManager::EQ, token.kind) assert_equal('=', token.image) end def test_escaped_char token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new("\\*"))).get_next_token assert_equal(Koara::TokenManager::ESCAPED_CHAR, token.kind) assert_equal("\\*", token.image) end def test_gt token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('>'))).get_next_token assert_equal(Koara::TokenManager::GT, token.kind) assert_equal('>', token.image) end def test_image_label token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('image:'))).get_next_token assert_equal(Koara::TokenManager::IMAGE_LABEL, token.kind) assert_equal('image:', token.image) end def test_lbrack token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('['))).get_next_token assert_equal(Koara::TokenManager::LBRACK, token.kind) assert_equal('[', token.image) end def test_lparen token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('('))).get_next_token assert_equal(Koara::TokenManager::LPAREN, token.kind) assert_equal('(', token.image) end def test_lt token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('<'))).get_next_token assert_equal(Koara::TokenManager::LT, token.kind) assert_equal('<', token.image) end def test_rbrack token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new(']'))).get_next_token assert_equal(Koara::TokenManager::RBRACK, token.kind) assert_equal(']', token.image) end def test_rparen token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new(')'))).get_next_token assert_equal(Koara::TokenManager::RPAREN, token.kind) assert_equal(')', token.image) end def test_space token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new(' '))).get_next_token assert_equal(Koara::TokenManager::SPACE, token.kind) assert_equal(' ', token.image) end def test_tab token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new("\t"))).get_next_token assert_equal(Koara::TokenManager::TAB, token.kind) assert_equal("\t", token.image) end def test_underscore token = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new('_'))).get_next_token assert_equal(Koara::TokenManager::UNDERSCORE, token.kind) assert_equal('_', token.image) end def test_linebreak tm = Koara::TokenManager.new(Koara::CharStream.new(Koara::Io::StringReader.new("a\nb"))) token = tm.get_next_token assert_equal(Koara::TokenManager::CHAR_SEQUENCE, token.kind) assert_equal('a', token.image) token = tm.get_next_token assert_equal(Koara::TokenManager::EOL, token.kind) assert_equal("\n", token.image) token = tm.get_next_token assert_equal(Koara::TokenManager::CHAR_SEQUENCE, token.kind) end end
<?php require('toc.php'); $pdf = new PDF_TOC(); $pdf->SetFont('Times', '', 12); $pdf->AddPage(); $pdf->Cell(0, 5, 'Cover', 0, 1, 'C'); $pdf->AddPage(); $pdf->startPageNums(); $pdf->Cell(0, 5, 'TOC1', 0, 1, 'L'); $pdf->TOC_Entry('TOC1', 0); $pdf->Cell(0, 5, 'TOC1.1', 0, 1, 'L'); $pdf->TOC_Entry('TOC1.1', 1); $pdf->AddPage(); $pdf->Cell(0, 5, 'TOC2', 0, 1, 'L'); $pdf->TOC_Entry('TOC2', 0); $pdf->AddPage(); for ($i = 3; $i <= 80; $i++) { $pdf->Cell(0, 5, 'TOC' . $i, 0, 1, 'L'); $pdf->TOC_Entry('TOC' . $i, 0); } $pdf->stopPageNums(); $pdf->AddPage(); $pdf->Cell(0, 5, 'Unnumbered page', 0, 1, 'L'); //Generate and insert TOC at page 2 $pdf->insertTOC(2); $pdf->Output(); ?>
default['cockpit_install']['action'] = 'install' default['cockpit_install']['machines'] = {} default['cockpit_install']['auto_discover'] = false default['cockpit_install']['auto_discover_filter'] = nil
require 'test_helper' require 'rake' class DSLTest < Minitest::Test include RakeRemoteFile::DSL def setup ENV['AWS_REGION'] = 'us-east-1' ENV['AWS_ACCESS_KEY_ID'] = 'key' ENV['AWS_SECRET_ACCESS_KEY'] = 'secret' end def test_remote_file_task url = "https://s3.amazonaws.com/my_bucket/a/file/path" remote_file 'local_file', url task = Rake::Task['local_file'] assert !task.nil? assert_equal 'local_file', task.name end end
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.skupper.throttleService; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import io.vertx.core.Vertx; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; @Path("/hello") public class ThrottleService { @Inject Vertx vertx; private int ratePerTenth; private String hostname = System.getenv("HOSTNAME"); private int count = 0; // // The following state members are accessed by multiple threads. Access to these // variables must be synchronized. // private Object lock = new Object(); private int sendSlots = 1; private List<CompletableFuture<String>> pendingFutures = new ArrayList<CompletableFuture<String>>(); private List<String> pendingResponses = new ArrayList<String>(); public void SetupTimer() { // // Attempt to get the rate limit from the environment. If unable, default to // a ratePerTenth of 1 (10 responses per second). // try { ratePerTenth = Integer.parseInt(System.getenv("RATE_LIMIT")); } catch (NumberFormatException e) { ratePerTenth = 1; } // // Set up a timer to process deferred responses in batches every 100 milliseconds. // vertx.setPeriodic(100, l -> { synchronized(lock) { sendSlots = ratePerTenth; while (sendSlots > 0 && !pendingResponses.isEmpty()) { sendSlots--; String response = pendingResponses.remove(0); CompletableFuture<String> future = pendingFutures.remove(0); future.complete(response); } } }); } @GET @Produces(MediaType.TEXT_PLAIN) public CompletionStage<String> hello() { if (count == 0) SetupTimer(); // // Create a response to the GET that includes the pod name and the request count. // count++; String response = String.format("{\"pod\":\"%s\",\"count\":\"%d\"}", hostname, count); CompletableFuture<String> future = new CompletableFuture<>(); // // If there is at least one available slot, respond immediately. If not, we are being // rate-limited and the response must be deferred. // boolean noDelay = false; synchronized(lock) { if (sendSlots > 0) { sendSlots--; noDelay = true; } else { pendingResponses.add(response); pendingFutures.add(future); } } if (noDelay) { future.complete(response); } return future; } }
class ProviderModel { const ProviderModel({this.copyable = false}); final bool copyable; } class ProviderModelProp { const ProviderModelProp({this.nullable = true}); final bool nullable; }
package net.gtaun.shoebill.common import net.gtaun.shoebill.Shoebill import net.gtaun.util.event.EventManager /** * Created by marvin on 14.11.16 in project shoebill-common. * Copyright (c) 2016 Marvin Haschker. All rights reserved. */ @AllOpen abstract class LifecycleObject @JvmOverloads constructor(eventManager: EventManager = Shoebill.get().eventManager) : AbstractShoebillContext(eventManager)
--- id: 382ee147 title: Planned Maintenance description: We detected a networking problem that caused temporary issues for our API and origin servers. date: 2020-03-15T21:33:18.362Z modified: 2020-03-15T23:33:18.362Z severity: under-maintenance resolved: true affectedsystems: - api --- We detected a networking problem that caused temporary issues for our API and origin servers. ::: update Resolved | 2020-03-15T23:33:18.362Z Our Files Conversion Process is responding slowly and we've investigating what is causing this issue. ::: ::: update Monitoring | 2020-03-15T22:33:18.362Z Our Files Conversion System is not responding properly and we've investigating what is causing this issue. If you're affected by this issue, you can contact us at our [Support Page](https://statusfy.marquez.co). ::: ::: update Resolved | 2020-03-15T22:03:18.362Z Our Files Conversion System is not responding properly and we've investigating what is causing this issue. :::
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Entity * @ORM\Table( * name="user", * uniqueConstraints={ * @ORM\UniqueConstraint(columns={"name"}), * @ORM\UniqueConstraint(columns={"email"}) * } * ) * @UniqueEntity(fields="name", message="Username already taken"), * @UniqueEntity(fields="email", message="Email already taken") */ class User { /** * @ORM\Column(type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="string", length=100, nullable=false) */ private $name; /** * @ORM\Column(type="string", nullable=false) */ private $email; /** * @ORM\Column(type="string", nullable=false) */ private $hash; /** * @ORM\Column(type="boolean", nullable=false, options = {"default": false}) */ private $notify_poll = false; /** * @ORM\Column(type="boolean", nullable=false, options = {"default": true}) */ private $notify_result = true; /** * @ORM\Column(type="boolean", nullable=false, options = {"default": false}) */ private $blocked = false; /** * @ORM\Column(type="boolean", nullable=false, options = {"default": false}) */ private $is_admin = false; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return User */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set email * * @param string $email * * @return User */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set notifyPoll * * @param boolean $notifyPoll * * @return User */ public function setNotifyPoll($notifyPoll) { $this->notify_poll = $notifyPoll; return $this; } /** * Get notifyPoll * * @return boolean */ public function getNotifyPoll() { return $this->notify_poll; } /** * Set notifyResult * * @param boolean $notifyResult * * @return User */ public function setNotifyResult($notifyResult) { $this->notify_result = $notifyResult; return $this; } /** * Get notifyResult * * @return boolean */ public function getNotifyResult() { return $this->notify_result; } /** * Set blocked * * @param boolean $blocked * * @return User */ public function setBlocked($blocked) { $this->blocked = $blocked; return $this; } /** * Get blocked * * @return boolean */ public function getBlocked() { return $this->blocked; } /** * Set isAdmin * * @param boolean $isAdmin * * @return User */ public function setIsAdmin($isAdmin) { $this->is_admin = $isAdmin; return $this; } /** * Get isAdmin * * @return boolean */ public function getIsAdmin() { return $this->is_admin; } /** * Set hash * * @param string $hash * * @return User */ public function setHash($hash) { $this->hash = $hash; return $this; } /** * Get hash * * @return string */ public function getHash() { return $this->hash; } }
package org.monarchinitiative.hpo_case_annotator.core.publication; public enum PublicationDataFormat { EUTILS, PUBMED_SUMMARY }
import React from 'react'; // @ts-ignore: library file import import * as pc from 'playcanvas/build/playcanvas.prf.js'; // @ts-ignore: library file import import * as pcx from 'playcanvas/build/playcanvas-extras.js'; import Example from '../../app/example'; import { AssetLoader } from '../../app/helpers/loader'; class ClusteredLightingExample extends Example { static CATEGORY = 'Graphics'; static NAME = 'Clustered Lighting'; static ENGINE = 'PERFORMANCE'; load() { return <> <AssetLoader name='normal' type='texture' url='static/assets/textures/normal-map.png' /> </>; } // @ts-ignore: override class function example(canvas: HTMLCanvasElement, assets: { normal: pc.Asset }): void { // Create the application and start the update loop const app = new pc.Application(canvas, {}); const pointLightList: Array<pc.Entity> = []; const spotLightList: Array<pc.Entity> = []; let dirLight: pc.Entity = null; app.start(); // enabled clustered lighting. This is a temporary API and will change in the future // @ts-ignore engine-tsd pc.LayerComposition.clusteredLightingEnabled = true; // adjust default clusterered lighting parameters to handle many lights: // 1) subdivide space with lights into this many cells: // @ts-ignore engine-tsd app.scene.layers.clusteredLightingCells = new pc.Vec3(12, 16, 12); // 2) and allow this many lights per cell: // @ts-ignore engine-tsd app.scene.layers.clusteredLightingMaxLights = 48; // Set the canvas to fill the window and automatically change resolution to be the same as the canvas size app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW); app.setCanvasResolution(pc.RESOLUTION_AUTO); window.addEventListener("resize", function () { app.resizeCanvas(canvas.width, canvas.height); }); // set up options for mini-stats, start with the default options and add clusted lighting stats const options = pcx.MiniStats.getDefaultOptions(); options.stats.push( { // CPU time it takes to process the clusters each frame name: "Clusters", stats: ["frame.lightClustersTime"], decimalPlaces: 2, unitsName: "ms", watermark: 3 }, { // number of clusters used internally // should be one if all lights are on the same set of layers name: "Num Clusters", stats: ["frame.lightClusters"], watermark: 3 } ); // create mini-stats system const miniStats = new pcx.MiniStats(app, options); // material with tiled normal map let material = new pc.StandardMaterial(); material.normalMap = assets.normal.resource; material.normalMapTiling.set(5, 5); material.bumpiness = 2; material.update(); // ground plane const ground = new pc.Entity(); ground.addComponent('render', { type: "plane", material: material }); ground.setLocalScale(150, 150, 150); app.root.addChild(ground); // high polycount cylinder const cylinderMesh = pc.createCylinder(app.graphicsDevice, { capSegments: 200 }); const cylinder = new pc.Entity(); cylinder.addComponent('render', { material: material, meshInstances: [new pc.MeshInstance(cylinderMesh, material)], castShadows: true }); app.root.addChild(cylinder); cylinder.setLocalPosition(0, 50, 0); cylinder.setLocalScale(50, 100, 50); // create many omni lights that do not cast shadows let count = 30; const intensity = 1.6; for (let i = 0; i < count; i++) { const color = new pc.Color(intensity * Math.random(), intensity * Math.random(), intensity * Math.random(), 1); const lightPoint = new pc.Entity(); lightPoint.addComponent("light", { type: "omni", color: color, range: 12, castShadows: false }); // attach a render component with a small sphere to each light const material = new pc.StandardMaterial(); material.emissive = color; material.update(); lightPoint.addComponent('render', { type: "sphere", material: material, castShadows: true }); lightPoint.setLocalScale(5, 5, 5); // add it to the scene and also keep it in an array app.root.addChild(lightPoint); pointLightList.push(lightPoint); } // create many spot lights count = 16; for (let i = 0; i < count; i++) { const color = new pc.Color(intensity * Math.random(), intensity * Math.random(), intensity * Math.random(), 1); const lightSpot = new pc.Entity(); lightSpot.addComponent("light", { type: "spot", color: color, innerConeAngle: 5, outerConeAngle: 6 + Math.random() * 40, range: 25, castShadows: false }); // attach a render component with a small cone to each light material = new pc.StandardMaterial(); material.emissive = color; material.update(); lightSpot.addComponent('render', { type: "cone", material: material }); lightSpot.setLocalScale(5, 5, 5); lightSpot.setLocalPosition(100, 50, 70); lightSpot.lookAt(new pc.Vec3(100, 60, 70)); app.root.addChild(lightSpot); spotLightList.push(lightSpot); } // Create a single directional light which casts shadows dirLight = new pc.Entity(); dirLight.addComponent("light", { type: "directional", color: pc.Color.WHITE, intensity: 0.2, range: 300, shadowDistance: 300, castShadows: true, shadowBias: 0.2, normalOffsetBias: 0.05 }); app.root.addChild(dirLight); // Create an entity with a camera component const camera = new pc.Entity(); camera.addComponent("camera", { clearColor: new pc.Color(0.2, 0.2, 0.2), farClip: 500, nearClip: 0.1 }); camera.setLocalPosition(120, 120, 120); camera.lookAt(new pc.Vec3(0, 40, 0)); app.root.addChild(camera); // Set an update function on the app's update event let time = 0; app.on("update", function (dt: number) { time += dt; // move lights along sin based waves around the cylinder pointLightList.forEach(function (light, i) { const angle = (i / pointLightList.length) * Math.PI * 2; const y = Math.sin(time * 0.5 + 7 * angle) * 30 + 70; light.setLocalPosition(30 * Math.sin(angle), y, 30 * Math.cos(angle)); }); // rotate spot lights around spotLightList.forEach(function (spotlight, i) { const angle = (i / spotLightList.length) * Math.PI * 2; spotlight.setLocalPosition(40 * Math.sin(time + angle), 5, 40 * Math.cos(time + angle)); spotlight.lookAt(pc.Vec3.ZERO); spotlight.rotateLocal(90, 0, 0); }); // rotate direcional light if (dirLight) { dirLight.setLocalEulerAngles(25, -30 * time, 0); } }); } } export default ClusteredLightingExample;
set -e GITLAB_DB_USER=${GITLAB_DB_USER:-git} GITLAB_DB_NAME=${GITLAB_DB_NAME:-gitlabhq_production} psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -d template1 <<-EOSQL CREATE EXTENSION IF NOT EXISTS pg_trgm; CREATE USER "$GITLAB_DB_USER" CREATEDB; CREATE DATABASE "$GITLAB_DB_NAME" OWNER "$GITLAB_DB_USER"; GRANT ALL PRIVILEGES ON DATABASE "$GITLAB_DB_NAME" TO "$GITLAB_DB_USER"; EOSQL
#!/bin/bash # Script helping users run a go docker image to encapsulate the runtime. # # This script helps to remove the need for maintaining your own local go environment and runtime. # Through the use of a golang:1.11.4 docker image, as well as local bind mounts, the container # is able to access your files in this directory directly, and is able to run them natively. docker run -it --rm \ --name hello-go \ --mount type=bind,source="$(pwd)",target=/go/src/app \ --mount type=bind,source="$(pwd)/.bashrc",target=/root/.bashrc \ --workdir="/go/src/app/" \ -p 3000:3000 \ golang:1.14.4 \ /bin/bash
#!/usr/bin/env python import csv import pathlib CURRENT_DIR = pathlib.Path(__file__).parent.absolute() class Country(): def __init__(self, row): self.name, self.code, _, _, lat, long = row self.lat = float(lat) self.long = float(long) self.loc = self.name self.elos = [] def __str__(self): return "{}, {}, lat: {}, long: {}, loc: {}".format(self.name, self.code, self.lat, self.long, self.loc) def country_map(): mappings = {} with open('{}/{}'.format(CURRENT_DIR, 'country_map.csv')) as f: reader = csv.reader(f) for row in reader: mappings[row[0]] = row[1] return mappings def country_dict(): countries = {} mappings = country_map() with open('{}/{}'.format(CURRENT_DIR, 'countries_codes_and_coordinates.csv')) as f: reader = csv.reader(f) for row in reader: country = Country(row) if country.code in mappings: country.loc = mappings[country.code] countries[country.code] = country return countries if __name__ == '__main__': c = country_dict() for x in c.values(): print(x)
@{ ViewData["Title"] = "Home Page"; } <h2> This is a ASP .NET web application deployed on Azure App Service </h2>
///--------------------------------------------------------------------------------------------------------------------- /// <copyright company="Microsoft"> /// Copyright (c) Microsoft Corporation. All rights reserved. /// </copyright> ///--------------------------------------------------------------------------------------------------------------------- namespace ExpressionBuilder { using Microsoft.UI.Composition; public sealed class ManipulationPropertySetReferenceNode : PropertySetReferenceNode { internal ManipulationPropertySetReferenceNode(string paramName, CompositionPropertySet ps = null) : base(paramName, ps) { } // Needed for GetSpecializedReference<> internal ManipulationPropertySetReferenceNode() : base(null, null) { } // Animatable properties public Vector3Node CenterPoint { get { return ReferenceProperty<Vector3Node>("CenterPoint"); } } public Vector3Node Pan { get { return ReferenceProperty<Vector3Node>("Pan"); } } public Vector3Node Scale { get { return ReferenceProperty<Vector3Node>("Scale"); } } public Vector3Node Translation { get { return ReferenceProperty<Vector3Node>("Translation"); } } public Matrix4x4Node Matrix { get { return ReferenceProperty<Matrix4x4Node>("Matrix"); } } } }
# -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # based on: http://code.activestate.com/recipes/573463/ # Modified by Philippe Normand # Copyright 2008, Frank Scholz <[email protected]> from coherence.extern.et import ET as ElementTree, indent, parse_xml class ConfigItem(object): """ the base """ class Config(ConfigItem): def __init__(self,filename,root=None,preamble=False,element2attr_mappings=None): self.filename = filename self.element2attr_mappings = element2attr_mappings or {} self.db = parse_xml(open(self.filename).read()) self.config = self.db = ConvertXmlToDict(self.db.getroot()) self.preamble = '' if preamble == True: self.preamble = """<?xml version="1.0" encoding="utf-8"?>\n""" if root != None: try: self.config = self.config[root] except KeyError: pass self.config.save = self.save def tostring(self): root = ConvertDictToXml(self.db,self.element2attr_mappings) tree = ElementTree.ElementTree(root).getroot() indent(tree,0) xml = self.preamble + ElementTree.tostring(tree, encoding='utf-8') return xml def save(self, new_filename=None): if new_filename != None: self.filename = new_filename xml = self.tostring() f = open(self.filename, 'wb') f.write(xml) f.close() def get(self,key,default=None): if key in self.config: item = self.config[key] try: if item['active'] == 'no': return default return item except (TypeError,KeyError): return item return default def set(self,key,value): self.config[key] = value class XmlDictObject(dict,ConfigItem): def __init__(self, initdict=None): if initdict is None: initdict = {} dict.__init__(self, initdict) self._attrs = {} def __getattr__(self, item): value = self.__getitem__(item) try: if value['active'] == 'no': raise KeyError except (TypeError,KeyError): return value return value def __setattr__(self, item, value): if item == '_attrs': object.__setattr__(self, item, value) else: self.__setitem__(item, value) def get(self,key,default=None): try: item = self[key] try: if item['active'] == 'no': return default return item except (TypeError,KeyError): return item except KeyError: pass return default def set(self,key,value): self[key] = value def __str__(self): if self.has_key('_text'): return self.__getitem__('_text') else: return '' def __repr__(self): return repr(dict(self)) @staticmethod def Wrap(x): if isinstance(x, dict): return XmlDictObject((k, XmlDictObject.Wrap(v)) for (k, v) in x.iteritems()) elif isinstance(x, list): return [XmlDictObject.Wrap(v) for v in x] else: return x @staticmethod def _UnWrap(x): if isinstance(x, dict): return dict((k, XmlDictObject._UnWrap(v)) for (k, v) in x.iteritems()) elif isinstance(x, list): return [XmlDictObject._UnWrap(v) for v in x] else: return x def UnWrap(self): return XmlDictObject._UnWrap(self) def _ConvertDictToXmlRecurse(parent, dictitem,element2attr_mappings=None): assert type(dictitem) is not type([]) if isinstance(dictitem, dict): for (tag, child) in dictitem.iteritems(): if str(tag) == '_text': parent.text = str(child) ## elif str(tag) == '_attrs': ## for key, value in child.iteritems(): ## parent.set(key, value) elif element2attr_mappings != None and tag in element2attr_mappings: parent.set(element2attr_mappings[tag],child) elif type(child) is type([]): for listchild in child: elem = ElementTree.Element(tag) parent.append(elem) _ConvertDictToXmlRecurse(elem, listchild,element2attr_mappings=element2attr_mappings) else: if(not isinstance(dictitem, XmlDictObject) and not callable(dictitem)): attrs = dictitem dictitem = XmlDictObject() dictitem._attrs = attrs if tag in dictitem._attrs: parent.set(tag, child) elif not callable(tag) and not callable(child): elem = ElementTree.Element(tag) parent.append(elem) _ConvertDictToXmlRecurse(elem, child,element2attr_mappings=element2attr_mappings) else: if not callable(dictitem): parent.text = str(dictitem) def ConvertDictToXml(xmldict,element2attr_mappings=None): roottag = xmldict.keys()[0] root = ElementTree.Element(roottag) _ConvertDictToXmlRecurse(root, xmldict[roottag],element2attr_mappings=element2attr_mappings) return root def _ConvertXmlToDictRecurse(node, dictclass): nodedict = dictclass() ## if node.items(): ## nodedict.update({'_attrs': dict(node.items())}) if len(node.items()) > 0: # if we have attributes, set them attrs = dict(node.items()) nodedict.update(attrs) nodedict._attrs = attrs for child in node: # recursively add the element's children newitem = _ConvertXmlToDictRecurse(child, dictclass) if nodedict.has_key(child.tag): # found duplicate tag, force a list if type(nodedict[child.tag]) is type([]): # append to existing list nodedict[child.tag].append(newitem) else: # convert to list nodedict[child.tag] = [nodedict[child.tag], newitem] else: # only one, directly set the dictionary nodedict[child.tag] = newitem if node.text is None: text = '' else: text = node.text.strip() if len(nodedict) > 0: # if we have a dictionary add the text as a dictionary value (if there is any) if len(text) > 0: nodedict['_text'] = text else: # if we don't have child nodes or attributes, just set the text if node.text is not None: nodedict = node.text.strip() return nodedict def ConvertXmlToDict(root,dictclass=XmlDictObject): return dictclass({root.tag: _ConvertXmlToDictRecurse(root, dictclass)}) def main(): c = Config('config.xml',root='config') #print '%r' % c.config #c.save(new_filename='config.new.xml') print c.config['interface'] #for plugin in c.config.pluginlist.plugin: # if plugin.active != 'no': # print '%r' % plugin if __name__ == '__main__': main()
/* * * Created by mahmoud on 12/27/21, 11:33 PM * Copyright (c) 2021 . All rights reserved. * Last modified 12/22/21, 10:24 AM */ package com.mahmoud.dfont.extensions import android.util.Log import android.view.View import androidx.core.content.res.ResourcesCompat import com.mahmoud.dfont.services.ChangeableTypefaceViews import com.mahmoud.dfont.services.DFontSharedPreferences import com.mahmoud.dfont.utils.DFontKeys.DFONT_TAG /** * When this function is called, * - First check if the view hasTypeface using [ChangeableTypefaceViews.hasTypeface] function * - Get typeface from sharedPreferences using [DFontSharedPreferences.getInt] then check if it is * not [ResourcesCompat.ID_NULL] * - Call [ChangeableTypefaceViews.changeTypeface] to change view typeface accirdingly * * @see ChangeableTypefaceViews.hasTypeface * @see DFontSharedPreferences.getInt, * @see ChangeableTypefaceViews.changeTypeface */ fun View.notifyTypefaceChanged() { if (!ChangeableTypefaceViews.hasTypeface(this)) { Log.d(DFONT_TAG, "notifyTypefaceChanged: ${this.javaClass.name} has no typeface.") return } val typeface = DFontSharedPreferences.getFont() if (typeface == ResourcesCompat.ID_NULL) { Log.d(DFONT_TAG, "No typeface stored in DFontSharedPreferences. Call " + "DFontSharedPreferences.saveFont(...) to save your desired font") return } // TODO: check if view typeface is identical to @typeface variable ChangeableTypefaceViews.changeTypeface(this, context, typeface) }
using System; using Fivet.ZeroIce.model; using Ice; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Fivet.ZeroIce { /// <summary> /// The Implementation of TheSystem interface /// </summary> public class TheSystemImpl : TheSystemDisp_ { /// <summary> /// The Logger /// </summary> private readonly ILogger<TheSystemImpl> _logger; /// <summary> /// The Constructor /// </summary> /// <param name="logger">The Logger</param> /// <param name="serviceScopeFactory">The Scope</param> public TheSystemImpl(ILogger<TheSystemImpl> logger, IServiceScopeFactory serviceScopeFactory) { _logger = logger; _logger.LogDebug("Building TheSystemImpl..."); } /// <summary> /// Return the difference in time /// </summary> /// <param name="clienTime"></param> /// <param name="current"></param> /// <returns>The Delay</returns> public override long getDelay(long clienTime, Current current = null) { return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - clienTime; } } }
angular.module('LearnversationApp') .controller('userProfileCtrl', ['usersFactory', 'usersLanguagesFactory', 'languagesFactory', 'levelsFactory', 'userProfileImagesFactory', 'commentsFactory', '$route', '$location', '$scope', '$routeParams', function(usersFactory, usersLanguagesFactory, languagesFactory, levelsFactory, userProfileImagesFactory, commentsFactory, $route, $location, $scope, $routeParams) { var vm = this; vm.loggedUser = {}; vm.visitedUser = {}; vm.images = []; vm.languages = []; vm.levels = []; vm.users = []; vm.userIdFromPath = ""; vm.userLanguages = {}; vm.comments = {}; vm.errorMessage = ""; vm.messageState = ""; vm.boxComment = {}; vm.boxComment.idc = ""; vm.boxComment.receiver = ""; vm.boxComment.sender = ""; vm.boxComment.text = ""; vm.boxComment.timeStamp = ""; vm.userPath = ""; vm.editing = false; vm.functions = { getLanguages : function() { languagesFactory.getAllLanguages() .then(function(response){ console.log("Getting all languages:", response); vm.languages = response; }, function(response){ console.log("Error obteniendo los lenguajes"); }) }, getLevels : function() { levelsFactory.getAllLevels() .then(function(response){ console.log("Getting all levels:", response); vm.levels = response; }, function (response) { console.log("Error obteniendo los niveles") }) }, getProfileImages : function(){ userProfileImagesFactory.getAllProfileImages(). then(function(response){ vm.images = response; console.log("Getting user images", response); }, function(response){ console.log("Error obteniendo las imágenes de los users") }) }, getAllUsers : function(){ usersFactory.getAllUsers() .then(function(response){ vm.users = response; console.log("Todos los usuarios", vm.users); }, function(response){ console.log("Error obteniendo todos los usuarios"); }) } ,getComments : function(){ var userId = ""; if(vm.editing == true) userId = vm.loggedUser.idu; else userId = vm.visitedUser.idu; commentsFactory.getAllCommentsByReceiver(userId) .then(function(response){ vm.comments = response; console.log("comments : ", vm.comments); }, function(response){ console.log("error getting comments", response.status); }) }, getUserInSession : function(){ usersFactory.getLoggedUser(). then(function(response){ vm.loggedUser = response; vm.functions.getUserPath(); console.log("Obteniendo user ", vm.loggedUser.username); }, function(response){ console.log("Error obteniendo el usuario logueado", response.status); }) }, getUserPath : function(){ vm.userPath = $location.path(); if(vm.userPath == "/userProfile/myProfile"){ vm.editing = true; vm.functions.getUserLanguages(); vm.functions.getComments(); }else{ vm.userIdFromPath = $routeParams.ID; console.log("string parseado", vm.userIdFromPath); vm.functions.getUserVisited(); } console.log("userPath", vm.userPath); }, getUserVisited : function(){ usersFactory.getUserById(vm.userIdFromPath) .then(function(response){ vm.visitedUser = response; vm.functions.getUserLanguages(); vm.functions.getComments(); }, function(response){ console.log("error obteniendo el usuario visitado"); }) }, getUserLanguages : function(){ var userId = ""; if(vm.editing == true) userId = vm.loggedUser.idu; else userId = vm.visitedUser.idu; usersLanguagesFactory.getUserLanguagesByUser(userId) .then(function(response){ vm.userLanguages = response; console.log("lenguajes del user :", vm.userLanguages); }, function(response){ console.log("error getting users language", response.code); }) }, sendComment : function(){ vm.boxComment.receiver = vm.visitedUser.idu; vm.boxComment.sender = vm.loggedUser.idu; commentsFactory.addComment(vm.boxComment) .then(function(response){ vm.functions.getComments(); vm.messageState = "Mensaje enviado con éxito"; vm.boxComment.text = ""; vm.errorMessage = ""; }, function(response){ console.log("error sending comment", response); vm.messageState = ""; vm.errorMessage = response.data.userMessage; }) }, } vm.functions.getLanguages(); vm.functions.getLevels(); vm.functions.getAllUsers(); vm.functions.getProfileImages(); vm.functions.getUserInSession(); }])
use super::Request; use crate::common::{OrderEvent, OrderType, SendOrderStatus, Side, Symbol, TriggerSignal}; use chrono::{DateTime, Utc}; use http::Method; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct SendOrderRequest { pub order_type: OrderType, pub symbol: Symbol, pub side: Side, pub size: u64, pub limit_price: f64, pub stop_price: Option<f64>, pub trigger_signal: Option<TriggerSignal>, pub cli_ord_id: Option<Uuid>, pub reduce_only: Option<bool>, } impl SendOrderRequest { pub fn limit(symbol: Symbol, price: f64, qty: i64) -> Self { let side = if qty > 0 { Side::Buy } else { Side::Sell }; Self { order_type: OrderType::Lmt, symbol: symbol, side: side, size: qty.abs() as u64, limit_price: price, stop_price: None, trigger_signal: None, cli_ord_id: None, reduce_only: None, } } } #[derive(Deserialize, Debug, Clone)] pub struct SendOrderResponse { #[serde(rename = "sendStatus")] pub send_status: SendStatus, } #[derive(Deserialize, Debug, Clone)] #[serde(untagged)] pub enum SendStatus { Success { order_id: Uuid, status: SendOrderStatus, #[serde(rename = "receivedTime")] received_time: DateTime<Utc>, #[serde(rename = "orderEvents")] order_events: Vec<OrderEvent>, }, Fail { status: SendOrderStatus, }, } impl SendStatus { pub fn order_id(&self) -> Option<Uuid> { match self { SendStatus::Success { order_id, .. } => Some(*order_id), _ => None, } } pub fn status(&self) -> SendOrderStatus { match self { SendStatus::Success { status, .. } => *status, SendStatus::Fail { status } => *status, } } } impl Request for SendOrderRequest { const METHOD: Method = Method::POST; const SIGNED: bool = true; const ENDPOINT: &'static str = "/sendorder"; const HAS_PAYLOAD: bool = true; type Response = SendOrderResponse; }
class Valvat module Checksum class MT < Base check_digit_length 2 def check_digit multipliers = [9, 8, 7, 6, 4, 3] sum = sum_figures_by { |digit, index| digit * multipliers[index] } supposed_checksum = 37 - (sum % 37) supposed_checksum.zero? ? 37 : supposed_checksum end end end end
import * as monaco from 'monaco-editor'; export type Monaco = typeof monaco; export type EmitOutput = monaco.languages.typescript.EmitOutput; export type OutputFile = monaco.languages.typescript.OutputFile; export type ICodeEditor = monaco.editor.IStandaloneCodeEditor; export type TypeScriptWorker = monaco.languages.typescript.TypeScriptWorker; export type MonacoUri = monaco.Uri; export type IThemeData = monaco.editor.IStandaloneThemeData; export const g: { monaco?: Monaco; editor?: ICodeEditor } = {};
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BrightnessChanger : MonoBehaviour { MeshRenderer mr; // Use this for initialization void Awake () { mr = gameObject.GetComponent<MeshRenderer>(); mr.material.SetFloat("_Brightness", (Mathf.Sin(Time.fixedTime)+1)*20); } // Update is called once per frame void Update () { mr.material.SetFloat("_Brightness", (Mathf.Sin(Time.fixedTime) + 1) * 20); } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Reflection; public class Controller { private List<IWeapon> weapons; public Controller() { this.weapons = new List<IWeapon>(); } public void InsertGemToWeapon(string weaponName, IGem gem, int gemIndex) { if (this.weapons.Count != 0) { IWeapon currentWeapon = this.weapons.First(x => x.Name == weaponName); currentWeapon.AddGem(gem, gemIndex); } } public void RemoveGemFromWeapon(string weaponName, int gemIndex) { if (this.weapons.Count != 0) { IWeapon currentWeapon = this.weapons.First(x => x.Name == weaponName); currentWeapon.RemoveGem(gemIndex); } } public void AddWeaponToStash(IWeapon weapon) { this.weapons.Add(weapon); } public void PrintWeapon(string weaponName) { var currentWeapon = this.weapons.First(x => x.Name == weaponName); Console.WriteLine(currentWeapon); } }
import React, { useState } from 'react' import { Link, useParams } from 'react-router-dom' export default function HomePage() { const [resp,setresp] = useState(); const [error,seterror] = useState(); const history = useParams() useEffect(() => { fetch(`/bill/${history.n}`, { // configuration }) .then(response => response.json()) .then(response => { setresp(response) }) .catch(err => err.json()) .catch(err=> seterror(err)) }, [resp,error]) return ( <div className="text-center"> <h1>igisubizo</h1> <h3 className="main-title home-page-title">{props.message}</h3> <footer> <p><Link to="/">kwitangiriro</Link>.</p> </footer> </div> ) }
import { defineClientAppEnhance } from '@vuepress/client' export default defineClientAppEnhance(({ app, router, siteData }) => { // ... })
Put your markdown files (Hexo/Jekyll) in this directory then start Solo, these files will be imported as posts. 把 Markdown 文件(Hexo/Jekyll)放到本目录后启动 Solo,这些 MD 文件将会被自动导入作为文章。
import React from 'react' import { observable, action, computed } from 'mobx' import { Modal, Spin, notification } from 'antd' import { tree as getTree, add, edit, del, detail, IAdd } from '../../../api/account/admin/privilege' import { Curd, Form, Tree, EditForm, ItemMapPlus as itemMapPlus } from 'fullbase-components' import IStore, { IAddFormConf, IFormStatus, IDetailShowConf, } from 'fullbase-components/dist/store/_i' import Http from '../../../api/http' import Config from '../../../config' import { ICURD } from 'fullbase-components/dist/store/curd' import { IForm } from 'fullbase-components/dist/store/form' import { getMap } from "../../../api/system/dict"; const { codeSuccess, apiFormat: { code, msg } } = Config const { dfDataArr, dfDataObj } = Http interface ICurd extends ICURD<any> { } @Curd @Form class Privilege implements IStore { self: Privilege & ICurd & IForm constructor() { this.self = this as unknown as Privilege & ICurd & IForm } dataFn = { tree: getTree, add, edit, del, detail } dict: { [key: string]: any } = { tree: [] } @action getDict = async () => { const data = await getMap('status,privilegeType') if (data.code === 0) { this.dict = { ...this.dict, ...data.data } } } @observable treeForm = { id: '' } @observable treeLoading = false @observable treeData = { ...dfDataArr } @observable selectPrivilege = { id: '', title: '' } @observable isAddPrivilege = false @observable isEditPrivilege = false treeInitData = () => { this.getDict() } treeRequestAfterFn = ({ data, form }: any) => { if (data[code] === codeSuccess) { this.dict.tree = [{ id: 0, parentId: 0, name: '顶级节点' }].concat(data.data) } return { data, form } } treeSelect = (keys: string[], e: any) => { if (e.selected) { this.selectPrivilege = { id: keys[0] || '', title: e.selectedNodes[0].props.title || '' } } else { this.selectPrivilege = { id: '', title: '' } } } @action addPrivilege = () => { this.self.setForm({ name: 'add', valObj: { parentId: this.selectPrivilege.id || 0 } }) this.isAddPrivilege = true } @action editPrivilege = async () => { if (!this.selectPrivilege.id || parseInt(this.selectPrivilege.id, 10) === 0) { notification.error({ message: '请先选择权限', }) } else { this.self.setForm({ name: 'detail', valObj: { id: this.selectPrivilege.id } }) this.isEditPrivilege = true const detailData = await this.self.getDetail() if (detailData[code] !== codeSuccess) { notification.error({ message: detailData[code], description: detailData[msg] }) this.isEditPrivilege = false } else { this.self.setForm({ name: 'edit', valObj: detailData.data }) } } } @action delPrivilege = async () => { if (!this.selectPrivilege.id || parseInt(this.selectPrivilege.id, 10) === 0) { notification.error({ message: '请先选择权限', }) } else { const self = this.self Modal.confirm({ title: `你确定要删除权限: ${this.selectPrivilege.title} ?`, onOk: () => new Promise(async (resolve, reject) => { const delData = await this.delItem(self.selectPrivilege.id) if (delData[code] !== codeSuccess) { reject() } else { self.getDetail({ formName: 'tree' }) resolve() } }) }) } } // 添加成功 关闭弹窗 addRequestAfterFn = ({ data, form }: any) => { if (data[code] === codeSuccess) { this.isAddPrivilege = false this.addForm = { ...this.dfAddForm } this.self.getDetail({ formName: 'tree' }) } return { data, form } } // 编辑成功 关闭弹窗 editRequestAfterFn = ({ data, form }: any) => { if (data[code] === codeSuccess) { this.isEditPrivilege = false this.self.getDetail({ formName: 'tree' }) } return { data, form } } treeShowConf: IDetailShowConf = { pageTitle: '权限管理', fields: [ { span: 12, field: 'tree', render: (r: any, data: any[]) => data.length < 1 ? '暂无权限,请先添加' : <Tree data={data} onSelect={this.treeSelect} checkable={false} labelKey="name"/> }, { span: 12, field: 'selectTree' }, { span: 24, field: 'model', render: () => <div> <Modal title="添加权限" maskClosable={false} visible={this.isAddPrivilege} okButtonProps={{ loading: this.addStatus.loading, disabled: !this.addStatus.submit }} onOk={() => this.self.add()} onCancel={() => this.isAddPrivilege = false} okText="保存"> <EditForm itemMap={itemMapPlus} Store={this} name="add" data={this.dict}/> </Modal> <Modal title="编辑权限" maskClosable={false} visible={this.isEditPrivilege} okButtonProps={{ loading: this.editStatus.loading, disabled: !this.editStatus.submit }} onOk={() => this.self.edit()} onCancel={() => this.isEditPrivilege = false} okText="保存"> <Spin spinning={this.detailLoading} tip="获取详情……"> <EditForm itemMap={itemMapPlus} Store={this} name="edit" data={this.dict}/> </Spin> </Modal> </div> } ] } @computed get treeBtnConf() { return { isEdit: false, actions: [ { children: '添加', type: 'primary', onClick: this.addPrivilege }, { children: '编辑', type: 'primary', onClick: this.editPrivilege, disabled: !this.selectPrivilege.id }, { children: '删除', type: 'danger', onClick: this.delPrivilege, disabled: !this.selectPrivilege.id }, ] } } dfAddForm: IAdd = { parentId: 0, name: '', icon: '', type: '', api: '', page: '', path: '', desc: '', status: 1, order: 0, } @observable addForm = { ...this.dfAddForm } @observable addErrs = { name: '', icon: '', } @observable addStatus: IFormStatus = { submit: false, loading: false } @observable addData = { ...dfDataObj } addFormConf: IAddFormConf = { props: { layout: 'inline' }, fields: [ { title: '菜单名', type: 'input', field: 'name', span: 24, rules: 'required' }, { title: '父节点', type: 'selectTree', field: 'parentId', span: 24, rules: 'required', data: 'tree', props: { labelKey: 'name', multiple: false } }, { title: 'api地址', type: 'selectRemote', field: 'api', span: 24, props: { url: '/admin/system/api/rows', labelKey: 'desc', apiKey: 'descLike' } }, { title: '图标', type: 'input', field: 'icon', span: 24, }, { title: '页面', type: 'selectRemote', field: 'page', span: 24, props: { url: '/admin/system/page/rows', labelKey: 'desc', apiKey: 'descLike' } }, { title: '前端路径', type: 'input', field: 'path', span: 24 }, { title: '状态', type: 'select', field: 'status', data: 'status', span: 24, props: { isNull: false, allowClear: false } }, { title: '类型', type: 'select', field: 'type', data: 'privilegeType', span: 24, props: { isNull: false, allowClear: false } }, { title: '排序', type: 'inputNumber', field: 'order', span: 24, props: { min: 0 } }, { title: '备注', type: 'input', field: 'desc', span: 24 }, ] } @observable detailForm = { id: '' } @observable detailLoading = false @observable detailData = { ...this.addData, data: { tree: [] } } dfEditForm = { ...this.dfAddForm, id: '' } @observable editForm = { ...this.dfEditForm } @observable editErrs = { ...this.addErrs } @observable editStatus: IFormStatus = { ...this.addStatus } @observable editData = { ...this.addData } editFormConf: IAddFormConf = { ...this.addFormConf, pageTitle: '编辑系统信息' } @action delItem = async (id: number | string) => { return this.dataFn.del({ id }) } } export default Privilege
```python import requests r = requests.get("https://www.ing.nl") cookies = r.cookies.get_dict() with open("cookies.txt","w") as fp: for i, k in enumerate(cookies): fp.write("Cookie name: {} value {}\n".format(k,cookies.get(k))) ```
pluginManagement { repositories { google() jcenter() gradlePluginPortal() mavenCentral() } resolutionStrategy { eachPlugin { if (requested.id.namespace == "com.android") { useModule("com.android.tools.build:gradle:${requested.version}") } } } } rootProject.name = "later" include(":later-core") include(":later-ktx") include(":later-test-expect") project(":later-test-expect").projectDir = File("later-test/later-test-expect")
import path from 'path'; /** * Reverse function of path.join * * @param filePath a path joined via path.join * @param prefix the prefixed path * @returns the file path without the prefix */ export function pathUnjoin(filePath: string, prefix: string): string { if (prefix === '') { return filePath; } const osDependantPrefix = prefix.replace(/\/|\\/g, path.sep); return !osDependantPrefix.endsWith(path.sep) ? filePath.slice(osDependantPrefix.length + path.sep.length) : filePath.slice(osDependantPrefix.length); }
#!/usr/bin/perl # # Copyright (c) 2009-2012 Brown Deer Technology, LLC. All Rights Reserved. # # This software was developed by Brown Deer Technology, LLC. # For more information contact [email protected] # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License version 3 (LGPLv3) # as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # DAR # printf "\n#include <stdcl.h>\n"; for($c=0;$c<10;++$c) { for($a=1;$a<$c;++$a) { $b=$c-$a; printf "\n/* $b=$c-$a */\n"; printf "__kernel void\n"; printf "test_arg_".$a."_".$b."_kern(\n"; for($i=0;$i<$a;++$i) { printf "\t__global double2* a$i,\n" } for($j=0;$j<$b;++$j) { printf "\t__global double2* b$j"; if ($j < $b-1) { printf ","; } printf "\n"; } printf ")\n"; printf "{\n"; printf "\tdouble2 za = __builtin_vector_double2(0.75f,0.33f);\n"; printf "\tuint gtid = get_global_id(0);\n"; for($i=0;$i<$a;++$i) { printf "\tdouble2 tmp$i = a$i\[gtid] + $i.1f + za;\n"; } for($j=0;$j<$b;++$j) { printf "\tb$j\[gtid] = ($j.0f+1.1f)*("; for($i=0;$i<$a;++$i) { for($i=0;$i<$a;++$i) { printf "+"; printf "tmp$i" } } printf ");\n" } printf "}\n"; } }
# iOS-Parallax-Demo This source code is demonstration for post http://codentrick.com/parallax-effect-for-ios-with-swift/. Images used belongs to Samsung Mobile Twitter.
package modern.challenge; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class Main { public static void main(String[] args) { Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp"); String customFilePrefix = "log_"; String customFileSuffix = ".txt"; try { Path tmpFile = Files.createTempFile(customBaseDir, customFilePrefix, customFileSuffix); System.out.println("Created as: " + tmpFile); System.out.println("Sleep for 10 seconds until deletion ..."); File asFile = tmpFile.toFile(); asFile.deleteOnExit(); // simulate some operations with temp file until delete it Thread.sleep(10000); } catch (IOException | InterruptedException e) { // handle exception, don't print it as below System.err.println(e); } System.out.println("Delete file completed ..."); } }
import React from "react" import featured from "../components/featured.css" const Featured = props => ( <div className="featured-container"> <div className="featured-group"> <div className="media-container"> <img src="https://cl.ly/9f5d219dc441/download/Kapture%2525202020-05-26%252520at%2525209.18.24.gif" /> </div> <div className="title-container"> <h2>Apps I have done.</h2> <p>Todo app with search bar and persistent data</p> <a href="https://apps.apple.com/us/app/got-it/id1509864659"> <button> <img src="https://cl.ly/d4e04d580273/download/arrow-down.png" width="18px" /> <p>App Store</p> </button> </a> <span>Download on App Store</span> </div> </div> </div> ) export default Featured
use super::*; use num::complex::Complex; pub enum Side { Left, Right } pub fn dirichlet(_: Side, _: &Vec<Phasor>) -> Phasor { return *phasor::zero(); } pub fn transparent(s: Side, es: &Vec<Phasor>) -> Phasor { // forma mais simples que considera que a frente de onda é transversal ao eixo z. // caso implemente semi vector ou full vector algoritmo é interessante ver os mais casos // do Hadley 1992 pra garantir que passos muito grandes em Z não cause problemas match s { Side::Left => { let x0 = es[0]; let x1 = es[1]; let eta = x0/x1; valid_eta(eta) }, Side::Right => { let mut es_it = es.iter(); let xn = es_it.next_back().unwrap(); let xn_less_one = es_it.next_back().unwrap(); let eta = (xn*1000000.0)/(xn_less_one*1000000.0); valid_eta(eta) } } } fn valid_eta(eta: Complex<f64>) -> Complex<f64> { let tmp = if eta.re < 0.0 || eta.re.is_nan() { Complex::new(0.0, eta.im) } else { eta }; let result = if tmp.im.is_nan() { Complex::new(tmp.re, 0.0) } else { tmp }; result }
#!/usr/bin/env node import meow from 'meow'; import Conf from 'conf'; import add from './commands/add'; import open from './commands/open'; import setConfig from './commands/set'; async function main() { const { input, flags } = meow(` Usage: $ w-project [command] Commands: add Add a workspace to the config open Show options of the projects Example: Add a new workspace: $ w-project add <pathToTheWorkspace> Choose a project to work on: $ w-project open `); const conf = new Conf({ projectName: 'w-project' }); const command = input[0] || ''; switch(command) { case 'add': await add({ conf, workspacePath: input[1], }) break; case '': case 'open': await open({ conf }); break; case 'set': await setConfig({ conf, property: input[1], value: input[2] }); break; default: console.error(`Unsupported command ${command}`); } } main();
const request = require('request-promise'); const { RateLimiter } = require('limiter'); const log = require('./log'); const limiter = new RateLimiter(2, 'second'); function getComment(id) { log(id, 'added'); return new Promise((resolve, reject) => { limiter.removeTokens(1, (err, remainingRequests) => { log(id, 'requesting'); request({ uri: `https://jsonplaceholder.typicode.com/comments/${id}`, json: true }) .then(resolve) .catch(reject); }); }); } module.exports = { getComment };
export enum RGConnectionType { INHERITANCE = 0, COMPOSITION = 1, ACTION = 2, REPLACE = 3, REMOVE = 4, CONDITION = 5 }
// // UIColor+HFFoundation.h // HFFoundation // // Created by HeHongling on 10/9/16. // Copyright © 2016 HeHongling. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UIColor (HFFoundation) + (UIColor *)hf_randomColor; + (nullable UIColor *)hf_colorWithHexString:(NSString *)hexStr; + (nullable UIColor *)hf_colorWithHexString:(NSString *)hexStr alpha:(CGFloat)alpha; + (UIColor *)hf_colorWithRGB:(uint32_t)rgbValue; + (UIColor *)hf_colorWithRGBA:(uint32_t)rgbaValue; + (UIColor *)hf_colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha; @end NS_ASSUME_NONNULL_END
ALTER TABLE seasons ADD `type` integer unsigned AFTER `status`; UPDATE seasons SET type = 0;
/*if not async then phantomjs fails to run the webserver and the test concurrently*/ var less = {async: true, strictMath: true}; /* record log messages for testing */ var logMessages = [], realConsoleLog = console.log; console.log = function (msg) { logMessages.push(msg); realConsoleLog.call(console, msg); }; var testLessEqualsInDocument = function () { testLessInDocument(testSheet); }; var testLessErrorsInDocument = function () { testLessInDocument(testErrorSheet); }; var testLessInDocument = function (testFunc) { var links = document.getElementsByTagName('link'), typePattern = /^text\/(x-)?less$/; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) && (links[i].type.match(typePattern)))) { testFunc(links[i]); } } }; var testSheet = function (sheet) { it(sheet.id + " should match the expected output", function () { var lessOutputId = sheet.id.replace("original-", ""), expectedOutputId = "expected-" + lessOutputId, lessOutput = document.getElementById(lessOutputId).innerText, expectedOutputHref = document.getElementById(expectedOutputId).href, expectedOutput = loadFile(expectedOutputHref); waitsFor(function () { return expectedOutput.loaded; }, "failed to load expected outout", 10000); runs(function () { // use sheet to do testing expect(lessOutput).toEqual(expectedOutput.text); }); }); }; var testErrorSheet = function (sheet) { it(sheet.id + " should match an error", function () { var lessHref = sheet.href, id = sheet.id.replace(/^original-less:/, "less-error-message:"), errorHref = lessHref.replace(/.less$/, ".txt"), errorFile = loadFile(errorHref), actualErrorElement = document.getElementById(id), actualErrorMsg; describe("the error", function () { expect(actualErrorElement).not.toBe(null); }); actualErrorMsg = actualErrorElement.innerText .replace(/\n\d+/g, function (lineNo) { return lineNo + " "; }) .replace(/\n\s*in /g, " in ") .replace("\n\n", "\n"); waitsFor(function () { return errorFile.loaded; }, "failed to load expected outout", 10000); runs(function () { var errorTxt = errorFile.text .replace("{path}", "") .replace("{pathrel}", "") .replace("{pathhref}", "http://localhost:8081/less/errors/") .replace("{404status}", " (404)"); expect(actualErrorMsg).toEqual(errorTxt); if (errorTxt == actualErrorMsg) { actualErrorElement.style.display = "none"; } }); }); }; var loadFile = function (href) { var request = new XMLHttpRequest(), response = {loaded: false, text: ""}; request.open('GET', href, true); request.onload = function (e) { response.text = request.response.replace(/\r/g, ""); response.loaded = true; } request.send(); return response; }; (function () { var jasmineEnv = jasmine.getEnv(); jasmineEnv.updateInterval = 1000; var htmlReporter = new jasmine.HtmlReporter(); jasmineEnv.addReporter(htmlReporter); jasmineEnv.specFilter = function (spec) { return htmlReporter.specFilter(spec); }; var currentWindowOnload = window.onload; window.onload = function () { if (currentWindowOnload) { currentWindowOnload(); } execJasmine(); }; function execJasmine() { setTimeout(function () { jasmineEnv.execute(); }, 3000); } })();
using FluentValidation; namespace Core.Application.Models { public class BudgetJarDto : EntityDto<Guid> { public Guid UserId { get; set; } public string Name { get; set; } = string.Empty; public float Percentage { get; set; } public Guid IconId { get; set; } public Decimal TotalBalance { get; set; } public IconDto Icon { get; set; } = new IconDto(); public bool IsDefault { get; set; } public bool Archived { get; set; } public static BudgetJarDto Clone(BudgetJarDto budgetJar) { return new BudgetJarDto() { Id = budgetJar.Id, UserId = budgetJar.UserId, Name = budgetJar.Name, Percentage = budgetJar.Percentage, TotalBalance = budgetJar.TotalBalance, IconId = budgetJar.IconId, Icon = budgetJar.Icon, IsDefault = budgetJar.IsDefault, }; } } public class BudgetJarValidator : BasicValidator<BudgetJarDto> { public BudgetJarValidator() { RuleFor(x => x.Name).NotEmpty(); RuleFor(x => x.Percentage).NotEmpty(); } } }
import os def pathsplit(p, rest=[]): (h, t) = os.path.split(p) if len(h) < 1: return [t]+rest if len(t) < 1: return [h]+rest return pathsplit(h, [t]+rest) def commonpath(l1, l2, common=[]): if len(l1) < 1: return (common, l1, l2) if len(l2) < 1: return (common, l1, l2) if l1[0] != l2[0]: return (common, l1, l2) return commonpath(l1[1:], l2[1:], common+[l1[0]]) def relpath(p1, p2): (common, l1, l2) = commonpath(pathsplit(p1), pathsplit(p2)) p = [] if len(l1) > 0: p = ["../" * len(l1)] p = p + l2 return os.path.join(*p)
package games.game2048 import board.Cell import board.SquareBoard import org.junit.Assert import org.junit.Test class TestMoveValuesInRowOrColumn : AbstractTestGameWithSmallNumbers() { private val defaultInput = """-2-4 2--- ---- 4---""" @Test fun testRow() = testMoveInRowOrColumn({ it.getRow(1, 1..4) }, "Row(1, 1..4)", "24-- 2--- ---- 4---") @Test fun testRowReversed() = testMoveInRowOrColumn({ it.getRow(1, 4 downTo 1) }, "Row(1, 4 downTo 1)", "--24 2--- ---- 4---") @Test fun testColumn() = testMoveInRowOrColumn({ it.getColumn(1..4, 1) }, "Column(1..4, 1)", "22-4 4--- ---- ----") @Test fun testColumnReversed() = testMoveInRowOrColumn({ it.getColumn(4 downTo 1, 1) }, "Column(4 downTo 1, 1)", "-2-4 ---- 2--- 4---") @Test fun testNoMove() = testMoveInRowOrColumn({ it.getRow(1, 1..4) }, "Row(1, 1..4)", "2424 ---- ---- ----", "2424 ---- ---- ----", expectedMove = false) private fun testMoveInRowOrColumn( getRowOrColumn: (SquareBoard) -> List<Cell>, rowOrColumnName: String, expected: String, input: String = defaultInput, expectedMove: Boolean = true ) { val inputBoard = TestBoard(input) val board = createBoard(inputBoard) val rowOrColumn = getRowOrColumn(board) val actualMove = board.moveValuesInRowOrColumn(rowOrColumn) Assert.assertEquals("Incorrect move in $rowOrColumnName.\nInput:\n$inputBoard\n", TestBoard(expected), board.toTestBoard()) Assert.assertEquals("The 'moveValuesInRowOrColumn' method returns incorrect result for input:\n$inputBoard", expectedMove, actualMove) } }
package nz.co.chrisdrake.tv import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import nz.co.chrisdrake.tv.data.DataModule import javax.inject.Singleton @Component(modules = arrayOf( ApplicationModule::class, ActivityBindingModule::class, AndroidInjectionModule::class, DataModule::class )) @Singleton interface ApplicationComponent : AndroidInjector<TvApplication>
import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:tmdb/models/watchlist_model.dart'; class WatchListState extends Equatable { const WatchListState(); @override List<Object> get props => []; } class WatchListLoading extends WatchListState {} class WatchListLoaded extends WatchListState { final WatchListModel watchList; const WatchListLoaded({@required this.watchList}); @override List<Object> get props => [watchList]; } class WatchListEmpty extends WatchListState {} class WatchListLoadingError extends WatchListState { final dynamic error; const WatchListLoadingError({@required this.error}); @override List<Object> get props => [error]; }
package org.ossiaustria.amigo.platform.rest import org.ossiaustria.amigo.platform.domain.models.Account import org.ossiaustria.amigo.platform.domain.services.PersonProfileService import org.ossiaustria.amigo.platform.domain.services.auth.AuthService import org.ossiaustria.amigo.platform.domain.services.auth.TokenUserDetails import org.ossiaustria.amigo.platform.exceptions.UserNotFoundException import org.springframework.security.core.Authentication import org.springframework.security.core.context.SecurityContextHolder import org.springframework.stereotype.Component interface CurrentUserService { fun authentication(): Authentication fun authenticationOrNull(): Authentication? // fun person(): Person fun account(): Account } @Component class SimpleCurrentUserService( val authService: AuthService, val personService: PersonProfileService ) : CurrentUserService { override fun authentication(): Authentication { return SecurityContextHolder.getContext().authentication } override fun authenticationOrNull(): Authentication? { return SecurityContextHolder.getContext().authentication } // override fun person(): Person { // val tokenUserDetails: TokenUserDetails = authentication().principal as TokenUserDetails // return personService.findById(tokenUserDetails.personsIds.first()) // ?: throw UserNotFoundException() // } override fun account(): Account { val tokenUserDetails: TokenUserDetails = authentication().principal as TokenUserDetails return authService.findById(tokenUserDetails.accountId) ?: throw UserNotFoundException() } }
from gym.envs.registration import register import gym import os import sys dirpath = os.path.dirname(os.path.dirname(__file__)) sys.path.append(dirpath) env_specs = gym.envs.registry.env_specs if 'HumanoidSafe-v2' not in env_specs: register( id='HumanoidSafe-v2', entry_point='mujoco_safety_gym.envs:HumanoidEnv', max_episode_steps=1000, ) if 'AntSafe-v2' not in env_specs: register( id='AntSafe-v2', entry_point='mujoco_safety_gym.envs:AntEnv', max_episode_steps=1000, ) if 'AntSafeVisualize-v2' not in env_specs: register( id='AntSafeVisualize-v2', entry_point='mujoco_safety_gym.envs:AntEnvVisualize', max_episode_steps=1000, ) if 'HopperSafe-v2' not in env_specs: register( id='HopperSafe-v2', entry_point='mujoco_safety_gym.envs:HopperEnv', max_episode_steps=1000, ) if 'HalfCheetahSafe-v2' not in env_specs: register( id='HalfCheetahSafe-v2', entry_point='mujoco_safety_gym.envs:HalfCheetahEnv', max_episode_steps=1000, ) if 'FetchPushSafety-v0' not in env_specs: register( id='FetchPushSafety-v0', entry_point='mujoco_safety_gym.envs:FetchPushEnv', max_episode_steps=1000, ) if 'FetchReachSafety-v0' not in env_specs: register( id='FetchReachSafety-v0', entry_point='mujoco_safety_gym.envs:FetchReachEnv', max_episode_steps=1000, ) if 'FetchSlideSafety-v0' not in env_specs: register( id='FetchSlideSafety-v0', entry_point='mujoco_safety_gym.envs:FetchSlideEnv', max_episode_steps=1000, )
using Eaf.Authorization; using Eaf.Logging; using Eaf.Runtime.Validation; using Eaf.UI; using Shouldly; using Xunit; namespace Eaf.Tests.Logging { public class LogSeverity_Tests : TestBaseWithLocalIocManager { [Fact] public void AuthorizationException_Default_Log_Severity_Change_Test() { // change log severity ... EafAuthorizationException.DefaultLogSeverity = LogSeverity.Error; var exception = new EafAuthorizationException("Test exception !"); exception.Severity.ShouldBe(LogSeverity.Error); } [Fact] public void AuthorizationException_Default_Log_Severity_Test() { // change log severity ... EafAuthorizationException.DefaultLogSeverity = LogSeverity.Warn; var exception = new EafAuthorizationException("Test exception !"); exception.Severity.ShouldBe(LogSeverity.Warn); } [Fact] public void UserFriendlyException_Default_Log_Severity_Change_Test() { // change log severity ... UserFriendlyException.DefaultLogSeverity = LogSeverity.Error; var exception = new UserFriendlyException("Test exception !"); exception.Severity.ShouldBe(LogSeverity.Error); } [Fact] public void UserFriendlyException_Default_Log_Severity_Test() { // change log severity ... UserFriendlyException.DefaultLogSeverity = LogSeverity.Warn; var exception = new UserFriendlyException("Test exception !"); exception.Severity.ShouldBe(LogSeverity.Warn); } [Fact] public void ValidationException_Default_Log_Severity_Change_Test() { // change log severity ... EafValidationException.DefaultLogSeverity = LogSeverity.Error; var exception = new EafValidationException("Test exception !"); exception.Severity.ShouldBe(LogSeverity.Error); } [Fact] public void ValidationException_Default_Log_Severity_Test() { // change log severity ... EafValidationException.DefaultLogSeverity = LogSeverity.Warn; var exception = new EafValidationException("Test exception !"); exception.Severity.ShouldBe(LogSeverity.Warn); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. import * as http from "http"; import * as os from "os"; import * as path from "path"; import { resolve as pathResolve } from "path"; import { ParsedUrlQuery } from "querystring"; import * as url from "url"; import * as util from "util"; import * as _ from "lodash"; import * as models from "../models"; import { requestResponseDefinition } from "../models/requestResponse"; import { LowerHttpMethods, SwaggerSpec } from "../swagger/swaggerTypes"; import { SchemaValidateFunction, SchemaValidateIssue, SchemaValidator, } from "../swaggerValidator/schemaValidator"; import * as C from "../util/constants"; import { log } from "../util/logging"; import * as utils from "../util/utils"; import { RuntimeException } from "../util/validationError"; import { inversifyGetContainer, inversifyGetInstance, TYPES } from "../inversifyUtils"; import { setDefaultOpts } from "../swagger/loader"; import { apiValidationErrors, ApiValidationErrorCode } from "../util/errorDefinitions"; import { LiveValidatorLoader, LiveValidatorLoaderOption } from "./liveValidatorLoader"; import { getProviderFromPathTemplate, OperationSearcher } from "./operationSearcher"; import { LiveRequest, LiveResponse, OperationContext, validateSwaggerLiveRequest, validateSwaggerLiveResponse, ValidationRequest, } from "./operationValidator"; const glob = require("glob"); export interface LiveValidatorOptions extends LiveValidatorLoaderOption { swaggerPaths: string[]; git: { shouldClone: boolean; url?: string; branch?: string; }; useRelativeSourceLocationUrl?: boolean; directory: string; swaggerPathsPattern: string[]; excludedSwaggerPathsPattern: string[]; isPathCaseSensitive: boolean; loadValidatorInBackground: boolean; loadValidatorInInitialize: boolean; } export interface RequestResponsePair { readonly liveRequest: LiveRequest; readonly liveResponse: LiveResponse; } export interface LiveValidationResult { readonly isSuccessful?: boolean; readonly operationInfo: OperationContext; readonly errors: LiveValidationIssue[]; readonly runtimeException?: RuntimeException; } export interface RequestResponseLiveValidationResult { readonly requestValidationResult: LiveValidationResult; readonly responseValidationResult: LiveValidationResult; readonly runtimeException?: RuntimeException; } export type LiveValidationIssue = { code: ApiValidationErrorCode; pathsInPayload: string[]; documentationUrl?: string; } & Omit<SchemaValidateIssue, "code">; /** * Additional data to log. */ interface Meta { [key: string]: any; } /** * Options for a validation operation. * If `includeErrors` is missing or empty, all error codes will be included. */ export interface ValidateOptions { readonly includeErrors?: ApiValidationErrorCode[]; readonly includeOperationMatch?: boolean; } export enum LiveValidatorLoggingLevels { error = "error", warn = "warn", info = "info", verbose = "verbose", debug = "debug", silly = "silly", } export enum LiveValidatorLoggingTypes { trace = "trace", perfTrace = "perfTrace", error = "error", incomingRequest = "incomingRequest", } /** * @class * Live Validator for Azure swagger APIs. */ export class LiveValidator { public options: LiveValidatorOptions; public operationSearcher: OperationSearcher; private logFunction?: (message: string, level: string, meta?: Meta) => void; private loader?: LiveValidatorLoader; private loadInBackgroundComplete: boolean = false; private validateRequestResponsePair?: SchemaValidateFunction; /** * Constructs LiveValidator based on provided options. * * @param {object} ops The configuration options. * @param {callback function} logCallback The callback logger. * * @returns CacheBuilder Returns the configured CacheBuilder object. */ public constructor( options?: Partial<LiveValidatorOptions>, logCallback?: (message: string, level: string, meta?: Meta) => void ) { const ops: Partial<LiveValidatorOptions> = options || {}; this.logFunction = logCallback; setDefaultOpts(ops, { swaggerPaths: [], excludedSwaggerPathsPattern: C.DefaultConfig.ExcludedSwaggerPathsPattern, directory: path.resolve(os.homedir(), "repo"), isPathCaseSensitive: false, loadValidatorInBackground: true, loadValidatorInInitialize: false, isArmCall: false, }); if (!ops.git) { ops.git = { url: "https://github.com/Azure/azure-rest-api-specs.git", shouldClone: false, }; } if (!ops.git.url) { ops.git.url = "https://github.com/Azure/azure-rest-api-specs.git"; } if (!ops.git.shouldClone) { ops.git.shouldClone = false; } this.options = ops as LiveValidatorOptions; this.logging(`Creating livevalidator with options:${JSON.stringify(this.options)}`); this.operationSearcher = new OperationSearcher(this.logging); } /** * Initializes the Live Validator. */ public async initialize(): Promise<void> { const startTime = Date.now(); // Clone github repository if required if (this.options.git.shouldClone && this.options.git.url) { const cloneStartTime = Date.now(); utils.gitClone(this.options.directory, this.options.git.url, this.options.git.branch); this.logging( `Clone spec repository ${this.options.git.url}, branch:${this.options.git.branch} in livevalidator.initialize` ); this.logging( `Clone spec repository ${this.options.git.url}, branch:${this.options.git.branch}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.initialize.gitclone", Date.now() - cloneStartTime ); } // Construct array of swagger paths to be used for building a cache this.logging("Get swagger path."); const swaggerPaths = await this.getSwaggerPaths(); const container = inversifyGetContainer(); this.loader = inversifyGetInstance(LiveValidatorLoader, { container, fileRoot: this.options.directory, ...this.options, loadSuppression: this.options.loadSuppression ?? Object.keys(apiValidationErrors), }); this.loader.logging = this.logging; // re-set the transform context after set the logging function this.loader.setTransformContext(); const schemaValidator = container.get(TYPES.schemaValidator) as SchemaValidator; this.validateRequestResponsePair = await schemaValidator.compileAsync( requestResponseDefinition ); const allSpecs: SwaggerSpec[] = []; while (swaggerPaths.length > 0) { const swaggerPath = swaggerPaths.shift()!; const spec = await this.getSwaggerInitializer(this.loader!, swaggerPath); if (spec !== undefined) { allSpecs.push(spec); } } this.logging("Apply global transforms for all specs"); try { this.loader.transformLoadedSpecs(); } catch (e) { const errMsg = `Failed to transform loaded specs, detail error message:${e?.message}.ErrorStack:${e?.stack}`; this.logging( errMsg, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.initialize.transformLoadedSpecs" ); throw new Error(errMsg); } if (this.options.loadValidatorInInitialize) { while (allSpecs.length > 0) { try { const spec = allSpecs.shift()!; const loadStart = Date.now(); this.logging( `Start building validator for ${spec._filePath}`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loader.buildAjvValidator" ); await this.loader.buildAjvValidator(spec); const durationInMs = Date.now() - loadStart; this.logging( `Complete building validator for ${spec._filePath} with DurationInMs:${durationInMs}`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loader.buildAjvValidator" ); this.logging( `Complete building validator for ${spec._filePath} in initialization time`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.initialize.loader.buildAjvValidator", durationInMs ); } catch (e) { this.logging( `ErrorMessage:${e?.message}.ErrorStack:${e?.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.initialize.loadValidatorInInitialize" ); } } this.loader = undefined; } this.logging("Cache initialization complete."); const elapsedTime = Date.now() - startTime; this.logging( `Cache complete initialization with DurationInMs:${elapsedTime}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.initialize" ); this.logging( `Cache complete initialization`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.initialize", elapsedTime ); if (this.options.loadValidatorInBackground) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.loadAllSpecValidatorInBackground(allSpecs); } } public isLoadInBackgroundCompleted() { return this.loadInBackgroundComplete; } private async loadAllSpecValidatorInBackground(allSpecs: SwaggerSpec[]) { const backgroundStartTime = Date.now(); utils.shuffleArray(allSpecs); while (allSpecs.length > 0) { try { const spec = allSpecs.shift()!; const startTime = Date.now(); this.logging( `Start building validator for ${spec._filePath} in background`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); await this.loader!.buildAjvValidator(spec, { inBackground: true }); const elapsedTime = Date.now() - startTime; this.logging( `Complete building validator for ${spec._filePath} in background with DurationInMs:${elapsedTime}.`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); this.logging( `Complete building for ${spec._filePath} in background`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.loadAllSpecValidatorInBackground-1", elapsedTime ); } catch (e) { this.logging( `ErrorMessage:${e?.message}.ErrorStack:${e?.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); } } this.loader = undefined; this.loadInBackgroundComplete = true; const elapsedTimeForBuild = Date.now() - backgroundStartTime; this.logging( `Build validator for all specs finished in background with DurationInMs:${elapsedTimeForBuild}.`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); this.logging( `Build validator for all specs finished in background`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.loadAllSpecValidatorInBackground", elapsedTimeForBuild ); } /** * Validates live request. */ public async validateLiveRequest( liveRequest: LiveRequest, options: ValidateOptions = {}, operationInfo?: OperationContext ): Promise<LiveValidationResult> { const startTime = Date.now(); const correlationId = liveRequest.headers?.["x-ms-correlation-request-id"] || ""; const { info, error } = this.getOperationInfo(liveRequest, correlationId, operationInfo); if (error !== undefined) { this.logging( `ErrorMessage:${error.message}.ErrorStack:${error.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveRequest", undefined, info.validationRequest ); return { isSuccessful: undefined, errors: [], runtimeException: error, operationInfo: info, }; } if (!liveRequest.query) { liveRequest.query = url.parse(liveRequest.url, true).query; } let errors: LiveValidationIssue[] = []; let runtimeException; try { errors = await validateSwaggerLiveRequest( liveRequest, info, this.loader, options.includeErrors, this.logging ); } catch (reqValidationError) { const msg = `An error occurred while validating the live request for operation ` + `"${info.operationId}". The error is:\n ` + `${util.inspect(reqValidationError, { depth: null })}`; runtimeException = { code: C.ErrorCodes.RequestValidationError.name, message: msg }; this.logging( msg, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveRequest", undefined, info.validationRequest ); } const elapsedTime = Date.now() - startTime; this.logging( `Complete request validation`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.validateLiveRequest", elapsedTime, info.validationRequest ); if (!options.includeOperationMatch) { delete info.operationMatch; delete info.validationRequest; } return { isSuccessful: runtimeException ? undefined : errors.length === 0, operationInfo: info, errors, runtimeException, }; } /** * Validates live response. */ public async validateLiveResponse( liveResponse: LiveResponse, specOperation: { url: string; method: string }, options: ValidateOptions = {}, operationInfo?: OperationContext ): Promise<LiveValidationResult> { const startTime = Date.now(); const correlationId = liveResponse.headers?.["x-ms-correlation-request-id"] || ""; const { info, error } = this.getOperationInfo(specOperation, correlationId, operationInfo); if (error !== undefined) { this.logging( `ErrorMessage:${error.message}.ErrorStack:${error.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveResponse", undefined, info.validationRequest ); return { isSuccessful: undefined, errors: [], runtimeException: error, operationInfo: { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId }, }; } let errors: LiveValidationIssue[] = []; let runtimeException; this.transformResponseStatusCode(liveResponse); try { errors = await validateSwaggerLiveResponse( liveResponse, info, this.loader, options.includeErrors, this.options.isArmCall, this.logging ); } catch (resValidationError) { const msg = `An error occurred while validating the live response for operation ` + `"${info.operationId}". The error is:\n ` + `${util.inspect(resValidationError, { depth: null })}`; runtimeException = { code: C.ErrorCodes.RequestValidationError.name, message: msg }; this.logging( msg, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveResponse", undefined, info.validationRequest ); } const elapsedTime = Date.now() - startTime; this.logging( `Complete response validation`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.validateLiveResponse", elapsedTime, info.validationRequest ); if (!options.includeOperationMatch) { delete info.operationMatch; delete info.validationRequest; } return { isSuccessful: runtimeException ? undefined : errors.length === 0, operationInfo: info, errors, runtimeException, }; } /** * Validates live request and response. */ public async validateLiveRequestResponse( requestResponseObj: RequestResponsePair, options?: ValidateOptions ): Promise<RequestResponseLiveValidationResult> { const validationResult = { requestValidationResult: { errors: [], operationInfo: { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId }, }, responseValidationResult: { errors: [], operationInfo: { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId }, }, }; if (!requestResponseObj) { const message = 'requestResponseObj cannot be null or undefined and must be of type "object".'; return { ...validationResult, runtimeException: { code: C.ErrorCodes.IncorrectInput.name, message, }, }; } const errors = this.validateRequestResponsePair!({}, requestResponseObj); if (errors.length > 0) { const error = errors[0]; const message = `Found errors "${error.message}" in the provided input in path ${error.jsonPathsInPayload[0]}:\n` + `${util.inspect(requestResponseObj, { depth: null })}.`; return { ...validationResult, runtimeException: { code: C.ErrorCodes.IncorrectInput.name, message, }, }; } const request = requestResponseObj.liveRequest; const response = requestResponseObj.liveResponse; this.transformResponseStatusCode(response); const requestValidationResult = await this.validateLiveRequest(request, { ...options, includeOperationMatch: true, }); const info = requestValidationResult.operationInfo; const responseValidationResult = requestValidationResult.isSuccessful === undefined && requestValidationResult.runtimeException === undefined ? requestValidationResult : await this.validateLiveResponse( response, request, { ...options, includeOperationMatch: false, }, info ); delete info.validationRequest; delete info.operationMatch; return { requestValidationResult, responseValidationResult, }; } private transformResponseStatusCode(liveResponse: LiveResponse) { // If status code is passed as a status code string (e.g. "OK") transform it to the status code // number (e.g. '200'). if ( !http.STATUS_CODES[liveResponse.statusCode] && utils.statusCodeStringToStatusCode[liveResponse.statusCode.toLowerCase()] ) { liveResponse.statusCode = utils.statusCodeStringToStatusCode[liveResponse.statusCode.toLowerCase()]; } } private getOperationInfo( request: { url: string; method: string }, correlationId: string, operationInfo?: OperationContext ): { info: OperationContext; error?: any; } { const info = operationInfo ?? { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId, }; try { if (info.validationRequest === undefined) { info.validationRequest = this.parseValidationRequest( request.url, request.method, correlationId ); } if (info.operationMatch === undefined) { const result = this.operationSearcher.search(info.validationRequest); info.apiVersion = result.apiVersion; info.operationMatch = result.operationMatch; } info.operationId = info.operationMatch.operation.operationId!; return { info }; } catch (error) { return { info, error }; } } public parseValidationRequest( requestUrl: string, requestMethod: string | undefined | null, correlationId: string ): ValidationRequest { return parseValidationRequest(requestUrl, requestMethod, correlationId); } private async getMatchedPaths(jsonsPattern: string | string[]): Promise<string[]> { const startTime = Date.now(); let matchedPaths: string[] = []; if (typeof jsonsPattern === "string") { matchedPaths = glob.sync(jsonsPattern, { ignore: this.options.excludedSwaggerPathsPattern, nodir: true, }); } else { for (const pattern of jsonsPattern) { const res: string[] = glob.sync(pattern, { ignore: this.options.excludedSwaggerPathsPattern, nodir: true, }); matchedPaths = matchedPaths.concat(res); } } this.logging( `Using swaggers found from directory: "${ this.options.directory }" and pattern: "${jsonsPattern.toString()}". Total paths count: ${matchedPaths.length}`, LiveValidatorLoggingLevels.info ); this.logging( `Using swaggers found from directory: "${ this.options.directory }" and pattern: "${jsonsPattern.toString()}". Total paths count: ${matchedPaths.length}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.livevalidator.getMatchedPaths", Date.now() - startTime ); return matchedPaths; } private async getSwaggerPaths(): Promise<string[]> { if (this.options.swaggerPaths.length !== 0) { this.logging( `Using user provided swagger paths by options.swaggerPaths. Total paths count: ${this.options.swaggerPaths.length}` ); return this.options.swaggerPaths; } else { const allJsonsPattern = path.join(this.options.directory, "/specification/**/*.json"); const swaggerPathPatterns: string[] = []; if ( this.options.swaggerPathsPattern === undefined || this.options.swaggerPathsPattern.length === 0 ) { return this.getMatchedPaths(allJsonsPattern); } else { this.options.swaggerPathsPattern.map((item) => { swaggerPathPatterns.push(path.join(this.options.directory, item)); }); return this.getMatchedPaths(swaggerPathPatterns); } } } private async getSwaggerInitializer( loader: LiveValidatorLoader, swaggerPath: string ): Promise<SwaggerSpec | undefined> { const startTime = Date.now(); this.logging(`Building cache from:${swaggerPath}`, LiveValidatorLoggingLevels.debug); try { const spec = await loader.load(pathResolve(swaggerPath)); const elapsedTimeLoadSpec = Date.now() - startTime; this.logging( `Load spec ${swaggerPath}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.getSwaggerInitializer.loader.load", elapsedTimeLoadSpec ); const startTimeAddSpecToCache = Date.now(); this.operationSearcher.addSpecToCache(spec); this.logging( `Add spec to cache ${swaggerPath}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.getSwaggerInitializer.operationSearcher.addSpecToCache", Date.now() - startTimeAddSpecToCache ); const elapsedTime = Date.now() - startTime; this.logging( `Complete loading with DurationInMs:${elapsedTime}`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.getSwaggerInitializer" ); return spec; } catch (err) { this.logging( `Unable to initialize "${swaggerPath}" file from SpecValidator. We are ` + `ignoring this swagger file and continuing to build cache for other valid specs. ErrorMessage: ${err?.message};ErrorStack: ${err?.stack}`, LiveValidatorLoggingLevels.warn, LiveValidatorLoggingTypes.error ); return undefined; } } private logging = ( message: string, level?: LiveValidatorLoggingLevels, loggingType?: LiveValidatorLoggingTypes, operationName?: string, durationInMilliseconds?: number, validationRequest?: ValidationRequest ) => { level = level || LiveValidatorLoggingLevels.info; loggingType = loggingType || LiveValidatorLoggingTypes.trace; operationName = operationName || ""; durationInMilliseconds = durationInMilliseconds || 0; if (this.logFunction !== undefined) { if (validationRequest !== undefined && validationRequest !== null) { this.logFunction(message, level, { CorrelationId: validationRequest.correlationId, ProviderNamespace: validationRequest.providerNamespace, ResourceType: validationRequest.resourceType, ApiVersion: validationRequest.apiVersion, OperationName: operationName, LoggingType: loggingType, DurationInMilliseconds: durationInMilliseconds, }); } else { this.logFunction(message, level, { OperationName: operationName, LoggingType: loggingType, DurationInMilliseconds: durationInMilliseconds, }); } } else { log.log(level, message); } }; } /** * OAV expects the url that is sent to match exactly with the swagger path. For this we need to keep only the part after * where the swagger path starts. Currently those are '/subscriptions' and '/providers'. */ export function formatUrlToExpectedFormat(requestUrl: string): string { return requestUrl.substring(requestUrl.search("/?(subscriptions|providers)/i")); } /** * Parse the validation request information. * * @param requestUrl The url of service api call. * * @param requestMethod The http verb for the method to be used for lookup. * * @param correlationId The id to correlate the api calls. * * @returns parsed ValidationRequest info. */ export const parseValidationRequest = ( requestUrl: string, requestMethod: string | undefined | null, correlationId: string ): ValidationRequest => { if ( requestUrl === undefined || requestUrl === null || typeof requestUrl.valueOf() !== "string" || !requestUrl.trim().length ) { const msg = "An error occurred while trying to parse validation payload." + 'requestUrl is a required parameter of type "string" and it cannot be an empty string.'; const e = new models.LiveValidationError(C.ErrorCodes.PotentialOperationSearchError.name, msg); throw e; } if ( requestMethod === undefined || requestMethod === null || typeof requestMethod.valueOf() !== "string" || !requestMethod.trim().length ) { const msg = "An error occurred while trying to parse validation payload." + 'requestMethod is a required parameter of type "string" and it cannot be an empty string.'; const e = new models.LiveValidationError(C.ErrorCodes.PotentialOperationSearchError.name, msg); throw e; } let queryStr; let apiVersion = ""; let resourceType = ""; let providerNamespace = ""; const parsedUrl = url.parse(requestUrl, true); const pathStr = parsedUrl.pathname || ""; if (pathStr !== "") { // Lower all the keys and values of query parameters before searching for `api-version` const queryObject = _.transform( parsedUrl.query, (obj: ParsedUrlQuery, value, key) => (obj[key.toLowerCase()] = _.isString(value) ? value.toLowerCase() : value) ); apiVersion = (queryObject["api-version"] || C.unknownApiVersion) as string; providerNamespace = getProviderFromPathTemplate(pathStr) || C.unknownResourceProvider; resourceType = utils.getResourceType(pathStr, providerNamespace); // Provider would be provider found from the path or Microsoft.Unknown providerNamespace = providerNamespace || C.unknownResourceProvider; if (providerNamespace === C.unknownResourceProvider) { apiVersion = C.unknownApiVersion; } providerNamespace = providerNamespace.toLowerCase(); apiVersion = apiVersion.toLowerCase(); queryStr = queryObject; requestMethod = requestMethod.toLowerCase(); } return { providerNamespace, resourceType, apiVersion, requestMethod: requestMethod as LowerHttpMethods, host: parsedUrl.host!, pathStr, query: queryStr, correlationId, requestUrl, }; };
#!/bin/bash # Loosely based on the Linux From Scratch build process # Setup set -e umask 022 jobs=-j8 export LC_ALL=POSIX export SRC=$ROOT/src export DEPS=$SRC/deps export PATCHDIR=$SRC/patches for script in $SRC/steps/prerequisites/* do mkdir $ROOT/work cd $ROOT/work echo Running $script . $script cd $ROOT rm -rf $ROOT/work hash -r done
import React from "react" import styled from "styled-components" const Footer = ({ children }) => ( <FooterGroup> <Title> There are many paths to mastery, and if you are persistent you will certainly find one that suits you. @angelVU </Title> <Button href="https://twitter.com/intent/tweet?screen_name=TwitterDev&ref_src=twsrc%5Etfw" class="twitter-mention-button" data-show-count="false" > Tweet to @angelVZUR </Button> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8" ></script> {/* <StyledLink href="https://twitter.com/intent/tweet?screen_name=TwitterDev&ref_src=twsrc%5Etfw" class="twitter-mention-button" data-show-count="false" > Tweet to @angelVZUR </StyledLink> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8" ></script> */} <LinkGroup>{/* <Text></Text> <Text> Hello There</Text> */}</LinkGroup> <CopyRight>{children}</CopyRight> </FooterGroup> ) export default Footer const CopyRight = styled.div` max-width: 500px; margin: 0 auto; padding: 0 20px; ` const FooterGroup = styled.div` margin: 0 auto; padding: 50px 0; background: white; display: grid; grid-gap: 20px; ` const Title = styled.p` font-size: 24px; font-weight: 600; max-width: 500px; margin: 0 auto; @media (max-width: 720px) { max-width: 300px; text-align: center; } ` const Text = styled.p`` const Button = styled.a` background: white; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15); border-radius: 8px; color: black; border: none; padding: 18px 60px; font-weight: 600; font-size: 24px; justify-self: center; cursor: pointer; transition: 0.8s cubic-bezier(0.2, 0.8, 0.2, 1); &:hover { box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15); transform: translateY(-3px); } @media (max-width: 375px) { padding: 12px 30px; font-size: 18px; } ` const LinkGroup = styled.div` max-width: 500px; margin: 50px auto; display: grid; grid-template-columns: repeat(2, 1fr); grid-gap: 10px; a { transition: 0.8s; } `
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:horizontal_calendar_widget/date_helper.dart'; import 'package:horizontal_calendar_widget/horizontal_calendar.dart'; import 'package:intl/intl.dart'; import 'components/components.dart'; void main() => runApp(MyApp()); int daysCount(DateTime first, DateTime last) => last.difference(first).inDays + 1; class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Horizontal Calendar Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar(title: Text('Horizontal Calendar Demo')), body: Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: DemoWidget(), ), ), ); } } const labelMonth = 'Month'; const labelDate = 'Date'; const labelWeekDay = 'Week Day'; class DemoWidget extends StatefulWidget { const DemoWidget({ Key key, }) : super(key: key); @override _DemoWidgetState createState() => _DemoWidgetState(); } class _DemoWidgetState extends State<DemoWidget> { DateTime firstDate; DateTime lastDate; String dateFormat = 'dd'; String monthFormat = 'MMM'; String weekDayFormat = 'EEE'; List<String> order = [labelMonth, labelDate, labelWeekDay]; bool forceRender = false; Color defaultDecorationColor = Colors.transparent; BoxShape defaultDecorationShape = BoxShape.rectangle; bool isCircularRadiusDefault = true; Color selectedDecorationColor = Colors.green; BoxShape selectedDecorationShape = BoxShape.rectangle; bool isCircularRadiusSelected = true; Color disabledDecorationColor = Colors.grey; BoxShape disabledDecorationShape = BoxShape.rectangle; bool isCircularRadiusDisabled = true; int minSelectedDateCount = 1; int maxSelectedDateCount = 1; RangeValues selectedDateCount; List<DateTime> initialSelectedDates; int initialScroll = 0; @override void initState() { super.initState(); const int days = 30; firstDate = toDateMonthYear(DateTime.now()); lastDate = toDateMonthYear(firstDate.add(Duration(days: days - 1))); selectedDateCount = RangeValues( minSelectedDateCount.toDouble(), maxSelectedDateCount.toDouble(), ); initialSelectedDates = feedInitialSelectedDates(minSelectedDateCount, days); } List<DateTime> feedInitialSelectedDates(int target, int calendarDays) { List<DateTime> selectedDates = List<DateTime>.empty(growable: true); for (int i = 0; i < calendarDays; i++) { if (selectedDates.length == target) { break; } DateTime date = firstDate.add(Duration(days: i)); if (date.weekday != DateTime.sunday) { selectedDates.add(date); } } return selectedDates; } @override Widget build(BuildContext context) { var horizontalCalendar = HorizontalCalendar( key: forceRender ? UniqueKey() : Key('Calendar'), height: 120, padding: EdgeInsets.all(22), firstDate: firstDate, lastDate: lastDate, initialScroll: initialScroll, dateFormat: dateFormat, weekDayFormat: weekDayFormat, monthFormat: monthFormat, defaultDecoration: BoxDecoration( color: defaultDecorationColor, shape: defaultDecorationShape, borderRadius: defaultDecorationShape == BoxShape.rectangle && isCircularRadiusDefault ? BorderRadius.circular(8) : null, ), selectedDecoration: BoxDecoration( color: selectedDecorationColor, shape: selectedDecorationShape, borderRadius: selectedDecorationShape == BoxShape.rectangle && isCircularRadiusSelected ? BorderRadius.circular(8) : null, ), disabledDecoration: BoxDecoration( color: disabledDecorationColor, shape: disabledDecorationShape, borderRadius: disabledDecorationShape == BoxShape.rectangle && isCircularRadiusDisabled ? BorderRadius.circular(8) : null, ), isDateDisabled: (date) => date.weekday == DateTime.sunday, labelOrder: order.map(toLabelType).toList(), minSelectedDateCount: minSelectedDateCount, maxSelectedDateCount: maxSelectedDateCount, initialSelectedDates: initialSelectedDates, ); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SizedBox(height: 16), horizontalCalendar, SizedBox(height: 32), Expanded( child: ListView( children: <Widget>[ Header(headerText: 'Date Ranges'), Row( children: <Widget>[ Expanded( child: PropertyLabel( label: 'First Date', value: Text(DateFormat('dd/MM/yyyy').format(firstDate)), onTap: () async { final date = await datePicker(context, firstDate); if (date == null) { return; } if (lastDate.isBefore(date)) { showMessage('First Date cannot be after Last Date'); return; } int min = minSelectedDateCount; if (!isRangeValid(date, lastDate, min)) { showMessage( "Date range is too low to set this configuration", ); return; } setState(() { forceRender = true; dateRangeChange(date, lastDate); }); }, ), ), Expanded( child: PropertyLabel( label: 'Last Date', value: Text(DateFormat('dd/MM/yyyy').format(lastDate)), onTap: () async { final date = await datePicker(context, lastDate); if (date == null) { return; } if (firstDate.isAfter(date)) { showMessage( 'Last Date cannot be before First Date', ); return; } int min = minSelectedDateCount; if (!isRangeValid(firstDate, date, min)) { showMessage( "Date range is too low to set this configuration", ); return; } setState(() { forceRender = true; dateRangeChange(firstDate, date); }); }, ), ), Expanded( child: TextField( decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password', ), onChanged: (format) { setState(() { initialScroll = 500; forceRender = false; }); }, )), ], ), Header(headerText: 'Date Selection'), PropertyLabel( label: 'Min-Max Selectable Dates ($minSelectedDateCount - $maxSelectedDateCount)', value: CustomRangeSlider( range: selectedDateCount, min: 0, max: 15, onRangeSet: (newRange) { selectedDateCount = newRange; }, ), ), ElevatedButton( child: Text('Update'), onPressed: () { setState(() { int min = selectedDateCount.start.toInt(); if (!isRangeValid(firstDate, lastDate, min)) { showMessage( "Date range is too low to set this configuration", ); return; } minSelectedDateCount = selectedDateCount.start.toInt(); maxSelectedDateCount = selectedDateCount.end.toInt(); initialSelectedDates = feedInitialSelectedDates( minSelectedDateCount, daysCount(firstDate, lastDate), ); showMessage("Updated"); }); }, ), Header(headerText: 'Formats'), PropertyLabel( label: 'Date Format', value: DropDownProperty( hint: 'Select Date Format', value: dateFormat, options: ['dd', 'dd/MM'], onChange: (format) { setState(() { forceRender = false; dateFormat = format; }); }, ), ), PropertyLabel( label: 'Month Format', value: DropDownProperty( hint: 'Select Month Format', value: monthFormat, options: [ 'MM', 'MMM', ], onChange: (format) { setState(() { forceRender = false; monthFormat = format; }); }, ), ), PropertyLabel( label: 'WeekDay Format', value: DropDownProperty( hint: 'Select Weekday Format', value: weekDayFormat, options: ['EEE', 'EEEE'], onChange: (format) { setState(() { forceRender = false; weekDayFormat = format; }); }, ), ), Header(headerText: 'Labels'), PropertyLabel( label: 'Label Orders (Drag & Drop to reorder)', value: Align( alignment: Alignment.centerLeft, child: Row( children: <Widget>[ SizedBox( height: 200, width: 150, child: ReorderableListView( children: order .map( (listItem) => Align( key: Key(listItem), heightFactor: 1, alignment: Alignment.centerLeft, child: Chip( onDeleted: () => listItem != labelDate ? setState(() { forceRender = false; order.remove(listItem); }) : null, deleteIcon: listItem != labelDate ? Icon(Icons.cancel) : null, label: Text(listItem), ), ), ) .toList(), onReorder: (oldIndex, newIndex) { setState(() { forceRender = false; if (newIndex > oldIndex) { newIndex -= 1; } final item = order.removeAt(oldIndex); order.insert(newIndex, item); }); }, ), ), ElevatedButton( child: Text('Add Labels'), onPressed: () { setState(() { forceRender = false; if (!order.contains(labelMonth)) { order.add(labelMonth); } if (!order.contains(labelWeekDay)) { order.add(labelWeekDay); } }); }, ) ], ), ), ), Header(headerText: 'Default Decoration'), DecorationBuilder( decorationShape: defaultDecorationShape, onSelectShape: (value) { setState(() { forceRender = false; defaultDecorationShape = value; }); }, isCircularRadius: isCircularRadiusDefault, onCircularRadiusChange: (isSelected) { setState( () { isCircularRadiusDefault = isSelected; }, ); }, color: defaultDecorationColor, onColorChange: (value) { setState(() { forceRender = false; defaultDecorationColor = value; }); }, ), Header(headerText: 'Selected Decoration'), DecorationBuilder( decorationShape: selectedDecorationShape, onSelectShape: (value) { setState(() { forceRender = false; selectedDecorationShape = value; }); }, isCircularRadius: isCircularRadiusSelected, onCircularRadiusChange: (isSelected) { setState( () { forceRender = false; isCircularRadiusSelected = isSelected; }, ); }, color: selectedDecorationColor, onColorChange: (value) { setState(() { forceRender = false; selectedDecorationColor = value; }); }, ), Header(headerText: 'Disabled Decoration'), DecorationBuilder( decorationShape: disabledDecorationShape, onSelectShape: (value) { setState(() { forceRender = false; disabledDecorationShape = value; }); }, isCircularRadius: isCircularRadiusDisabled, onCircularRadiusChange: (isSelected) { setState( () { forceRender = false; isCircularRadiusDisabled = isSelected; }, ); }, color: disabledDecorationColor, onColorChange: (value) { setState(() { forceRender = false; disabledDecorationColor = value; }); }, ) ], ), ) ], ); } void showMessage(String message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text(message)), ); } bool isRangeValid(DateTime first, DateTime last, int minSelection) { int availableDays = availableDaysCount( getDateList(first, last), [DateTime.sunday], ); return availableDays >= minSelection; } int availableDaysCount(List<DateTime> dates, List<int> disabledDays) => dates.where((date) => !disabledDays.contains(date.weekday)).length; void dateRangeChange(DateTime first, DateTime last) { firstDate = first; lastDate = last; initialSelectedDates = feedInitialSelectedDates( minSelectedDateCount, daysCount(first, last), ); selectedDateCount = RangeValues( minSelectedDateCount.toDouble(), maxSelectedDateCount.toDouble(), ); } } Future<DateTime> datePicker( BuildContext context, DateTime initialDate, ) async { final selectedDate = await showDatePicker( context: context, initialDate: initialDate, firstDate: DateTime.now().subtract( Duration(days: 365), ), lastDate: DateTime.now().add( Duration(days: 365), ), ); return toDateMonthYear(selectedDate); } LabelType toLabelType(String label) { LabelType type; switch (label) { case labelMonth: type = LabelType.month; break; case labelDate: type = LabelType.date; break; case labelWeekDay: type = LabelType.weekday; break; } return type; } String fromLabelType(LabelType label) { String labelString; switch (label) { case LabelType.month: labelString = labelMonth; break; case LabelType.date: labelString = labelDate; break; case LabelType.weekday: labelString = labelWeekDay; break; } return labelString; }
module Narrative class RoleDefinition attr_reader :name def initialize(name, partners, &responsibilities) @name = name @partners = partners @responsibilities = responsibilities end def cast!(actors) role = Module.new(&@responsibilities) acquaint! role, actors.slice(*@partners) actors[@name].extend(role) end private def acquaint!(role_module, partners) role_module.instance_eval do partners.each do |role_name, partner| define_method(role_name) { partner } private role_name end end end end end
import { PipeTransform } from '@angular/core'; import { getRandomNumber } from '../test-util/functions.util'; import { BooleanPipe } from './boolean.pipe'; describe('BooleanPipe', () => { let pipe: PipeTransform; beforeEach(() => { pipe = new BooleanPipe(); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('should return true when no value is specified as first argument - true case', () => { expect(pipe.transform(true)).toEqual('true'); }); it('should return false when no value is specified as first argument - false case', () => { expect(pipe.transform(false)).toEqual('false'); }); it('should return a custom value when specified as first argument - true case', () => { const trueVal = 'val-' + getRandomNumber() + 'rnd'; expect(pipe.transform(true, trueVal)).toEqual(trueVal); }); it('should return a custom value when specified as second argument - false case', () => { const falsyVal = 'val-' + getRandomNumber() + 'rnd'; expect(pipe.transform(false, undefined, falsyVal)).toEqual(falsyVal); }); });
# threaditjs-react A React/Redux implementation of ThreadItJS. [Demo](http://react.threaditjs.benpaulhanna.com/)
package environment.element import scoututil.Util._ import environment.layer._ import environment.element._ import environment.element.seed._ import scala.collection.mutable.{ArrayBuffer => AB} class WaterDepth(var value: Option[Double]) extends Element { val name = "Water Depth" val unit = "ft" val constant = false val radial = false val lowerBound = 0.0 val upperBound = 100.0 def this(d: Double) = this(Some(d)) def this() = this(None) } package seed { case class WaterDepthSeed( val elementName: String = "Water Depth", val dynamic: Boolean = true, val average: Double = 0.0, val deviation: Double = 0.2, val formFields: String = """{ "field-keys": [ ], "fields": { } }""" ) extends ElementSeed { def this(seedData: Map[String, String]) { this() } def buildLayer(height: Int, width: Int, scale: Double): Layer = { return new Layer(AB.fill(height)(AB.fill(width)(Some(new WaterDepth(0.0))))) } } }
##################### # BXEngine # # room.py # # Copyright 2021 # # Michael D. Reiley # ##################### # ********** # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # ********** from lib.logger import Logger class Room(object): """A class to represent the current room. :ivar config: This contains the engine's configuration variables. :ivar app: The main App instance. :ivar world: The World instance. :ivar resource: The ResourceManager instance. :ivar file: The filename of the room. :ivar vars: The JSON object representing the room file. :ivar image: The background image for this room. :ivar music: The music file loaded for this room, if any. :ivar log: The Logger instance for this class. """ def __init__(self, config, app, world, resource, room_file): """The Room initializer. :param config: This contains the engine's configuration variables. :param app: The main App instance. :param world: The World instance. :param resource: The ResourceManager instance. :param room_file: The filename of the room. """ self.config = config self.app = app self.world = world self.resource = resource self.file = room_file self.vars = None self.image = None self.music = None self.log = Logger("Room") def _load(self) -> bool: """Load the room descriptor JSON file. Also load the room image. :return: True if succeeded, False if failed. """ # Attempt to load the room file. self.log.info("Loading room: {0}".format(self.file)) self.vars = self.resource.load_json(self.file, "room") # We were unable to load the room file. if not self.vars: self.log.error("Unable to load room descriptor: {0}".format(self.file)) return False # Attempt to load the room's background image. self.image = self.resource.load_image(self.vars["image"], self.config["window"]["size"]) # We were unable to load the background image. if not self.image: self.log.error("Unable to load room image: {0}".format(self.vars["image"])) return False # Music is defined for this room. if "music" in self.vars: self.music = self.vars["music"] # A file is named. Attempt to play it, if not already playing. if type(self.music) is str: if self.app.audio.playing_music != self.music: self.app.audio.play_music(self.music) # The music was null, or a number of seconds to fade, so we are stopping all music. elif type(self.music) in [None, int, float]: self.app.audio.stop_music(self.music) # Success. self.log.info("Finished loading room: {0}".format(self.file)) return True
require 'spec_helper_acceptance' test_name 'simp_gitlab class' describe 'simp_gitlab class' do let(:server) {only_host_with_role( hosts, 'server' )} let(:permitted_client) {only_host_with_role( hosts, 'permittedclient' )} let(:denied_client) {only_host_with_role( hosts, 'unknownclient' )} let(:manifest) do <<-EOS include 'svckill' include 'iptables' iptables::listen::tcp_stateful { 'ssh': dports => 22, trusted_nets => ['any'], } class { 'simp_gitlab': trusted_nets => [ '10.0.0.0/8', '192.168.21.21', '192.168.21.22', '127.0.0.1/32', ], pki => false, firewall => true, } EOS end context 'default parameters' do # Using puppet_apply as a helper it 'should work with no errors' do apply_manifest_on(server, manifest, :catch_failures => true) end it 'should be idempotent' do apply_manifest_on(server, manifest, :catch_changes => true) end it 'allows http connection on port 80' do shell 'sleep 90' # give it some time to start up fqdn = fact_on(server, 'fqdn') result = on(permitted_client, "curl -L http://#{fqdn}/users/sign_in" ) expect(result.stdout).to match(/GitLab|password/) end it 'allows http connection on port 80 from permitted clients' do shell 'sleep 30' # give it some time to start up fqdn = fact_on(server, 'fqdn') # retry on first connection in case it still needs more time result = on(server, "curl --retry 3 --retry-delay 15 -L http://#{fqdn}/users/sign_in" ) expect(result.stdout).to match(/GitLab|password/) result = on(permitted_client, "curl -L http://#{fqdn}/users/sign_in" ) expect(result.stdout).to match(/GitLab|password/) # We are testing with firewall enabled, so we expect curl to fail # # Curl exit codes: # # 7 = Failed connect to #{fqdn} # 28 = Connection timed out # # Both exit codes have been encountered during testing, and I think it # depends on the whether the host system's network stack has been locked # down (ala SIMP) or not. result = on(denied_client, "curl -L http://#{fqdn}:777/users/sign_in", :acceptable_exit_codes => [7,28]) end end end
function javaversion(callback) { var spawn = require('child_process').spawn('java', ['-version']); spawn.on('error', function(err){ return callback(err, null); }) spawn.stderr.on('data', function(data) { data = data.toString().split('\n')[0]; var javaVersion = new RegExp('version').test(data) ? data.split(' ')[2].replace(/"/g, '') : false; if (javaVersion != false) { return callback(null, javaVersion.trim()); } else { // reportStatus('java', false); } }); spawn.on('exit', function(code) { if(code != 0) { reportStatus('java', false); } }) } const java = function(reportStatus) { javaversion(function(err,version){ if(version) { const v = version.split('.'); reportStatus('java', true, v); } else { reportStatus('java', true, version); } }); } const maven = function(reportStatus) { try { require('maven').create({quiet: true}).execute(['--version']).then( () => { reportStatus('mvn', true, 'not parsed'); }); } catch( error ) { reportStatus('mvn', false); } } const fail = function(reportStatus) { reportStatus('fail', false); } const available = { java: java, maven: maven, fail: fail } const status = { } function checkAvailable(tech, cb) { function reportStatus(technology, techstatus, version = undefined) { status[technology] = { available: techstatus, version }; if(Object.keys(status).length === tech.length) { let allok = true; Object.keys(status).forEach(key => { stat = status[key]; console.log(key,stat.available,stat.version); if(stat.available === false) allok = false; // yes, we could do this with an AND }) if(allok) { console.log('all checks passed'); } else { console.log('at least one check failed'); } cb(allok, status); } } if(tech.length === 0) { console.log('checking all') for(key in available) { available[key](reportStatus); } } else { if(tech[0] === 'available') { console.log('available checks:'); Object.keys(available).forEach(key => console.log(key)); } else { tech.forEach( arg => { available[arg](reportStatus); }) } } } module.exports = checkAvailable
#!/bin/sh dwm_date () { Date=$(date +'%Y-%m-%d %a %H:%M') printf "📆 ‧ $Date" } dwm_date
import {argsert} from './argsert.js'; import {isPromise} from './utils/is-promise.js'; import {YargsInstance, Arguments} from './yargs-factory.js'; export class GlobalMiddleware { globalMiddleware: Middleware[] = []; yargs: YargsInstance; frozens: Array<Middleware[]> = []; constructor(yargs: YargsInstance) { this.yargs = yargs; } addMiddleware( callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation: boolean, global = true, mutates = false ): YargsInstance { argsert( '<array|function> [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length ); if (Array.isArray(callback)) { for (let i = 0; i < callback.length; i++) { if (typeof callback[i] !== 'function') { throw Error('middleware must be a function'); } const m = callback[i] as Middleware; m.applyBeforeValidation = applyBeforeValidation; m.global = global; } Array.prototype.push.apply( this.globalMiddleware, callback as Middleware[] ); } else if (typeof callback === 'function') { const m = callback as Middleware; m.applyBeforeValidation = applyBeforeValidation; m.global = global; m.mutates = mutates; this.globalMiddleware.push(callback as Middleware); } return this.yargs; } // For "coerce" middleware, only one middleware instance can be registered // per option: addCoerceMiddleware( callback: MiddlewareCallback, option: string ): YargsInstance { const aliases = this.yargs.getAliases(); this.globalMiddleware = this.globalMiddleware.filter(m => { const toCheck = [...(aliases[option] || []), option]; if (!m.option) return true; else return !toCheck.includes(m.option); }); (callback as Middleware).option = option; return this.addMiddleware(callback, true, true, true); } getMiddleware() { return this.globalMiddleware; } freeze() { this.frozens.push([...this.globalMiddleware]); } unfreeze() { const frozen = this.frozens.pop(); if (frozen !== undefined) this.globalMiddleware = frozen; } reset() { this.globalMiddleware = this.globalMiddleware.filter(m => m.global); } } export function commandMiddlewareFactory( commandMiddleware?: MiddlewareCallback[] ): Middleware[] { if (!commandMiddleware) return []; return commandMiddleware.map(middleware => { (middleware as Middleware).applyBeforeValidation = false; return middleware; }) as Middleware[]; } export function applyMiddleware( argv: Arguments | Promise<Arguments>, yargs: YargsInstance, middlewares: Middleware[], beforeValidation: boolean ) { return middlewares.reduce<Arguments | Promise<Arguments>>( (acc, middleware) => { if (middleware.applyBeforeValidation !== beforeValidation) { return acc; } if (middleware.mutates) { if (middleware.applied) return acc; middleware.applied = true; } if (isPromise(acc)) { return acc .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)]) ) .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj) ); } else { const result = middleware(acc, yargs); return isPromise(result) ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) : Object.assign(acc, result); } }, argv ); } export interface MiddlewareCallback { (argv: Arguments, yargs: YargsInstance): | Partial<Arguments> | Promise<Partial<Arguments>>; } export interface Middleware extends MiddlewareCallback { applyBeforeValidation: boolean; global: boolean; option?: string; mutates?: boolean; applied?: boolean; }
(in-package #:ndjinn) (defun initialize-audio () (sdl2-mixer:init :flac :ogg) (sdl2-mixer:open-audio 44100 :s16sys 2 1024) (sdl2-mixer:allocate-channels 16)) (defun deinitialize-audio () (sdl2-mixer:halt-channel -1) (sdl2-mixer:close-audio) (sdl2-mixer:quit))
/******************************Module*Header*******************************\ * Module Name: efloat.hxx * * * * Contains internal floating point objects and methods. * * * * Created: 12-Nov-1990 16:45:01 * * Author: Wendy Wu [wendywu] * * * * Copyright (c) 1990 Microsoft Corporation * \**************************************************************************/ #define BOOL_TRUNCATE 0 #define BOOL_ROUND 1 // // IEEE format 32bits number // #define IEEE_0_0F ((FLOATL)0x00000000) #define IEEE_1_0F ((FLOATL)0x3F800000) #define IEEE_10_0F ((FLOATL)0x41200000) class EFLOAT; extern "C" { BOOL eftol_c(EFLOAT *, PLONG, LONG); BOOL eftofx_c(EFLOAT *, PFIX); LONG eftof_c(EFLOAT *); VOID ltoef_c(LONG, EFLOAT *); VOID fxtoef_c(FIX, EFLOAT *); VOID ftoef_c(FLOATL, EFLOAT *); // New style floating point support routines. The first pointer specifies // where to put the return value. The first pointer is the return value. EFLOAT *addff3_c(EFLOAT *,EFLOAT *,EFLOAT *); EFLOAT *subff3_c(EFLOAT *,EFLOAT *,EFLOAT *); EFLOAT *mulff3_c(EFLOAT *,const EFLOAT *,const EFLOAT *); EFLOAT *divff3_c(EFLOAT *,EFLOAT *,EFLOAT *); EFLOAT *sqrtf2_c(const EFLOAT *,const EFLOAT *); EFLOAT *fraction_c(EFLOAT *,EFLOAT *); }; class POINTFL; /*********************************Class************************************\ * class EFLOAT * * * * Energized floating point object. * * * * The floating point object defined below has 32 bits of signed mantissa * * and 16 bits of signed exponent. The decimal point is before the MSB * * of mantissa. The value of a number is determined by the following * * equation: * * value = 0.mantissa * 2^exponent * * * * Zero has only one unique representation with mantissa and exponent both * * zero. * * * * History: * * 12-Nov-1990 -by- Wendy Wu [wendywu] * * Wrote it. * \**************************************************************************/ class EFLOAT { public: // has to be public in order for EFLOAT_S i; // MAKEEFLOAT to do initializations public: EFLOAT_S Base() {return(i);} // Operator+= -- Add two EFLOAT numbers together. Caller is responsible for // overflow checking. VOID operator+=(EFLOAT& ef) {addff3_c(this,this,&ef);} // Operator-= -- Substract an EFLOAT number from another. Caller is // responsible for overflow checkings. VOID operator-=(EFLOAT& ef) {subff3_c(this,this,&ef);} // Operator*= -- Multiply two EFLOAT numbers together. Caller is responsible for // overflow checkings. VOID operator*=(EFLOAT& ef) {mulff3_c(this,this,&ef);} // vTimes16 -- Multiply an EFLOAT number by 16. VOID vTimes16() { if (i.lMant != 0) i.lExp += 4; } // Operator/ -- Divide an EFLOAT number by another. Caller is responsible for // overflow checkings. VOID operator/=(EFLOAT& ef) {divff3_c(this,this,&ef);} // vDivBy16 -- Divide an EFLOAT number by 16. VOID vDivBy16() { if (i.lMant != 0) i.lExp -= 4; } // vNegate - Negate an EFLOAT number. VOID vNegate() { if (i.lMant != 0x80000000) i.lMant = -i.lMant; else { i.lMant = 0x40000000; i.lExp += 1; } } // operator> -- Signed compare two numbers. See if an EFLOAT number is // greater than a given number. // Is there a better way to do this??? BOOL operator>(EFLOAT& ef) { LONG lsignSrc = ef.i.lMant >> 31, lsignDest = i.lMant >> 31; BOOL bReturn = FALSE; if (lsignSrc < lsignDest) // src is negative, dest is positive bReturn = TRUE; else if (lsignSrc > lsignDest) // src is positive, dest is negative ; else if (i.lExp == ef.i.lExp) // same sign, same exp, comp mantissa bReturn = i.lMant > ef.i.lMant; else if (lsignSrc == 0) // both src and dest are positive { if (((i.lExp > ef.i.lExp) && (i.lMant != 0)) || ef.i.lMant == 0) bReturn = TRUE; } else // both negative { if (i.lExp < ef.i.lExp) // zero won't reach here bReturn = TRUE; } return bReturn; } // operator<=,>,>=,== -- Compare two EFLOAT numbers. BOOL operator<=(EFLOAT& ef) { return(!((*this) > ef)); } BOOL operator<(EFLOAT& ef) { return(ef > (*this)); } BOOL operator>=(EFLOAT& ef) { return(ef <= (*this)); } BOOL operator==(EFLOAT& ef) { return((i.lMant == ef.i.lMant) && (i.lExp == ef.i.lExp)); } // Operator= -- Assign a value to an EFLOAT number. VOID operator=(LONG l) {ltoef_c(l,this);} VOID operator=(FLOATL f) {ftoef_c(f,this);} // vFxToEf -- Convert a FIX number to an EFLOAT number. // This could have been another operator=(FIX fx). However, since // FIX is defined as LONG. The compiler doesn't accept the second // definition. VOID vFxToEf(FIX fx) {fxtoef_c(fx,this);} // bEfToL -- Convert an EFLOAT number to a LONG integer. Fractions of 0.5 or // greater are rounded up. BOOL bEfToL(LONG &l) { return(eftol_c(this, &l, BOOL_ROUND)); } // bEfToLTruncate -- Convert an EFLOAT number to a LONG integer. The fractions // are truncated. BOOL bEfToLTruncate(LONG &l){ return(eftol_c(this, &l, BOOL_TRUNCATE)); } // lEfToF -- Convert an EFLOAT number to an IEEE FLOAT number. The return // value is placed in eax. // // NOTE: We want to treat it as a FLOATL (actually LONG, on X86) to avoid any fstp later. // LONG lEfToF() { return(eftof_c(this)); } VOID vEfToF(FLOATL &e) { LONG l = eftof_c(this); e = *((FLOATL *) (&l)); } // bEfToFx -- Convert an EFLOAT number to a FIX number. BOOL bEfToFx(FIX &fx) { return(eftofx_c(this, &fx)); } // bIsZero -- See if an EFLOAT number is zero. BOOL bIsZero() { return((i.lMant == 0) && (i.lExp == 0)); } // bIs16 -- Quick way to check the value of an EFLOAT number. BOOL bIs16() { return((i.lMant == 0x040000000) && (i.lExp == 6)); } BOOL bIsNeg16() { return((i.lMant == 0x0c0000000) && (i.lExp == 6)); } BOOL bIs1() { return((i.lMant == 0x040000000) && (i.lExp == 2)); } BOOL bIsNeg1() { return((i.lMant == 0x0c0000000) && (i.lExp == 2)); } BOOL bIs1Over16() { return((i.lMant == 0x040000000) && (i.lExp == -2)); } BOOL bIsNeg1Over16() { return((i.lMant == 0x0c0000000) && (i.lExp == -2)); } // vDivBy2 -- Divide an EFLOAT number by 2. VOID vDivBy2() { i.lExp -= 1; } VOID vMultByPowerOf2(INT ii) { i.lExp += (LONG) ii; } // vSetToZero -- Set the value of an EFLOAT number to zero. VOID vSetToZero() { i.lMant = 0; i.lExp = 0; } // vSetToOne -- Set the value of an EFLOAT number to one. VOID vSetToOne() {i.lMant=0x040000000; i.lExp=2;} // bIsNegative -- See if an EFLOAT number is negative. BOOL bIsNegative() { return(i.lMant < 0); } // signum -- Return a LONG representing the sign of the number. LONG lSignum() {return((i.lMant > 0) - (i.lMant < 0));} // vAbs -- Compute the absolute value. VOID vAbs() { if (bIsNegative()) vNegate(); } // vFraction -- Get the fraction part of an EFLOAT number. The result is // stored in the passed in parameter. VOID vFraction(EFLOAT& ef) {fraction_c(&ef,this);} // bExpInRange -- See if the exponent of an EFLOAT number is within the // given range. BOOL bExpLessThan(LONG max) { return(i.lExp <=max); } // vSqrt -- Takes the square root. VOID vSqrt() {sqrtf2_c(this,this);} // New style math routines. // // Usage example: EFLOAT z,t; z.eqAdd(x,t.eqSqrt(y)); // This would be the same as: EFLOAT z,t; z = x + (t = sqrt(y)); // // I.e. you can build complex expressions, but you must declare your own // temporaries. EFLOAT& eqSqrt(const EFLOAT& ef) { return(*sqrtf2_c(this,&ef)); } EFLOAT& eqAdd(EFLOAT& efA,EFLOAT& efB) { return(*addff3_c(this,&efA,&efB)); } EFLOAT& eqSub(EFLOAT& efA,EFLOAT& efB) { return(*subff3_c(this,&efA,&efB)); } EFLOAT& eqMul(const EFLOAT& efA,const EFLOAT& efB) { return(*mulff3_c(this,&efA,&efB)); } EFLOAT& eqDiv(EFLOAT& efA,EFLOAT& efB) { return(*divff3_c(this,&efA,&efB)); } EFLOAT& eqFraction(EFLOAT& ef) { return(*fraction_c(this,&ef)); } EFLOAT& eqAbs(EFLOAT& ef) { i.lExp = ef.i.lExp; i.lMant = ef.i.lMant; if (i.lMant < 0) { if (i.lMant != 0x80000000) { i.lMant = -i.lMant; } else { i.lMant = 0x40000000; i.lExp++; } } return(*this); } // eqDot -- Dot product of two vectors. EFLOAT eqDot(const POINTFL&,const POINTFL&); // eqCross -- Cross product of two vectors. (A scaler in 2 dimensions.) EFLOAT eqCross(const POINTFL&,const POINTFL&); // eqLength -- Length of a vector. EFLOAT eqLength(const POINTFL&); }; class EFLOATEXT: public EFLOAT { public: EFLOATEXT() {} EFLOATEXT(LONG l) {ltoef_c(l,this);} EFLOATEXT(FLOATL e) {ftoef_c(e,this);} VOID operator=(const EFLOAT& ef) {*(EFLOAT*) this = ef;} VOID operator=(LONG l) {*(EFLOAT*) this = l;} VOID operator*=(LONG l) { EFLOATEXT efT(l); mulff3_c(this,this,&efT); } VOID operator*=(EFLOAT& ef) { *(EFLOAT*)this *= ef; } VOID operator/=(EFLOAT& ef) { *(EFLOAT*)this /= ef; } VOID operator/=(LONG l) { EFLOATEXT efT(l); divff3_c(this,this,&efT); } }; extern "C" LONG lCvt(EFLOAT ef,LONG ll);
using OpenTK.Mathematics; namespace Engine.Animations { public struct KeyPosition { public Vector3 Position; public float TimeStamp; } public struct KeyRotation { public Quaternion Orientation; public float TimeStamp; } public struct KeyScale { public Vector3 Scale; public float TimeStamp; } }
--- title: "Workshop on Blockchain Technologies" collection: talks type: "Workshop" permalink: /talks/2020-01-20-21_Blockchain_Technologies_Workshop venue: "NSS College of Engineering, Palakkad" date: 2020-01-20 & 2020-01-21 location: "Coimbatore, India" ---
module UsersHelper def check_user return unless current_user?(@user) content_tag(:a, link_to("Delete #{@user.name}", @user, method: :delete, data: { confirm: 'You sure?' }, class: 'badge bg-secondary')) end def check_access render inline: ' <div class="card" style="width: 100%;"> <% @user.invited_to_events.each do |event| %> <div class="card-body"> <h5 class="card-title"><%= event.location %></h5> <h6 class="card-subtitle mb-2 text-muted"><%= event.date %></h6> <p class="card-text"><%= event.description %></p> <a href="#" class="card-link"><%= link_to "Show", event %></a> <% if current_user?(@user) %> <%= link_to "Accept Invite", { controller: "users", action: "accept_invite", event_id: event.id }, class:"badge bg-secondary" %> <% end %> </div> <% end %> </div>' end def user_attend render inline: ' <% @past_attended.each do |event| %> <div class="card-body"> <h5 class="card-title"><%= event.location %></h5> <h6 class="card-subtitle mb-2 text-muted"><%= event.date %></h6> <p class="card-text"><%= event.description %></p> <a href="#" class="card-link"><%= link_to "Show", event %></a> <% if current_user?(@user) %> <%= link_to "Decline Invite", { controller: "users", action: "decline_invite", event_id: event.id }, class:"badge bg-secondary" %> <% end %> </div> <% end %> ' end def user_attend_upcom render inline: ' <% @upcoming_attended.each do |event| %> <div class="card-body"> <h5 class="card-title"><%= event.location %></h5> <h6 class="card-subtitle mb-2 text-muted"><%= event.date %></h6> <p class="card-text"><%= event.description %></p> <a href="#" class="card-link"><%= link_to "Show", event %></a> <% if current_user?(@user) %> <%= link_to "Decline Invite", { controller: "users", action: "decline_invite", event_id: event.id }, class:"badge bg-secondary" %> <% end %> </div> <% end %> ' end end
import 'package:atlas/atlas.dart'; class DeviceLocation { final LatLng target; final double? accuracy; final double altitude; const DeviceLocation({ required this.target, this.accuracy = 0.0, this.altitude = 0.0, }); @override bool operator ==(Object other) { if (identical(this, other)) return true; if (other.runtimeType != runtimeType) return false; if (other is DeviceLocation) { return target == other.target && accuracy == other.accuracy && altitude == other.altitude; } else { return false; } } @override int get hashCode => target.hashCode ^ accuracy.hashCode ^ altitude.hashCode; }
<?php namespace MarsRover\Repository; class RoverRepository { public $redis; public function __construct($redis) { $this->redis = $redis; } public function getAllRovers() { return $this->redis->hGetAll(REDIS_ROVER_LIST); } public function getSingleRover(int $plateauid) { return $this->redis->hGet(REDIS_ROVER_LIST, $plateauid); } public function createNewRower(string $setup) { $newRoverID = $this->redis->incr(REDIS_LAST_ROVER_ID); $this->redis->hSet(REDIS_ROVER_LIST, $newRoverID, $setup); return $newRoverID; } public function setRowerCoordinates($newRoverID, $setup): void { $this->redis->hSet(REDIS_ROVER_LIST, $newRoverID, $setup); } }
program append_h5 use, intrinsic :: iso_fortran_env use hdf5 implicit none integer, parameter :: sp = REAL32 integer, parameter :: pos_space_rank = 3, pos_rank = 2, nr_pos = 10 character(len=3) :: dset_name = "pos" character(len=1024) :: file_name logical :: file_exists integer :: status, ierr integer(hid_t) :: file_id, dset_id, dspace_id, & dset_prop_id, fspace_id integer(hsize_t), dimension(pos_rank) :: pos_dim, max_pos_dim, & pos_chunk_dim, pos_offset, & new_pos_dim real(kind=sp), dimension(pos_space_rank, nr_pos) :: data integer :: i, j ! get file name from command line arguments if (command_argument_count() /= 1) then write (unit=error_unit, fmt="(A)") "#error: no file name given" stop end if call get_command_argument(1, file_name) ! open HDF5 Fortran interface call h5open_f(status) ! check whether file exists inquire(file=file_name, exist=file_exists) if (file_exists) then ! open HDF5 file call h5fopen_f(trim(file_name), H5F_ACC_RDWR_F, file_id, status) else ! create new file call h5fcreate_f(trim(file_name), H5F_ACC_TRUNC_F, file_id, status) end if ! open dataset call h5eset_auto_f(0, ierr) call h5dopen_f(file_id, dset_name, dset_id, status) call h5eset_auto_f(1, ierr) call h5eclear_f(ierr) ! if dataset doesn't exist, create it if (status < 0) then if (file_exists) then write(unit=error_unit, fmt="(3A)") "#error: file '", & trim(file_name), "' was not created with append_h5" stop else ! set dimenions and create filespace pos_dim(1) = pos_space_rank pos_dim(2) = 0 max_pos_dim(1) = pos_space_rank max_pos_dim(2) = H5S_UNLIMITED_F call h5screate_simple_f(pos_rank, pos_dim, fspace_id, status, & max_pos_dim) ! set chunk sizes and create dataset pos_chunk_dim(1) = pos_space_rank pos_chunk_dim(2) = nr_pos call h5pcreate_f(H5P_DATASET_CREATE_F, dset_prop_id, status) call h5pset_chunk_f(dset_prop_id, pos_rank, pos_chunk_dim, status) ! create dataset call h5dcreate_f(file_id, dset_name, H5T_NATIVE_REAL, & fspace_id, dset_id, status, dset_prop_id) if (status /= 0) then write(unit=error_unit, fmt="(3A)") "#error: can not create '", & trim(dset_name), "'" stop end if ! close property and filespace call h5pclose_f(dset_prop_id, status) call h5sclose_f(fspace_id, status) end if end if ! get filespace, get current dimensions and close filespace call h5dget_space_f(dset_id, fspace_id, status) call h5sget_simple_extent_dims_f(fspace_id, pos_dim, max_pos_dim, status) call h5sclose_f(fspace_id, status) ! extend data set to accomodate new data, and close it new_pos_dim(1) = pos_dim(1) new_pos_dim(2) = nr_pos + pos_dim(2) call h5dextend_f(dset_id, new_pos_dim, status) call h5dclose_f(dset_id, status) ! compute data do j = 1, nr_pos do i = 1, pos_space_rank data(i, j) = 1.0_sp*i*j + real(pos_dim(2)) end do end do ! create a hyperslab pos_offset(1) = 0 pos_offset(2) = pos_dim(2) pos_chunk_dim(1) = pos_space_rank pos_chunk_dim(2) = nr_pos call h5dopen_f(file_id, dset_name, dset_id, status) call h5dget_space_f(dset_id, fspace_id, status) call h5sselect_hyperslab_f(fspace_id, H5S_SELECT_SET_F, pos_offset, & pos_chunk_dim, status) call h5screate_simple_f(pos_rank, pos_chunk_dim, dspace_id, status) ! write data to HDF5 file call h5dwrite_f(dset_id, H5T_NATIVE_REAL, data, pos_chunk_dim, status, & mem_space_id=dspace_id, file_space_id=fspace_id) ! close filespace, dataset call h5sclose_f(fspace_id, status) call h5sclose_f(dspace_id, status) call h5dclose_f(dset_id, status) ! close HDF% file call h5fclose_f(file_id, status) ! close HDF5 Fortran interface call h5close_f(status) end program append_h5
import 'dart:convert'; import 'package:online_school/model/document_model.dart'; import 'package:online_school/model/live_courseware_model.dart'; import 'package:online_school/model/material_list_model.dart'; import 'package:online_school/model/material_model.dart'; import 'package:online_school/common/const/api_const.dart'; import 'package:online_school/common/network/network_manager.dart'; import 'package:online_school/common/network/response.dart'; import 'package:dio/dio.dart'; class MaterialDao { /// listType:AI 1,智慧学习 2 static Future<ResponseData> getMaterials(subjectId, gradeId, listType) async { var url = APIConst.CC_BASE_URL + 'api-service-general-wx/materials/version/material'; var query = mapToQuery({ 'subjectId': subjectId.toString(), 'gradeId': gradeId.toString(), 'listType': listType.toString() }); url = '$url?$query'; var response = await NetworkManager.netFetch(url, null, null, null); if (response.result) { var model = MaterialListModel.fromJson(response.data); response.model = model; } return response; } /// 获取已选教材 /// type: /// 1,AI测试(AI) /// 2,智慧学习 static Future<ResponseData> material(subjectId, gradeId, type) async { var url = APIConst.CC_BASE_URL + 'api-service-general-wx/materials/grade/subject'; var query = mapToQuery({ 'subjectId': subjectId.toString(), 'gradeId': gradeId.toString(), 'type': type.toString() }); url += '?$query'; var response = await NetworkManager.netFetch(url, null, null, null); if (response.result) { var courseList = MaterialModel.fromJson(response.data); response.model = courseList; } return response; } /// 获取已选教材下的所有课程文档 /// 传参说明:(gradeId, subjectId) 和 (materialId) 等价,二选一 /// http://int.etiantian.com:39804/display/zz/NEW-ETT-API-29-V2.0 static Future<ResponseData> getMaterialDocuments( {String gradeId, String subjectId, String materialId}) async { // assert((gradeId != null && subjectId != null && materialId == null) || // (gradeId == null && subjectId == null && materialId != null)); var url = APIConst.CC_BASE_URL + 'api-service-course-wx/wx-chapter/resource'; var query; if (materialId != null) { query = mapToQuery({'materialId': materialId}); } else { query = mapToQuery({ 'subjectId': subjectId, 'gradeId': gradeId, }); } url += '?$query'; var response = await NetworkManager.netFetch(url, null, null, null); if (response.result) { var docs = DocumentModel.fromJson(response.data); response.model = docs; } return response; } /// 获取直播课的课件 static Future<ResponseData> getLiveCourseware({String courseId}) async { // assert((gradeId != null && subjectId != null && materialId == null) || // (gradeId == null && subjectId == null && materialId != null)); var url = APIConst.CC_BASE_URL + 'api-study-service/api/course/{courseId}/coursewares/list'; url = url.replaceFirst('{courseId}', courseId); var response = await NetworkManager.netFetch(url, null, null, null); if (response.result) { var docs = LiveCoursewareModel.fromJson(response.data); response.model = docs; } return response; } /// 保存教材 /// type:1 AI, 2 自学 static Future<ResponseData> saveMaterial( versionId, materialId, subjectId, gradeId, type) async { var url = APIConst.CC_BASE_URL + 'api-service-general-wx/materials'; var body = jsonEncode({ 'versionId': versionId.toString(), 'materialId': materialId.toString(), 'subjectId': subjectId.toString(), 'gradeId': gradeId.toString(), 'type': type.toString() }); var headers = {'content-type': 'application/json'}; var response = await NetworkManager.netFetch(url, body, headers, Options(method: 'POST')); if (response.result) { var model = MaterialListModel.fromJson(response.data); response.model = model; } return response; } }
#!/bin/bash for i in {1..5}; do find "/home/camera/cam$i" -type f -mtime +7 -delete done
package eu.kanade.tachiyomi.ui.browse.animesource.globalsearch import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.data.database.models.Anime /** * Adapter that holds the anime items from search results. * * @param controller instance of [GlobalSearchController]. */ class GlobalAnimeSearchCardAdapter(controller: GlobalAnimeSearchController) : FlexibleAdapter<GlobalAnimeSearchCardItem>(null, controller, true) { /** * Listen for browse item clicks. */ val animeClickListener: OnAnimeClickListener = controller /** * Listener which should be called when user clicks browse. * Note: Should only be handled by [GlobalSearchController] */ interface OnAnimeClickListener { fun onAnimeClick(anime: Anime) fun onAnimeLongClick(anime: Anime) } }
-- | Where I put the monolithic run function, which solves the -- general problem of: -- > if C[E] = E' -- > then C = Inventor.run E E' -- The first term argument @E@ should always be -- a fixpoint with all arguments applied. module Elea.Inventor ( run ) where import Elea.Prelude import Elea.Term import Elea.Context ( Context ) import Elea.Show ( showM ) import qualified Elea.Unification as Unifier import qualified Elea.Index as Indices import qualified Elea.Monad.Env as Env import qualified Elea.Terms as Term import qualified Elea.Types as Type import qualified Elea.Simplifier as Simp import qualified Elea.Context as Context import qualified Elea.Equality as Equality import qualified Elea.Foldable as Fold import qualified Elea.Fixpoint as Fix import qualified Elea.Checker as Checker import qualified Elea.Constraint as Constraint import qualified Elea.Monad.Failure.Class as Fail import qualified Elea.Monad.Definitions.Class as Defs import qualified Elea.Monad.Memo.Class as Memo import qualified Data.Set as Set run :: forall m . (Env.All m, Defs.Read m, Fail.Can m, Memo.Can m) -- | A simplification function to be called within run. => (Term -> m Term) -> Term -> Term -> m Context run simplify f_term@(App f_fix@(Fix {}) f_args) g_term = do Fail.unless (Term.inductivelyTyped f_term) inventor g_term where -- The inductive type of f_term f_ty@(Type.Base f_ind) = Type.get f_term -- We use a helper function because the first two arguments never change. inventor :: Term -> m Context -- If g_term has a constructor topmost, we use that as the outer context -- and run run on one of the arguments. This assumes that only one -- argument will contain a fixpoint. inventor g_term@(App g_con@(Con {}) g_args) = do Fail.unless (length complex_args == 1) inner_ctx <- run simplify f_term (g_args `nth` arg_i) return (con_ctx ++ inner_ctx) where complex_args = findIndices (not . Term.isSimple) g_args [arg_i] = complex_args con_ctx = Context.make mkConCtx where mkConCtx gap = app g_con (setAt arg_i gap g_args) -- If g_term has a pattern match topmost, we use that as the outer context -- and run run on one of the branches, or the matched term, provided -- only one is non-simple. inventor g_term@(Case cse_t alts) -- If every branch is simple, use the match as a context -- around the matched term | length complex_alts == 0 = do inner_ctx <- run simplify f_term cse_t return (match_ctx ++ inner_ctx) -- If exactly one brach is non-simple, use that branch term as a context | length complex_alts == 1 = do inner_ctx <- Env.bindMany alt_bs (run simplify f_term alt_t) return (alt_ctx ++ inner_ctx) | length complex_alts > 1 = Fail.here where complex_alts = findIndices (not . Term.isSimple . get altInner) alts [alt_i] = complex_alts Alt alt_con alt_bs alt_t = alts `nth` alt_i match_ctx = Context.make $ \gap -> Case gap alts alt_ctx = Context.make $ \gap -> Case cse_t (setAt alt_i (Alt alt_con alt_bs gap) alts) -- If the two terms are just equal, we can return the identity context inventor g_term@(App (Fix {}) _) | f_term == g_term = return mempty -- If the inner term is non-recursively typed then we can use the special -- case where we fuse a pattern match over f_term into g_term inventor g_term@(App g_fix@(Fix {}) g_args) | not (Type.isRecursive f_ind) = do alts <- mapM makeAlt [0..length g_ind_cons - 1] return $ Context.make $ \gap -> Case gap alts where g_ty@(Type.Base (Type.Ind _ g_ind_cons)) = Type.get g_term makeAlt :: Nat -> m Alt makeAlt con_n = do alt_t <- Fix.constraintFusion simplify constr g_term return . Alt con alt_bs . Constraint.removeAll $ Indices.liftMany (length alt_bs) alt_t where constr = Constraint.make con f_term alt_bs = Type.makeAltBindings con con = Constructor f_ind con_n -- Otherwise we need to do proper fixpoint invention inventor g_term@(App (Fix {}) _) = do -- DEBUG f_term_s <- showM f_term g_term_s <- showM g_term let s1 = "\nInventing C s.t. C[" ++ f_term_s ++ "] is " ++ g_term_s -- Retrieve the type of f_term and g_term -- so we can pass them to inventCase f_ty <- id -- . trace s1 $ Type.getM f_term let Type.Base ind_ty@(Type.Ind _ cons) = f_ty g_ty <- Type.getM g_term -- We are inventing a fold function and inventCase discovers each of -- the fold parameters fold_cases <- mapM (inventCase f_ty g_ty . toEnum) [0..length cons - 1] let fold_f = Term.buildFold ind_ty g_ty fold = Simp.run (app fold_f fold_cases) ctx = Context.make (\t -> app fold [t]) -- This algorithm is not sound by construction, so we check its -- answer using our equation solver let ctx_f_term = Context.apply ctx f_term eq <- Equality.prove simplify ctx_f_term g_term Fail.unless eq return ctx where inventCase :: Type -> Type -> Nat -> m Term inventCase f_ty g_ty con_n = do -- Fuse this context with the inner fixpoint. -- If this fails then just unroll the inner fixpoint once. -- For now we don't use this, because it just makes computation longer -- and is only for more advanced examples we can't do yet anyway mby_fused_eq <- return Nothing -- Fail.catch (fusion (\_ _ -> simplify) full_ctx f_fix) fused_eq <- case mby_fused_eq of Just eq -> return eq Nothing -> simplify (Context.apply full_ctx (Term.unfoldFix f_fix)) -- DEBUG fused_eq_s <- showM fused_eq let s2 = "\nBranch: " ++ fused_eq_s -- Find a function which satisfies the equation func <- id -- . trace s2 . Fail.fromMaybe . Env.trackOffset . Fold.findM (runMaybeT . caseFunction) $ fused_eq -- DEBUG func_s <- showM func let s3 = "\nFunction discovered: " ++ func_s return -- . trace s3 $ func where -- Constrain @f_term@ to be this particular constructor cons_con = Constructor (Type.inductiveType f_ty) con_n constraint_ctx = Constraint.makeContext cons_con f_term eq_ty -- We represent the equation using a new inductive type. eq_ind = Type.Ind "__EQ" [("==", [Type.ConArg f_ty, Type.ConArg g_ty])] eq_ty = Type.Base eq_ind eq_con = Constructor eq_ind 0 -- Build a context which is an equation between f_term and g_term -- where the fixpoint in f_term has been replaced by the gap. eq_ctx = Context.make makeEqCtx where makeEqCtx gap_f = app (Con eq_con) [app gap_f f_args, g_term] -- Compose the constraint with the equation context -- using the context monoid full_ctx = constraint_ctx ++ eq_ctx caseFunction :: Term -> MaybeT Env.TrackOffset Term caseFunction t@(App (Con eq_con') [left_t, right_t]) -- Make sure this is actually an equation | eq_con' == eq_con , get (Type.indName . Type.constructorOf) eq_con' == "__EQ" = do -- Check the shape of the left side of the equation is -- the constructor we are finding the case for Fail.unless (isCon left_f) Fail.unless (Constructor ind con_n == con') -- Try to invent a function which satisfies the equation at this point. func <- id . foldrM constructFunction right_t $ zip con_args left_args -- Lower the indices in the discovered function to be valid -- outside this point in the term. -- Remember we have descended into a term to collect equations. offset <- Env.offset Fail.unless (Indices.lowerableBy offset func) return (Indices.lowerMany offset func) where Type.Base ind@(Type.Ind _ cons) = f_ty left_f:left_args = Term.flattenApp left_t Con con' = left_f (_, con_args) = id . assert (length cons > con_n) $ cons `nth` enum con_n -- We move through the constructor arguments backwards, building -- up the term one by one. constructFunction :: (Type.ConArg, Term) -> Term -> MaybeT Env.TrackOffset Term -- If we are at a regular constructor argument (non recursive) -- then the term at this position should just be a variable. constructFunction (Type.ConArg ty, Var x) term = return . Lam (Bind "x" ty) -- Replace the variable at this position with the newly lambda -- abstracted variable . Indices.replaceAt (succ x) (Var 0) $ Indices.lift term -- If we are at a non variable recursive constructor argument, -- then we'll need to rewrite the recursive call to @f_term@. constructFunction (Type.IndVar, rec_term) term = do -- Need to lift the indices in @f_term@ and @g_term@ to be -- what they would be at this point inside the equation term. f_term' <- Env.liftByOffset f_term g_term' <- Env.liftByOffset g_term uni <- Unifier.find f_term' rec_term let g_term'' = Unifier.apply uni g_term' return . Lam (Bind "x" g_ty) . Term.replace (Indices.lift g_term'') (Var 0) $ Indices.lift term constructFunction _ _ = Fail.here caseFunction _ = Fail.here inventor _ = Fail.here
# regular try/except # anything in try block is executed until any Exception occurs # then that exception will be catched in one of the except blocks try: a = input('Enter a number: ') b = input('Enter a number: ') c = int(int(a) / int(b)) print(f'{a}/{b}={c}') except ZeroDivisionError as ex: print(f'Cannot devide by {b}') except ValueError as ex: print(f'Cannot convert entered value {a} or {b} to number') finally: print('This is the end of the statement') # the finally block is always executed weather or not the try block has exception # even if in a loop and we put a break or continue when an exception is caught while True: try: a = input('Enter a number: ') b = input('Enter a number: ') c = int(int(a) / int(b)) print(f'{a}/{b}={c}') except ZeroDivisionError as ex: print(f'Cannot devide by {b}') continue except ValueError as ex: print(f'Cannot convert entered value {a} or {b} to number') break finally: print('This is the end of the statement')
require 'spec_helper' describe Ingredient do before do @ingredient = FactoryGirl.build(:ingredient) end subject { @ingredient } it { is_expected.to respond_to(:name) } it { is_expected.to respond_to(:recipes) } describe "when name is not present" do before { @ingredient.name = " " } it { is_expected.not_to be_valid } end describe "when name is too long" do before { @ingredient.name = "a" * 500 } it { is_expected.not_to be_valid } end end
(function(){ var element = document.getElementById('header'), content = new Array(), joined, first = 'This is a first item', second = 'This is a second item', another = 'And another one!', last = '...and a last one'; content.push('<ul>'); content.push('<li>'); content.push(first); content.push('</li>'); content.push('<li>'); content.push(second); content.push('</li>'); content.push('<li>'); content.push(another); content.push('</li>'); content.push('<li>'); content.push(last); content.push('</li>'); content.push('</ul>'); joined = content.join("\n"); element.insertAdjacentHTML('afterend', joined); }());
# ssdump.py # Catalogues items in a SyncSketch.com account # Requires ss_username and ss_api_key to be exported in env var # Requires keywords from account-specific items in config.yaml # pip3 install yaml confuse syncsketch from syncsketch import SyncSketchAPI import yaml import confuse from os import environ import sys from ssdict import ssdict def findObject(dict,keywd): for item in dict: if keywd in item['name']: theMedia = item break else: theMedia = {} return theMedia configuration = confuse.Configuration("sstest", __name__) configuration.set_file('./config.yaml') BASE_URL=configuration['base_url'].get() if "ss_username" in environ: USERNAME = environ.get('ss_username') else: print('\nPlease export your Syncsketch username as an environment variable called "ss_username"\n') sys.exit() if "ss_api_key" in environ: API_KEY = environ.get('ss_api_key') else: print('\nPlease export your Syncsketch API key as an environment variable called "ss_api_key"\n') sys.exit() ss = SyncSketchAPI(USERNAME,API_KEY) print('\nConnected to SyncSketch? ' + str(ss.is_connected())) # Fetch Accounts # gets first account accounts = ss.get_accounts() ACCOUNT_ID = accounts['objects'][0] print('\nAccount ID: ' + str(ACCOUNT_ID['id']) + ': ' + ACCOUNT_ID['name']) # Fetch Projects projectsDict = ssdict(ss,ACCOUNT_ID,'projects') print(projectsDict.getCatalogue()) # Choose a Project Under Test itemkeyword = configuration['ProjectUnderTest'].get() theProject = findObject(projectsDict.collection,itemkeyword) # Fetch Reviews reviewsDict = ssdict(ss,theProject['id'],'reviews') print(reviewsDict.getCatalogue()) #Choose a Review Under Test itemkeyword = configuration['ReviewUnderTest'].get() theReview = findObject(reviewsDict.collection,itemkeyword) # Fetch Items itemsDict = ssdict(ss,theReview['id'],'items') print(itemsDict.getCatalogue()) #Choose an Item Under Test itemkeyword = configuration['ItemUnderTest'].get() theItem = findObject(itemsDict.collection,itemkeyword) # Fetch Comments commentsDict = ssdict(ss,theItem['id'],'comments') print(commentsDict.getCatalogue())
<?php use FluidEdgeNamespace\Modules\Header\Lib; if(!function_exists('fluid_edge_set_header_object')) { function fluid_edge_set_header_object() { $header_type = fluid_edge_get_meta_field_intersect('header_type', fluid_edge_get_page_id()); $object = Lib\HeaderFactory::getInstance()->build($header_type); if(Lib\HeaderFactory::getInstance()->validHeaderObject()) { $header_connector = new Lib\HeaderConnector($object); $header_connector->connect($object->getConnectConfig()); } } add_action('wp', 'fluid_edge_set_header_object', 1); }
<?php // Copyright 2004-present Facebook. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Facebook\WebDriver; use Facebook\WebDriver\Remote\RemoteWebDriver; use PHPUnit\Framework\BaseTestListener; class ReportSauceLabsStatusListener extends BaseTestListener { public function endTest(\PHPUnit_Framework_Test $test, $time) { if (!$test instanceof WebDriverTestCase || !$test->driver instanceof RemoteWebDriver) { return; } /** @var WebDriverTestCase $test */ if (!$test->isSauceLabsBuild()) { return; } $testStatus = $test->getStatus(); if ($this->testWasSkippedOrIncomplete($testStatus)) { return; } $endpointUrl = sprintf( 'https://saucelabs.com/rest/v1/%s/jobs/%s', getenv('SAUCE_USERNAME'), $test->driver->getSessionID() ); $data = [ 'passed' => ($testStatus === \PHPUnit_Runner_BaseTestRunner::STATUS_PASSED), 'custom-data' => ['message' => $test->getStatusMessage()], ]; $this->submitToSauceLabs($endpointUrl, $data); } /** * @param int $testStatus * @return bool */ private function testWasSkippedOrIncomplete($testStatus) { if ($testStatus === \PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED || $testStatus === \PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE) { return true; } return false; } /** * @param string $url * @param array $data */ private function submitToSauceLabs($url, array $data) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($curl, CURLOPT_USERPWD, getenv('SAUCE_USERNAME') . ':' . getenv('SAUCE_ACCESS_KEY')); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Disable sending 'Expect: 100-Continue' header, as it is causing issues with eg. squid proxy curl_setopt($curl, CURLOPT_HTTPHEADER, ['Expect:']); curl_exec($curl); if (curl_errno($curl)) { throw new \Exception(sprintf('Error publishing test results to SauceLabs: %s', curl_error($curl))); } curl_close($curl); } }
package flowar // Edge represents an edge of a directed graph. type Edge struct { Tail int Head int Length int } // PathMap represents the length of a path from a vertex to another. type PathMap map[int]map[int]int // Get gets the path length from a to b. func (pm PathMap) Get(a, b int) (length int, ok bool) { fromA := pm[a] if fromA == nil { return } length, ok = fromA[b] return } // Set sets a path from a to b with length. func (pm PathMap) Set(a, b int, length int) { fromA := pm[a] if fromA == nil { fromA = make(map[int]int) pm[a] = fromA } fromA[b] = length } // FloydWarshall returns All-pairs shortest paths calculated by Floyd-Warshall algorithm. // It also returns negCycle, which represents whether or not a negative cylce exists in the graph. func FloydWarshall(edges []Edge) (shortestPaths PathMap, negCycle bool) { // Init V := make(map[int]bool) A := make(PathMap) for _, e := range edges { V[e.Tail] = true V[e.Head] = true A.Set(e.Tail, e.Head, e.Length) } for v := range V { A.Set(v, v, 0) } // Run dynamic programming for k := range V { A1 := make(PathMap) for i := range V { for j := range V { cands := []int{} ij, ok0 := A.Get(i, j) if ok0 { cands = append(cands, ij) } ik, ok1 := A.Get(i, k) kj, ok2 := A.Get(k, j) if ok1 && ok2 { cands = append(cands, ik+kj) } for _, length := range cands { prev, ok := A1.Get(i, j) if !ok || (ok && length < prev) { A1.Set(i, j, length) } } } } A = A1 } // Return shortestPaths = A negCycle = false for v := range V { length, ok := A.Get(v, v) if ok && length < 0 { negCycle = true break } } return }
package freetds import ( "strconv" "strings" ) type credentials struct { user, pwd, host, database, mirrorHost, compatibility string maxPoolSize, lockTimeout int } // NewCredentials fills credentials stusct from connection string func NewCredentials(connStr string) *credentials { parts := strings.Split(connStr, ";") crd := &credentials{maxPoolSize: 100} for _, part := range parts { kv := strings.SplitN(part, "=", 2) if len(kv) == 2 { key := strings.ToLower(strings.Trim(kv[0], " ")) value := kv[1] switch key { case "server", "host": crd.host = value case "database": crd.database = value case "user id", "user_id", "user": crd.user = value case "password", "pwd": crd.pwd = value case "failover partner", "failover_partner", "mirror", "mirror_host", "mirror host": crd.mirrorHost = value case "max pool size", "max_pool_size": if i, err := strconv.Atoi(value); err == nil { crd.maxPoolSize = i } case "compatibility_mode", "compatibility mode", "compatibility": crd.compatibility = strings.ToLower(value) case "lock timeout", "lock_timeout": if i, err := strconv.Atoi(value); err == nil { crd.lockTimeout = i } } } } return crd }
Rails.application.routes.draw do scope module: :web do root 'tasks#index' resources :tasks, only: [:index] namespace :dashboard do root 'tasks#index', as: :root resources :tasks do member do get :download_attachment put :change_state end end end get 'sign_in' => 'sessions#new', as: :new_user_sign_in post 'sign_in' => 'sessions#create', as: :user_sign_in delete 'sign_out' => 'sessions#destroy', as: :user_sign_out namespace :admin do end end end
<?php /** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Framework\App\Test\Unit\ResourceConnection; use Magento\Framework\DB\Adapter\DdlCache; class ConnectionFactoryTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ protected $objectManager; /** * @var \Magento\Framework\App\ResourceConnection\ConnectionFactory */ protected $model; /** * @var \Magento\Framework\ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject */ protected $objectManagerMock; protected function setUp() { $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->objectManagerMock = $this->getMockBuilder('Magento\Framework\ObjectManagerInterface') ->disableOriginalConstructor() ->getMock(); $this->model = $this->objectManager->getObject( 'Magento\Framework\App\ResourceConnection\ConnectionFactory', ['objectManager' => $this->objectManagerMock] ); } public function testCreate() { $cacheAdapterMock = $this->getMockBuilder('Magento\Framework\Cache\FrontendInterface') ->disableOriginalConstructor() ->getMock(); $loggerMock = $this->getMockBuilder('Magento\Framework\DB\LoggerInterface') ->disableOriginalConstructor() ->getMock(); $adapterClass = 'Magento\Framework\App\ResourceConnection\ConnectionAdapterInterface'; $connectionAdapterMock = $this->getMockBuilder($adapterClass) ->disableOriginalConstructor() ->getMock(); $connectionMock = $this->getMockBuilder('Magento\Framework\DB\Adapter\AdapterInterface') ->disableOriginalConstructor() ->getMock(); $connectionMock->expects($this->once()) ->method('setCacheAdapter') ->with($cacheAdapterMock) ->willReturnSelf(); $connectionAdapterMock->expects($this->once()) ->method('getConnection') ->with($loggerMock) ->will($this->returnValue($connectionMock)); $this->objectManagerMock->expects($this->once()) ->method('create') ->with('Magento\Framework\App\ResourceConnection\ConnectionAdapterInterface') ->will($this->returnValue($connectionAdapterMock)); $poolMock = $this->getMockBuilder('Magento\Framework\App\Cache\Type\FrontendPool') ->disableOriginalConstructor() ->getMock(); $poolMock->expects($this->once()) ->method('get') ->with(DdlCache::TYPE_IDENTIFIER) ->will($this->returnValue($cacheAdapterMock)); $this->objectManagerMock->expects($this->any()) ->method('get') ->will($this->returnValueMap( [ ['Magento\Framework\DB\LoggerInterface', $loggerMock], ['Magento\Framework\App\Cache\Type\FrontendPool', $poolMock], ] )); $this->assertSame($connectionMock, $this->model->create(['active' => true])); } }
import classNames from 'clsx' import type * as React from 'react' import Select from '../../../../../core/components/baseItems/Select' import classes from './styles.module.css' interface Props extends React.ComponentProps<typeof Select> { choices: Array<string> } export default function SelectString({ choices, className, ...restProps }: Props) { return ( <Select className={classNames(classes.main, className)} {...restProps}> {choices.map((optionChoice, optionChoiceIndex) => { return ( <option key={optionChoiceIndex} value={optionChoiceIndex}> {optionChoice} </option> ) })} </Select> ) }
package parser import ( "fmt" "go/ast" "regexp" "strings" ) var ( re1 = regexp.MustCompile(`^[a-z]`) re2 = regexp.MustCompile(`^[A-Z]+$`) re3 = regexp.MustCompile(`^[A-Z][0-9a-z_]`) re4 = regexp.MustCompile(`^([A-Z]+)[A-Z][0-9a-z_]`) ) // IsExported determines whether or not a given name is exported. func IsExported(name string) bool { first := name[0:1] return first == strings.ToUpper(first) } // InferName infers an identifier name from a type expression. func InferName(expr ast.Expr) string { switch v := expr.(type) { case *ast.ArrayType: return InferName(v.Elt) + "Vals" case *ast.MapType: return InferName(v.Key) + strings.Title(InferName(v.Value)) + "Map" case *ast.ChanType: return InferName(v.Value) + "Ch" case *ast.StructType: return "structV" case *ast.InterfaceType: return "interfaceV" } var lastName string ast.Inspect(expr, func(n ast.Node) bool { if id, ok := n.(*ast.Ident); ok { lastName = id.Name } return true }) return lastName } // ConvertToUnexported converts an exported identifier to an unexported one. func ConvertToUnexported(name string) string { switch { // Unexported (e.g. client --> client) case re1.MatchString(name): return name // All in upper letters (e.g. ID --> id) case re2.MatchString(name): return strings.ToLower(name) // Starts with Title case (e.g. Request --> request) case re3.MatchString(name): return strings.ToLower(name[0:1]) + name[1:] // Starts with all upper letters followed by a Title case (e.g. HTTPRequest --> httpRequest) case re4.MatchString(name): m := re4.FindStringSubmatch(name) if len(m) == 2 { l := len(m[1]) return strings.ToLower(name[0:l]) + name[l:] } } panic(fmt.Sprintf("ConvertToUnexported: unexpected identifer: %s", name)) }
var FS = require("fs"); var Path = require("path"); var expect = require("chai").expect; var Parser = require("../lib/jsg.js"); var Schema = require("../lib/json-grammar.js"); var Testdir = Path.relative("", __dirname); describe ("", function () { [["ShExJ.jsg", "ShExJ_all.json", true], ["ShExJ.jsg", "empty.json", true], ["ShExJ.jsg", "bad-noType.json", "type"], ["ShExJ.jsg", "bad-wrongType.json", false], ["ShExJ.jsg", "bad-unknowProperty.json", "unknownProperty"], ["ShExJ.jsg", "ShExJ_ShapeAnd0.json", false], ["ShExJ.jsg", "ShExJ_ShapeAnd1.json", false], ["ShExJ.jsg", "ShExJ_ShapeAnd2.json", true], ["ShExJ.jsg", "ShExJ_ShapeAnd3.json", true], ["WikidataUpdate.jsg", "WikidataUpdate-Q20729.json", true] ].forEach(function (t) { var schema = Path.join(Testdir, t[0]); var data = Path.join(Testdir, t[1]); var boolResult = t[2] === true ? "pass" : "fail"; var errMatch = t[2] !== true && t[2] !== false ? t[2] : ""; var result = `${boolResult}` + (errMatch.length ? ` with an error on "${errMatch}"` : ""); var p, s, errors; it(`JSG should correctly parse schema '${schema}'.` , function () { p = Parser.parse(FS.readFileSync(schema, "utf8")); }); // console.log(JSON.stringify(p, null, 2)); it(`JSG should construct a schema from '${schema}'.` , function () { s = Schema(p); }); // console.log(s.htmlSerializer().serialize()); it(`Validating '${data}' against '${schema}' should ${result}.` , function () { try { errors = s.validator().validate(JSON.parse(FS.readFileSync(data, "utf8"))); } catch (e) { expect(e).to.equal(""); errors = null; } // console.log("errors:", errors); if (errors !== null) { expect(errors.length === 0).to.equal(boolResult === "pass"); if (boolResult === "fail" && errMatch.length !== 0 && errors.length !== 0) expect(errors[0].attribute).to.equal(errMatch); } }); }); });
--- layout: post title:Esto es la caña y va ser la po*** --- Este es seguro al 0.0000000000012% el mejor blog jamas visto en github ![_config.yml]({{ site.baseurl }}/images/vanidoso.jpg) Y aun puede mejorar mucho mas, estoy va a ser increible.
# frozen_string_literal: true require 'kruger/version' require 'httparty' require 'kruger/client' module Kruger class Error < StandardError; end end