text
stringlengths
27
775k
package com.avito.k8s import com.avito.android.Result import com.avito.k8s.model.KubePod import io.fabric8.kubernetes.api.model.apps.Deployment public interface KubernetesApi { public val namespace: String public suspend fun deletePod(podName: String): Boolean public suspend fun getPodLogs(podName: String): String public suspend fun getPodDescription(podName: String): String public suspend fun deleteDeployment(deploymentName: String) public suspend fun createDeployment(deployment: Deployment) public suspend fun getPods(deploymentName: String): Result<List<KubePod>> }
--- layout: blog title: Accelerating the journey to 1.0 author: nick description: Version 1.0 is coming. Soon. --- Our [roadmap to version 1.0](/blog/2017/07/17/roadmap-to-1-dot-0) was published in July 2017. It described a set of themes we wanted to address within the project, along with the functional items we decided were necessary to get there. Since then we've made gradual progress through the roadmap with three milestone releases containing many of its features. But there are still a number of features outstanding and at the current course and speed, it would be another 6 months to get them done. Having shipped the 0.20 release with the runtime/editor split work complete, we've been discussing how we can get to 1.0 sooner. We've been challenging the assumptions that underpinned the roadmap to see if they still held true. The key realisation is that 1.0 is not the end of the project. It is just another release, albeit one that rightly signifies the maturity of the project. The main concept with the 1.0 roadmap was to get to a point of functional 'completeness' and API stability. ### Functional 'completeness' This means we've addressed the major gaps of functionality that users have fed back to us. This is focussed on the larger items - pieces that have to be addressed in the core runtime, rather than as incremental enhancements to the existing nodes. Projects (0.18), Persistable Context (0.19) and Subflow Instance Properties (0.20) all fall into this criteria. Each of those addresses very specific requirements and greatly enhance what users can build with Node-RED. ### API Stability Whenever we add new features to the runtime, they introduce new APIs and extension points. As more users look to integrate Node-RED with their existing applications, or to customise it for their own needs, there is a real need to have a stable API. The Runtime/Editor split (0.20) work was the major item here - it has exposed more of the internal components of Node-RED with APIs that can be reused. There's more to be done to properly document those APIs and provide more concrete examples of how they can be used, but the technical work has been done. ### What's left? There are three items from the original roadmap that have not yet been delivered: - Library Redesign - an overhaul of the built-in library experience; one of the oldest bits of the Node-RED user experience that has not had much attention. - Pluggable Message Routing - the ability to plug custom code into how messages are passed between nodes. - New Message API - an update to how nodes handle messages that will enable the runtime to track better what nodes are doing and enable features such as automatically timing out a node. Work has started to various degrees on all three, from high-level design work to actual code contributions. But they all have more work to be done. There are also a number of threads of activity on items that didn't feature in the original roadmap, including: - Subflows Properties UI - allow a subflow to define its own custom UI to set its instance properties - Integrated Flow Testing - being able to define test cases for your flows in the editor and have a test-runner that can be used to validate them - Flow Linter - a command-line tool that can be used to validate a flow based on a set of rules about what a flow should and shouldn't do The risk we have, with all of this activity going on, is that we keep finding 'one more thing' to do before getting to 1.0. Each new item brings a risk of destabilising what we have and adding more time into the plan. ### Changing the plan With all of this in mind, we're going to do some reprioritisation to ensure we're focussed only on what is absolutely necessary for 1.0. Here's what that means to the remaining roadmap features: #### Library Redesign This will provide a much needed cosmetic improvement to how users interact with the library in the editor, but won't introduce any new capabilities. The underlying APIs will largely remain the same. We will not add the ability to plug-in other library sources in the 1.0 release, but the UI changes will keep that in mind for the future. #### Pluggable Message Routing This feature is no longer in the plan for 1.0. By itself, it doesn't add any value to users. The real value comes with the things that can then be plugged in - such as an interactive flow debugger. Rather than rush through a design for this item it makes sense for it to be done after 1.0, when we can also work on some concrete uses for it in parallel #### New Messaging API We have had a design for this agreed for some time and there's also a pull-request that implements that design sat waiting. But in the last couple of weeks we've identified some concerns that the new API is too big of a change for the value it would bring. With 1900+ node modules published, we need to be careful over any change we introduce in this area. An alternative design is being discussed which is a much more modest change that provides most of the functionality needed. #### Non-functional Changes The 1.0 release is an opportunity to make a splash around the project. That will bring new users to the community so we need to make sure we have everything in place to introduce them to Node-RED and help them get started. So alongside the technical work for 1.0, we also want to give the website a clean up, review our documentation and get more content into the cookbook. If you're looking for ways to contribute to the project, but not sure about jumping into the code, there's plenty to help with in this area. ### When is 1.0? The intention is for the *next* milestone release of Node-RED to be version 1.0. The target is to have the first 1.0-beta release in mid-May with the final release available in early June. ### And then? As we said at the start, version 1.0 is not the end of the project - its the next step forward in the project's growth. Alongside the release we'll have a clear roadmap of the ongoing work to take us to the next milestone and beyond. We'll also have the results of our Community Survey to feed back into the plan - if you haven't completed the survey yet, [please do](https://tiny.cc/NodeRED2019Survey)!
#! /bin/bash set -o pipefail set -o nounset set -o errexit export PATH=$PATH:. BASEDIR="$HOME/basedir" JDBC_HOST=127.0.0.1 JDBC_PORT=5432 JDBC_USERNAME=_owner JDBC_PASSWD=welcome JDBC_NAME=_database envdir $BASEDIR/conf/env/test/test \ pg_select_now \ "${JDBC_HOST}" \ "${JDBC_PORT}" \ "${JDBC_USERNAME}" \ "${JDBC_PASSWD}" \ "${JDBC_NAME}" \ | egrep --line-buffered --max-count=1 "40" echo SUCCESS
# -*- coding: UTF-8 -*- from django.db import models from apps.seguridad.models import Usuario, MotivoBloqueo from apps.seguridad.audit import audit @audit class BloqueoLog(models.Model): usuario = models.ForeignKey(Usuario) motivo = models.ForeignKey(MotivoBloqueo) fecha = models.DateField() class Meta: app_label = 'seguridad' db_table = 'seguridad_bloqueo_log'
(in-package #:sdl2) (defvar *user-event-types* (make-hash-table)) (defvar *user-event-codes* (make-hash-table)) (defvar *user-events* (make-hash-table)) (defvar *user-event-id* (c-let ((new-atomic sdl2-ffi:sdl-atomic-t)) (setf (new-atomic :value) 0) new-atomic)) (defvar *event-loop* nil) (defun new-event (&optional (event-type :firstevent)) (c-let ((event sdl2-ffi:sdl-event)) (setf (event :type) (get-event-code event-type)) event)) (defun free-event (event) (foreign-free (ptr event)) (invalidate event)) (defun register-user-event-type (user-event-type) "Register a new sdl event-type if it doesn't already exist" (when (not (keywordp user-event-type)) (error "Event types must be given as keywords")) (multiple-value-bind (event-type-code event-type-found) (gethash user-event-type *user-event-codes*) (if event-type-found event-type-code (let ((new-event-code (sdl2-ffi.functions::sdl-register-events 1))) (if (not (= new-event-code 4294967295)) (progn (setf (gethash user-event-type *user-event-codes*) new-event-code) (setf (gethash new-event-code *user-event-types*) user-event-type) new-event-code) (error (format nil "Failed to register new user-event type: ~a" user-event-type))))))) (defmacro with-sdl-event ((event &optional (event-type :firstevent)) &body body) "Allocate and automatically free an sdl event struct." `(c-let ((,event sdl2-ffi:sdl-event :from (new-event ,event-type))) (unwind-protect (progn ,@body) (free-event ,event)))) (defun add-user-data (user-data) (let* ((event-id (sdl-atomic-add *user-event-id* 1)) (id-in-use (nth-value 1 (gethash event-id *user-events*)))) (when id-in-use (error "Event ID already in use")) (setf (gethash event-id *user-events*) user-data) event-id)) (defun free-user-data (event-id) (remhash event-id *user-events*)) (defun get-user-data (event-id) "Returns the user-data attached to an event-id and if the event-id was found" (gethash event-id *user-events*)) (defun get-event-code (event-type) (multiple-value-bind (user-event-code is-user-event) (gethash event-type *user-event-codes*) (cond (is-user-event user-event-code) ((eq :lisp-message event-type) *lisp-message-event*) (t (enum-value 'sdl2-ffi:sdl-event-type event-type))))) (defun get-event-type (event) (c-let ((event sdl2-ffi:sdl-event :from event)) (multiple-value-bind (user-event-type is-user-event) (gethash (event :type) *user-event-types*) (cond (is-user-event user-event-type) ((eq (event :type) *lisp-message-event*) :lisp-message) (t (or (enum-key 'sdl2-ffi:sdl-event-type (event :type)) (event :type))))))) (defun user-event-type-p (event-type) (nth-value 1 (gethash event-type *user-event-codes*))) (defun pump-events () (sdl-pump-events)) (defun push-event (event) "Allocates a new sdl event struct of the specified type and pushes it into the queue." (etypecase event (symbol (with-sdl-event (ev event) (setf (ev :type) (get-event-code event)) (check-rc (sdl-push-event ev)))) (sdl2-ffi:sdl-event (check-rc (sdl-push-event event))) (sdl2-ffi:sdl-user-event (check-rc (sdl-push-event event))))) (defun push-user-event (user-event &optional user-data) "Allocates a new user-defined sdl event struct of the specified type and pushes it into the queue. Stores the optional user-data in sdl2::*user-events*" (if (user-event-type-p user-event) (with-sdl-event (event user-event) (let ((event-id (add-user-data user-data))) (setf (event :user :code) event-id) (push-event event))) (error "Not a known user-event type"))) (defun push-quit-event () (push-event :quit)) (defun next-event (event &optional (method :poll) timeout) "Method can be either :poll, :wait. If :wait is used, `TIMEOUT` may be specified." (case method (:poll (sdl-poll-event event)) (:wait (if timeout (sdl-wait-event-timeout event timeout) (sdl-wait-event event))) (:wait-with-timeout (sdl-wait-event-timeout event (or timeout 0))) (otherwise (error "Event method must be :poll or :wait")))) (defun expand-idle-handler (event-handlers) (remove nil (mapcar #'(lambda (handler) (cond ((eq (first handler) :idle) `(progn ,@(rest (rest handler)))))) event-handlers))) (defun expand-quit-handler (sdl-event forms quit) (declare (ignore sdl-event)) `(:quit (setf ,quit (funcall #'(lambda () ,@forms))))) (defparameter *event-type-to-accessor* '((:controlleraxismotion . :caxis) (:controllerbuttondown . :cbutton) (:controllerbuttonup . :cbutton) (:controllerdeviceadded . :cdevice) (:controllerdeviceremapped . :cdevice) (:controllerdeviceremoved . :cdevice) (:dollargesture . :dgesture) (:dropfile . :drop) (:fingermotion . :tfinger) (:fingerdown . :tfinger) (:fingerup . :tfinger) (:joyaxismotion . :jaxis) (:joyballmotion . :jball) (:joybuttondown . :jbutton) (:joybuttonup . :jbutton) (:joydeviceadded . :jdevice) (:joydeviceremoved . :jdevice) (:joyhatmotion . :jhat) (:keydown . :key) (:keyup . :key) (:mousebuttondown . :button) (:mousebuttonup . :button) (:mousemotion . :motion) (:mousewheel . :wheel) (:multigesture . :mgesture) (:syswmevent . :syswm) (:textediting . :edit) (:textinput . :text) (:userevent . :user) (:lisp-message . :user) (:windowevent . :window))) (defun unpack-event-params (event-var event-type params) (mapcar (lambda (param) (let ((keyword (first param)) (binding (second param)) (ref (or (cdr (assoc event-type *event-type-to-accessor*)) :user))) (if (eql keyword :user-data) `(,binding (get-user-data (c-ref ,event-var sdl2-ffi:sdl-event ,ref :code))) `(,binding (c-ref ,event-var sdl2-ffi:sdl-event ,ref ,keyword))))) params)) (defun expand-handler (sdl-event event-type params forms) (let ((parameter-pairs nil)) (do ((keyword params (if (cdr keyword) (cddr keyword) nil))) ((null keyword)) (push (list (first keyword) (second keyword)) parameter-pairs)) `(,event-type (let (,@(unpack-event-params sdl-event event-type (nreverse parameter-pairs))) ,@forms)))) ;; TODO you should be able to specify a target framerate (defmacro with-event-loop ((&key background (method :poll) (timeout nil) recursive) &body event-handlers) (let ((quit (gensym "QUIT-")) (sdl-event (gensym "SDL-EVENT-")) (sdl-event-type (gensym "SDL-EVENT-TYPE")) (sdl-event-id (gensym "SDL-EVENT-ID")) (idle-func (gensym "IDLE-FUNC-")) (rc (gensym "RC-"))) `(when (or ,recursive (not *event-loop*)) (setf *event-loop* t) (in-main-thread (:background ,background) (let ((,quit nil) (,idle-func nil)) (unwind-protect (with-sdl-event (,sdl-event) (setf ,idle-func #'(lambda () ,@(expand-idle-handler event-handlers))) (progn ,@(cddr (find :initialize event-handlers :key #'first))) (loop :until ,quit :do (loop :as ,rc = (next-event ,sdl-event ,method ,timeout) ,@(if (eq :poll method) `(:until (= 0 ,rc)) `(:until ,quit)) :do (let* ((,sdl-event-type (get-event-type ,sdl-event)) (,sdl-event-id (and (user-event-type-p ,sdl-event-type) (,sdl-event :user :code)))) (case ,sdl-event-type (:lisp-message () (get-and-handle-messages)) ,@(loop :for (type params . forms) :in event-handlers :collect (if (eq type :quit) (expand-quit-handler sdl-event forms quit) (expand-handler sdl-event type params forms)) :into results :finally (return (remove nil results)))) (when (and ,sdl-event-id (not (eq ,sdl-event-type :lisp-message))) (free-user-data ,sdl-event-id)))) (unless ,quit (funcall ,idle-func)))) (setf *event-loop* nil)))))))
package uk.gov.hmcts.reform.bulkscanprocessor.model.out; import com.fasterxml.jackson.annotation.JsonProperty; public class NonScannableItemResponse { @JsonProperty("document_control_number") public final String documentControlNumber; @JsonProperty("item_type") public final String itemType; public NonScannableItemResponse( @JsonProperty("document_control_number") String documentControlNumber, @JsonProperty("item_type") String itemType ) { this.documentControlNumber = documentControlNumber; this.itemType = itemType; } @Override public String toString() { return "NonScannableItemResponse{" + "documentControlNumber='" + documentControlNumber + '\'' + ", itemType='" + itemType + '\'' + '}'; } }
<?php use Simples\Error\SimplesRunTimeError; use Simples\Kernel\App; if (!function_exists('server')) { /** * @param string $index * @return mixed */ function server(string $index) { return filter(INPUT_SERVER, $index); } } if (!function_exists('post')) { /** * @param string $index * @return mixed */ function post(string $index) { return filter(INPUT_POST, $index); } } if (!function_exists('get')) { /** * @param string $index * @return mixed */ function get(string $index) { return filter(INPUT_GET, $index); } } if (!function_exists('filter')) { /** * @param int $source * @param string $index * @return mixed */ function filter(int $source, string $index) { return filter_input($source, $index); } } if (!function_exists('env')) { /** * @param string $property * @param mixed $default (null) * @return string */ function env($property, $default = null) { $filename = path(true, '.env'); if (file_exists($filename) && is_file($filename)) { $properties = parse_ini_file($filename); if (is_array($properties)) { return off($properties, $property); } } return $default; } } if (!function_exists('path')) { /** * @param string $root * @return string */ function path($root) { $args = func_get_args(); $peaces = []; if (is_bool($root)) { array_shift($args); if ($root) { $peaces = [root()]; } } $path = array_merge($peaces, $args); return implode(DIRECTORY_SEPARATOR, $path); } } if (!function_exists('root')) { /** * @return mixed|string */ function root() { $dir = \Simples\Kernel\App::options('root'); if (!$dir) { $dir = dirname(__DIR__, 4); } return $dir; } } if (!function_exists('storage')) { /** * @param string $path * @return string */ function storage($path) { return path(true, config('app.storage.root'), $path); } } if (!function_exists('resources')) { /** * @param string $path * @return string */ function resources($path) { return path(true, config('app.resources.root'), $path); } } if (!function_exists('out')) { /** * @param mixed $value */ function out($value) { print parse($value); } } if (!function_exists('parse')) { /** * @param mixed $value * @return string */ function parse($value): string { switch (gettype($value)) { case TYPE_BOOLEAN: return $value ? 'true' : 'false'; break; case TYPE_INTEGER: case TYPE_FLOAT: case TYPE_STRING: return trim($value); break; case TYPE_ARRAY: case TYPE_OBJECT: case TYPE_RESOURCE: return json_encode($value); // case TYPE_NULL: // case TYPE_UNKNOWN_TYPE: default: return ''; } } } if (!function_exists('coalesce')) { /** * @param array ...$arguments * @return mixed * @throws SimplesRunTimeError */ function coalesce(...$arguments) { foreach ($arguments as $argument) { if (!is_null($argument)) { return $argument; } } // TODO: use locale throw new SimplesRunTimeError("Can't resolve coalesce options", $arguments); } } if (!function_exists('off')) { /** * @param mixed $value * @param string|int $property (null) * @param mixed $default (null) * * @return mixed */ function off($value, $property = null, $default = null) { if (is_null($property)) { return $default; } if (!$value) { return $default; } if (is_array($value)) { return search($value, $property, $default); } /** @noinspection PhpVariableVariableInspection */ if ($value && is_object($value) && isset($value->$property)) { /** @noinspection PhpVariableVariableInspection */ return $value->$property; } return $default; } } /** * @SuppressWarnings("ExitExpression") */ if (!function_exists('stop')) { /** * @param array ...$arguments */ function stop(...$arguments) { ob_start(); if (count($arguments) === 1) { $arguments = $arguments[0]; } echo json_encode($arguments); $contents = ob_get_contents(); ob_end_clean(); out($contents); die; } } if (!function_exists('config')) { /** * @param string $name * @return mixed */ function config($name) { return \Simples\Kernel\App::config($name); } } if (!function_exists('headerify')) { /** * @param string $name * @return string */ function headerify($name) { return str_replace(' ', '-', ucwords(strtolower(str_replace(['_', '-'], ' ', $name)))); } } if (!function_exists('str_replace_first')) { /** * @param string $from * @param string $to * @param string $subject * @param bool $quote (false) * @return mixed */ function str_replace_first($from, $to, $subject, $quote = false) { if ($quote) { $from = '/' . preg_quote($from, '/') . '/'; } return preg_replace($from, $to, $subject, 1); } } if (!function_exists('guid')) { /** * @param bool $brackets * @return string */ function guid($brackets = false) { mt_srand((double)microtime() * 10000); $char = strtoupper(md5(uniqid(rand(), true))); $hyphen = chr(45); $uuid = substr($char, 0, 8) . $hyphen . substr($char, 8, 4) . $hyphen . substr($char, 12, 4) . $hyphen . substr($char, 16, 4) . $hyphen . substr($char, 20, 12); if ($brackets) { $uuid = chr(123) . $uuid . chr(125); } return $uuid; } } if (!function_exists('is_iterator')) { /** * @param mixed $var * @return bool */ function is_iterator($var) { return (is_array($var) || $var instanceof Traversable); } } if (!function_exists('throw_format')) { /** * @param Throwable $throw * @return string */ function throw_format(Throwable $throw) { return "[{$throw->getMessage()}] ON [{$throw->getFile()}] AT [{$throw->getLine()}]"; } } if (!function_exists('error_format')) { /** * @param Throwable $error * @return array */ function error_format(Throwable $error): array { $trace = App::beautifulTrace($error->getTrace()); return [ 'error' => [ 'fail' => get_class($error), 'details' => $error instanceof SimplesRunTimeError ? $error->getDetails() : [], 'trace' => $trace ] ]; } } if (!function_exists('error_message')) { /** * @param Throwable $error * @return string */ function error_message(Throwable $error): string { $pieces = []; $line = function ($message, $file, $line) { $file = str_replace(dirname(__DIR__, 4), '', $file); return $message . ' on ' . $file . ' in ' . $line; }; $pieces[] = $line($error->getMessage(), $error->getFile(), $error->getLine()); if (method_exists($error, 'getDetails')) { $pieces[] = '~'; $pieces[] = json_encode($error->getDetails(), JSON_PRETTY_PRINT); } if (is_array($error->getTrace())) { $pieces[] = '~'; foreach ($error->getTrace() as $item) { $class = off('class'); $function = $item['function']; $pieces[] = $line("`{$class}::{$function}`", off('file'), off('line')); } } return implode(PHP_EOL, $pieces); } } if (!function_exists('is_last_caller')) { /** * @param string $class * @return bool */ function is_last_caller(string $class): bool { $debug_backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 3); if (!is_array($debug_backtrace)) { return false; } $trace = array_pop($debug_backtrace); if (isset($trace['class']) && $trace['class'] === $class) { return true; } return false; } } if (!function_exists('search')) { /** * @param array $context * @param array|string $path * @param mixed $default (null) * @return mixed|null */ function search(array $context, $path, $default = null) { if (!is_array($path)) { $path = explode('.', $path); } foreach ($path as $piece) { if (!is_array($context) || !array_key_exists($piece, $context)) { return $default; } $context = $context[$piece]; } return $context; } } if (!function_exists('read')) { /** * @param string $prompt * @param string $options * @return string */ function read(string $prompt = '$ ', string $options = ''): string { if ($options) { $prompt = "{$prompt} {$options}\$ "; } $reader = function () use ($prompt) { return readline("{$prompt}"); }; if (PHP_OS === 'WINNT') { $reader = function () use ($prompt) { echo $prompt; return stream_get_line(STDIN, 1024, PHP_EOL); }; } $line = $reader(); readline_add_history($line); return trim($line); } } if (!function_exists('clearpath')) { /** * @param string $path * @return string */ function clearpath(string $path): string { return implode('/', array_filter(explode('/', $path), function ($value) { if (!in_array($value, ['..', '.'])) { return $value; } return null; })); } } if (!function_exists('test')) { /** * @param mixed $output * @param mixed $optional (null) * @return mixed */ function test($output, $optional = null) { if (env('TEST_MODE')) { return $output; } return $optional; } } if (!function_exists('argv')) { /** * @param array $argv * @return array */ function argv(array $argv): array { array_shift($argv); $parameters = []; foreach ($argv as $arg) { $parameter = explode('=', $arg); $value = $parameter[0]; if (count($parameter) === 2) { $parameters[$value] = $parameter[1]; continue; } $parameters[] = $value; } return $parameters; } } if (!function_exists('dasherize')) { /** * @param string $camelCase * @return string */ function dasherize(string $camelCase): string { $args = '$matches'; $code = 'return \'-\' . strtolower($matches[1]);'; $dashes = preg_replace_callback('/([A-Z])/', create_function($args, $code), $camelCase); return substr($dashes, 1); } } if (!function_exists('camelize')) { /** * @param string $dashes * @param bool $first * @return mixed */ function camelize(string $dashes, $first = true): string { $args = '$matches'; $code = 'return strtoupper($matches[1]);'; $camelCase = preg_replace_callback('/-(.)/', create_function($args, $code), $dashes); $case = 'ucfirst'; if (!$first) { $case = 'lcfirst'; } return (string)$case($camelCase); } } if (!function_exists('get_class_short_name')) { /** * Extract the short name of class * Ex.: (Namespace\Class) => Class * @param string $class * @return string */ function get_class_short_name(string $class) { return basename(str_replace('\\', '/', $class)); } } if (!function_exists('error_handler')) { /** * @param $code * @param $message * @param $file * @param $line * @throws ErrorException */ function error_handler($code, $message, $file, $line) { throw new ErrorException($message, $code, 1, $file, $line); } } if (!function_exists('type')) { /** * @param mixed $value * @param string $type * @return bool */ function type($value, string $type) { return gettype($value) === $type; } } /** * @SuppressWarnings("Superglobals") */ if (!function_exists('getallheaders')) { /** * @return array */ function getallheaders() { $headers = []; foreach ($_SERVER as $name => $value) { if (substr($name, 0, 5) == 'HTTP_') { $headers[headerify(substr($name, 5))] = $value; } } return $headers; } } if (!function_exists('runnable')) { /** * @param mixed $reference * @param string $method * @return callable * @throws SimplesRunTimeError */ function runnable($reference, $method = null) { $runnable = [$reference, $method]; if (is_string($reference)) { $runnable = "{$reference}::{$method}"; } if (!is_callable($runnable)) { throw new SimplesRunTimeError("Can't resolve callable to parameters", [ 'reference' => $reference, 'method' => $method, ]); } return $runnable; } } if (!function_exists('concat')) { /** * @return string */ function concat() { return implode(' ', func_get_args()); } }
# Deploying a Conformance Pack Using the AWS Command Line Interface<a name="conformance-pack-cli"></a> You can deploy, view, update, view compliance status, and delete an AWS Config conformance pack using the AWS Command Line Interface \(AWS CLI\)\. To install the AWS CLI on your local machine see, [AWS Config Conforms Amazon S3 bucket\.](https://s3.console.aws.amazon.com/s3/buckets/aws-config-conforms-docs) If necessary, type `aws configure` to configure the AWS CLI to use an AWS Region where AWS Config conformance packs are available\. **Topics** + [Deploy a Conformance Pack](#deploy-a-conformance-pack-cli) + [View a Conformance Pack](#view-a-conformance-pack) + [View Conformance Pack Status](#view-a-conformance-pack-status) + [View Conformance Pack Compliance Status](#view-a-conformance-pack-compliance-status) + [Get Compliance Details for a Specific Conformance Pack](#get-conformance-pack-compliance-details) + [Delete a Conformance Pack](#delete-a-conformance-pack-cli) ## Deploy a Conformance Pack<a name="deploy-a-conformance-pack-cli"></a> 1. Open a command prompt or a terminal window\. 1. Type the following command to deploy a conformance pack named **MyConformancePack1**\. ``` aws configservice put-conformance-pack --conformance-pack-name="MyConformancePack1" --template-s3-uri="s3://AmazonS3bucketname/template name.yaml" --delivery-s3-bucket=AmazonS3bucketname ``` OR You can also upload a YAML template from your local directory\. ``` aws configservice put-conformance-pack --conformance-pack-name="MyConformancePack1" --template-body=template body --delivery-s3-bucket=AmazonS3bucketname ``` 1. Press Enter to run the command\. You should see output similar to the following\. ``` { "conformancePackArn": "arn:aws:config:us-west-2:AccountID:conformance-pack/MyConformancePack1/conformance-pack-ID" } ``` ## View a Conformance Pack<a name="view-a-conformance-pack"></a> 1. Type the following command\. ``` aws configservice describe-conformance-packs ``` OR ``` aws configservice describe-conformance-packs --conformance-pack-name="MyConformancePack1" ``` 1. You should see output similar to the following\. ``` { "conformancePackName": "MyConformancePack1", "conformancePackId": "conformance-pack-ID", "conformancePackArn": "arn:aws:config:us-west-2:AccountID:conformance-pack/MyConformancePack1/conformance-pack-ID", "conformancePackInputParameters": [], "lastUpdateRequestedTime": "Thu Jul 18 16:07:05 PDT 2019" } ``` ## View Conformance Pack Status<a name="view-a-conformance-pack-status"></a> 1. Type the following command\. ``` aws configservice describe-conformance-pack-status --conformance-pack-name="MyConformancePack1" ``` 1. You should see output similar to the following \. ``` { "stackArn": "arn:aws:cloudformation:us-west-2:AccountID:stack/awsconfigconforms-MyConformancePack1-conformance-pack-ID/d4301fe0-a9b1-11e9-994d-025f28dd83ba", "conformancePackName": "MyConformancePack1", "conformancePackId": "conformance-pack-ID", "lastUpdateCompletedTime": "Thu Jul 18 16:15:17 PDT 2019", "conformancePackState": "CREATE_COMPLETE", "conformancePackArn": "arn:aws:config:us-west-2:AccountID:conformance-pack/MyConformancePack1/conformance-pack-ID", "lastUpdateRequestedTime": "Thu Jul 18 16:14:35 PDT 2019" } ``` ## View Conformance Pack Compliance Status<a name="view-a-conformance-pack-compliance-status"></a> 1. Type the following command\. ``` aws configservice describe-conformance-pack-compliance --conformance-pack-name="MyConformancePack1" ``` 1. You should see output similar to the following\. ``` { "conformancePackName": "MyConformancePack1", "conformancePackRuleComplianceList": [ { "configRuleName": "awsconfigconforms-RuleName1-conformance-pack-ID", "complianceType": "NON_COMPLIANT" }, { "configRuleName": "awsconfigconforms-RuleName2-conformance-pack-ID", "complianceType": "COMPLIANT" } ] } ``` ## Get Compliance Details for a Specific Conformance Pack<a name="get-conformance-pack-compliance-details"></a> 1. Type the following command\. ``` aws configservice get-conformance-pack-compliance-details --conformance-pack-name="MyConformancePack1" ``` 1. You should see output similar to the following\. ``` { "conformancePackRuleEvaluationResults": [ { "evaluationResultIdentifier": { "orderingTimestamp": "Tue Jul 16 23:07:35 PDT 2019", "evaluationResultQualifier": { "resourceId": "resourceID", "configRuleName": "awsconfigconforms-RuleName1-conformance-pack-ID", "resourceType": "AWS::::Account" } }, "configRuleInvokedTime": "Tue Jul 16 23:07:50 PDT 2019", "resultRecordedTime": "Tue Jul 16 23:07:51 PDT 2019", "complianceType": "NON_COMPLIANT" }, { "evaluationResultIdentifier": { "orderingTimestamp": "Thu Jun 27 15:16:36 PDT 2019", "evaluationResultQualifier": { "resourceId": "resourceID", "configRuleName": "awsconfigconforms-RuleName2-conformance-pack-ID", "resourceType": "AWS::EC2::SecurityGroup" } }, "configRuleInvokedTime": "Thu Jul 11 23:08:06 PDT 2019", "resultRecordedTime": "Thu Jul 11 23:08:06 PDT 2019", "complianceType": "COMPLIANT" } ], "conformancePackName": "MyConformancePack1" } } ``` ## Delete a Conformance Pack<a name="delete-a-conformance-pack-cli"></a> + Type the following command\. ``` aws configservice delete-conformance-pack --conformance-pack-name MyConformancePack1 ``` If successful, the command runs with no additional output\.
require 'postageapp' if (defined?(ActionMailer)) require 'postageapp/mailer' end module PostageApp::Rails def self.initialize PostageApp.configure do |config| if (defined?(::Rails.version)) config.framework = "Rails #{::Rails.version}" end if (defined?(::Rails.root)) config.project_root = ::Rails.root end if (defined?(::Rails.env)) config.environment = ::Rails.env end end end end PostageApp::Rails.initialize
import 'package:animated_card/animated_card.dart'; import 'package:flutter/material.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:payflow/modules/delete_boleto/delete_boleto_controller.dart'; import 'package:payflow/shared/auth/auth_controller.dart'; import 'package:payflow/shared/models/boleto_model.dart'; import 'package:payflow/shared/themes/app_text_styles.dart'; class BoletoTileWidget extends StatefulWidget { final BoletoModel data; BoletoTileWidget({ Key? key, required this.data, }) : super(key: key); @override _BoletoTileWidgetState createState() => _BoletoTileWidgetState(); } class _BoletoTileWidgetState extends State<BoletoTileWidget> { final controller = DeleteBoletoController(); final authController = AuthController(); @override Widget build(BuildContext context) { return AnimatedCard( direction: AnimatedCardDirection.right, child: Slidable( actionPane: SlidableScrollActionPane(), actions: [ IconSlideAction( caption: 'Fechar', color: Colors.black45, icon: Icons.close, onTap: () {}, ), IconSlideAction( caption: 'Deletar', color: Colors.red, icon: Icons.delete, onTap: () async { await showDialog( context: context, builder: (_) => AlertDialog( title: Text( "Deseja realmente excluir o boleto - ${widget.data.name}?"), content: Text("${widget.data.name}"), actions: [ TextButton( child: Text( "Não", style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), onPressed: () { Navigator.pop(context); }, ), TextButton( child: Text( "Sim", style: TextStyle( color: Colors.white, fontSize: 20, ), ), onPressed: () async { await controller.delBoleto( widget.data.name, widget.data.dueDate, widget.data.value, widget.data.barcode); //Navigator.pop(context); authController.currentUser(context); }, ), ], elevation: 24.0, backgroundColor: Colors.orange, ), ); setState(() {}); }, ), ], actionExtentRatio: 0.25, child: ListTile( contentPadding: EdgeInsets.symmetric(horizontal: 8.0), title: Text( widget.data.name!, style: TextStyles.titleListTile, ), subtitle: Text( "Vence em ${widget.data.dueDate}", style: TextStyles.captionBody, ), trailing: Text.rich( TextSpan( text: "R\$", style: TextStyles.trailingRegular, children: [ TextSpan( text: "${widget.data.value!.toStringAsFixed(2)}", style: TextStyles.trailingBold, ) ], ), ), ), ), ); } }
package pers.hyy.butian.conf import org.springframework.context.annotation.Configuration import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration @Configuration class SpringMongoConfig: AbstractMongoClientConfiguration() { @Override override fun autoIndexCreation(): Boolean { return true; } @Override override fun getDatabaseName(): String { return "butiansurvey"; } }
import 'package:flutter/material.dart'; import 'package:flutter_jsonform/src/extensions/text_style_attribute.dart'; extension FromJson on InputDecoration { InputDecoration fromJson(dynamic jsonDefinition) { Map<String, dynamic> json = jsonDefinition; var style = new InputDecoration(); if (json.containsKey('label')) { style = style.copyWith(labelText: json['label'].toString()); } if (json.containsKey('label_style')) { style = style.copyWith( labelStyle: TextStyle(inherit: true).fromJson(json['label_style'])); } if (json.containsKey('content_padding')) { style = style.copyWith( contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 10)); } return style; } }
class Order class Item < ActiveRecord::Base belongs_to :order belongs_to :product has_one :product_detail, through: :product end end
<div class="flex p-20"> <div class="flex-1"></div> <div class="flex-1 bg-indigo-300 p-5 rounded"> <form wire:submit.prevent="sendLink"> <div class="mb-4"> <label class="font-bold block mb-1" for="email">Email</label> <input id="email" class="block w-full rounded border-solid border-2 border-white" type="email" name="email" :value="old('email')" wire:model.defer="email"/> @error('email') <div class="font-bold text-white mt-2 bg-red-500 p-1 pl-3 pr-3 rounded">{{ $message }}</div> @enderror </div> <div class="mb-4"> <button wire:loading.attr="disabled" class="float-left font-bold bg-white py-1 pb-1 pr-4 pl-4 rounded"> <span wire:loading.remove>Email Password Reset Link</span> <span wire:loading> @svg('refresh', 'animate-spin fill-current w-4 h-4 mr-1 ml-0 inline') </span> </button> </div> </form> </div> <div class="flex-1"></div> </div>
/// <reference path="../typings/browser.d.ts" /> /// <reference path="./app.config.ts" /> /// <reference path="./app.constant.ts" /> /// <reference path="./app.run.ts"/> import * as myModule from './my-module/my.module'; import * as appConstants from './app.constant'; import * as appRun from './app.run'; import * as appConfig from './app.config'; export namespace app { export let name = 'app'; let angularModule = angular.module(name, ['ui.router', myModule.my.name]); angularModule.constant('config', appConstants.app.Constants.MyAppConstants); angularModule.run(appRun.app.Run); angularModule.config(appConfig.app.MyAppConfig); }
#!/bin/bash # Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Fast fail the script on failures. set -e pushd packages/devtools echo `pwd` # Print out the Dart version in use. dart --version # Add globally activated packages to the path. export PATH=$PATH:~/.pub-cache/bin # We should be using dart from /Users/travis/dart-sdk/bin/dart. echo "which dart: " `which dart` if [ "$BOT" = "main" ]; then # Provision our packages. pub get pub global activate webdev # Verify that dartfmt has been run. echo "Checking dartfmt..." if [[ $(dartfmt -n --set-exit-if-changed bin/ lib/ test/ web/) ]]; then echo "Failed dartfmt check: run dartfmt -w bin/ lib/ test/ web/" dartfmt -n --set-exit-if-changed bin/ lib/ test/ web/ exit 1 fi # Make sure the app versions are in sync. dart tool/version_check.dart # Analyze the source. pub global activate tuneup && tuneup check # Ensure we can build the app. pub run build_runner build -o web:build --release elif [ "$BOT" = "test_ddc" ]; then # Provision our packages. pub get pub global activate webdev pub run test --reporter expanded --exclude-tags useFlutterSdk pub run build_runner test -- --reporter expanded --exclude-tags useFlutterSdk --platform chrome-no-sandbox elif [ "$BOT" = "test_dart2js" ]; then # Provision our packages. pub get pub global activate webdev WEBDEV_RELEASE=true pub run --enable-asserts test --reporter expanded --exclude-tags useFlutterSdk pub run build_runner test -r -- --reporter expanded --exclude-tags useFlutterSdk --platform chrome-no-sandbox elif [ "$BOT" = "flutter_sdk_tests" ]; then # Get Flutter. if [ "$TRAVIS_DART_VERSION" = "stable" ]; then echo "Cloning stable Flutter branch" git clone https://github.com/flutter/flutter.git --branch stable ../flutter # Set the suffix so we use stable goldens. export DART_VM_OPTIONS="-DGOLDENS_SUFFIX=_stable" else echo "Cloning master Flutter branch" git clone https://github.com/flutter/flutter.git ../flutter fi cd .. export PATH=`pwd`/flutter/bin:`pwd`/flutter/bin/cache/dart-sdk/bin:$PATH flutter config --no-analytics flutter doctor # Put the Flutter version into a variable. # First awk extracts "Flutter x.y.z-pre.a": # -F '•' uses the bullet as field separator # NR==1 says only take the first record (line) # { print $1} prints just the first field # Second awk splits on space (default) and takes the second field (the version) export FLUTTER_VERSION=$(flutter --version | awk -F '•' 'NR==1{print $1}' | awk '{print $2}') echo "Flutter version is '$FLUTTER_VERSION'" # We should be using dart from ../flutter/bin/cache/dart-sdk/bin/dart. echo "which dart: " `which dart` # Return to the devtools directory. cd devtools # Provision our packages using Flutter's version of Dart. pub get pub global activate webdev # Run tests that require the Flutter SDK. pub run test -j1 --reporter expanded --tags useFlutterSdk else echo "unknown bot configuration" exit 1 fi popd
from YOUR_API_KEY import key import requests import logging import sys import os """ API request to the Google Maps API Imputs: API key """ # logger = logging.getLogger(__name__) # logger.setLevel(logging.DEBUG) # formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s') # file_handler = logging.FileHandler('gmap_api.log') # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) def get_elevations(avglat,avglon): locations = str() for i, row in enumerate(zip(avglat,avglon)): locations += str(avglat[i]) + ',' + str(avglon[i]) if i < len(avglon) - 1: locations += ' | ' search_url = 'https://maps.googleapis.com/maps/api/elevation/json?' search_payload = {"key": os.environ.get('GOOGLE_API_KEY'), 'locations':locations} search_req = requests.get(search_url, params=search_payload) search_json = search_req.json() # logger.debug(search_json) results = search_json['results'] elevations = [i['elevation'] for i in results] # if not elevations: # sys.exit(1) return elevations if __name__ == '__main__': print(get_elevations('30.2,-98.8'))
augment class Iterable { # N.B.: methods defined in src/builtins/Iterable.pir # .item multi method Numeric() { $.elems.Int } multi method Int() { $.elems.Int } multi method Num() { $.elems.Num } multi method Str() { $.list.Str } multi method elems() { $.list.elems } multi method fmt($format = '%s', $separator = ' ') { $.list.fmt($format, $separator); } multi method list() { $.iterator.list } }
import { Bytes } from '@cryptoeconomicslab/primitives' import { Decision } from '../types' import { DeciderManagerInterface } from '../DeciderManager' export interface Decider { decide( manager: DeciderManagerInterface, inputs: Bytes[], substitutions: { [key: string]: Bytes } ): Promise<Decision> }
import type { Size, AttributeCollection } from "./models/"; import "./PinkKoala.css"; export declare type PinkKoalaProps = { drawing: any; drawingProps: AttributeCollection | null; layers: string[]; size: Size; }; export declare const PinkKoala: (props: PinkKoalaProps) => JSX.Element;
package creg package experiment import scala.reflect.macros.blackbox.Context import scala.language.experimental.macros import scala.annotation.StaticAnnotation private[experiment] class defData extends StaticAnnotation { def macroTransform(annottees: Any*): Any = macro defData.impl } private[experiment] object defData { def impl(c: Context)(annottees: c.Tree*): c.Tree = { import c.universe._ annottees match { case Seq(ast @ q"def $name[..$typeParams] = $body") => val code = "\n" + showCode(ast) q"val $name: String = $code" } } }
# TypeScript & NodeJS - [Setup](#setup) - [Testing](#testing) - [Resources](#resources) ## Setup - `npm install typescript @types/node --save-dev` - `tsc --init` ### `tsconfig.json` ```json { "compilerOptions": { "target": "es5", "lib": ["es2015"], "rootDir": "src", "outDir": "dist", "module": "commonjs", "moduleResolution": "node", "strict": true, "declaration": true, "sourceMap": true, "inlineSources": true, "types": ["node", "mocha"] }, "include": ["src/**/*"] } ``` ### `package.json` ```json { "scripts": { "build": "tsc" }, "devDependencies": { "@types/node": "^10.12.11", "typescript": "^3.2.1" } } ``` ### Testing ```json { "scripts": { "test": "mocha dist/**/*.spec.js -R spec --bail" } "devDependencies": { "@types/mocha": "^5.2.5", "mocha": "^5.2.0", } } ``` ## Resources - [TS-Node](https://github.com/TypeStrong/ts-node) - [TS-Node-Dev](https://github.com/whitecolor/ts-node-dev)
package de.loc.input; import com.badlogic.ashley.core.Component; public class ClickableComponent implements Component { public boolean clicked = false; public boolean marked = false; }
using UnityEngine; using System.Collections; public class eatPlayer : MonoBehaviour { public static bool killed = false; private Transform player; public Transform mouth; Animator anim; private Vector3 eatpos; void Start() { player = GameObject.FindGameObjectWithTag("Player").transform; anim = GetComponent<Animator>(); } // Use this for initialization void OnTriggerEnter(Collider col) { print(col.gameObject); if(!killed && col.transform.root.tag == "Player") { eat_player(); } } void Update() { if (killed) { transform.root.position = Vector3.Lerp(transform.root.position, eatpos, Time.deltaTime * 5); Vector3 lookPos = player.position - transform.root.position; lookPos.y = 0; Quaternion rotation = Quaternion.LookRotation(lookPos); transform.root.rotation = Quaternion.Slerp(transform.root.rotation, rotation, Time.deltaTime * 2); Vector3 lookPos2 = mouth.position - player.position; lookPos2.y = 0; Quaternion rotation2 = Quaternion.LookRotation(lookPos2); player.rotation = Quaternion.Slerp(player.rotation, rotation2, Time.deltaTime * 2); //ugly maths here because code not playing nice... but it works Transform pcamera = player.GetComponentInChildren<Camera>().transform; Vector3 lookPos3 = mouth.position - pcamera.position; lookPos3.x = 0; Quaternion rotation3 = Quaternion.LookRotation(lookPos3); Vector3 tmp = rotation3.eulerAngles; tmp.y = 0; tmp.z = 0; tmp.x += 240; rotation3 = Quaternion.Euler(tmp); pcamera.localRotation = Quaternion.Slerp(pcamera.localRotation, rotation3, Time.deltaTime * 2); if (Mathf.Abs(Vector3.Angle(transform.root.forward, player.forward) - 180) <= 4) { anim.SetTrigger("ready"); } } } void eat_player() { player.GetComponent<CharacterController>().enabled = false; player.GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController>().enabled = false; player.GetComponentInChildren<LanternAngle>().drop_lantern(); killed = true; eatpos = player.position + player.transform.forward * 2 / 3f; eatpos.y = player.position.y - 1.22f; anim.SetLayerWeight(1, 0); anim.SetLayerWeight(2, 0); anim.SetLayerWeight(3, 0); anim.SetBool("eatingplayer", true); anim.SetFloat("Movement", 0); DemonBehavior.mouthtarget = 1; anim.speed = 1; DemonBehavior.target_speed = 1; transform.root.GetComponent<NavMeshAgent>().enabled = false; } }
# quic-uhip-analytics QUIC project to analyse UHIP data. The program takes spreadsheet of data and analyses the data. This project is made specifically for Queen's University International Centre and their style of data.
package mmorihiro.matchland.controller import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.scenes.scene2d.actions.Actions import com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeIn import com.badlogic.gdx.scenes.scene2d.actions.Actions.fadeOut import com.badlogic.gdx.scenes.scene2d.actions.TemporalAction import com.badlogic.gdx.scenes.scene2d.ui.Label import ktx.actors.plus import ktx.actors.then import ktx.scene2d.Scene2DSkin import mmorihiro.matchland.view.ScoreView import kotlin.run class ScoreController(private val onClear: () -> Unit, level: Int) : Controller { override val view = ScoreView(level).apply { this + tile this + score } fun isClear(value: Int): Boolean = value >= view.target fun percentEffect(value: Int) = view.run { val before = score.text.split("/").first().toInt() val amount = value - before score.setText("$value/${view.target}") Label(if (amount >= 0) "+$amount" else "$amount", Scene2DSkin.defaultSkin, "default-font", Color.WHITE).apply { x = score.x + 5 y = 25f this + (fadeIn(0.4f) then fadeOut(0.4f) then Actions.run { this.remove() }) this@run + this } this + object : TemporalAction(0.4f, Interpolation.smooth) { override fun update(percent: Float) { score.setText("${(before + amount * percent).toInt()}/${view.target}") } } if (isClear(value)) onClear() } }
# dotnet-bluetooth-weight Read the numbers of electronic balance via bluetooth. #How to run 1. git clone https://github.com/souws/dotnet-bluetooth-weight or git clone git@github.com:souws/dotnet-bluetooth-weight.git 2. cd to dotnet-bluetooth-weight\BleBalanceReader\BleBalanceReader 3. dotnet run --project BleBalanceReader.csproj
use super::super::io::Sink; use super::super::iter::Iterator; use super::super::ptr; use super::libc; use super::OSError; pub fn read(fd: i32, buf: *mut u8, count: usize) -> Result<usize, OSError> { let mut length = 0; let mut ptr = buf; while length < count { let size = unsafe { libc::read(fd, ptr, count - length) }; if size < 0 { return libc::get_error(); } if size == 0 { break; } length += size as usize; unsafe { ptr = ptr.offset(size); } } Ok(length) } pub fn write(fd: i32, buf: *const u8, count: usize) -> Result<(), OSError> { let mut written = 0; let mut ptr = buf; while written < count { let size = unsafe { libc::write(fd, ptr, count - written) }; if size < 0 { return libc::get_error(); } written += size as usize; unsafe { ptr = ptr.offset(size); } } Ok(()) } pub struct FileSource { fd: i32, size: isize, offset: isize, capacity: isize, buffer: *mut u8, } impl FileSource { pub const fn new(fd: i32, size: isize, buffer: *mut u8) -> Self { FileSource { fd, size, offset: size, capacity: size, buffer, } } } impl Iterator for FileSource { type Item = u8; fn next(&mut self) -> Option<u8> { if (self.offset == self.size) && (self.size == self.capacity) { self.offset = 0; self.size = read(self.fd, self.buffer, self.capacity as usize).unwrap() as isize; } if self.offset < self.size { let c = unsafe { ptr::read(self.buffer, self.offset) }; self.offset += 1; Some(c) } else { None } } } pub struct FileSink { fd: i32, offset: isize, capacity: isize, buffer: *mut u8, } impl FileSink { pub const fn new(fd: i32, size: isize, buffer: *mut u8) -> Self { FileSink { fd, offset: 0, capacity: size, buffer, } } } impl Sink for FileSink { fn write(&mut self, c: u8) { if self.offset == self.capacity { write(self.fd, self.buffer, self.capacity as usize).unwrap(); self.offset = 0; } unsafe { ptr::write(self.buffer, self.offset, c) }; self.offset += 1; } } impl Drop for FileSink { fn drop(&mut self) { write(self.fd, self.buffer, self.offset as usize).unwrap(); } }
import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:wallpaperplugin/wallpaperplugin.dart'; import 'package:dio/dio.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; void main() => runApp(WallpaperExampleApp()); ///Wallpaper example app showing how to use the wallpaperplugin class WallpaperExampleApp extends StatefulWidget { @override _WallpaperExampleAppState createState() => _WallpaperExampleAppState(); } class _WallpaperExampleAppState extends State<WallpaperExampleApp> { String _wallpaperStatus = 'Initial'; final String _wallpaperImageUrl = 'https://images.pexels.com/photos/2170473/pexels-photo-2170473.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940'; @override void initState() { super.initState(); initPlatformState(); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initPlatformState() async { String wallpaperStatus = 'Unexpected Result'; if (await _checkAndGetPermission() != null) { final String _localFile = await _downloadFileUsingDio(_wallpaperImageUrl, 'test_wallpaper'); // Platform messages may fail, so we use a try/catch PlatformException. try { Wallpaperplugin.setWallpaperWithCrop(localFile: _localFile); wallpaperStatus = 'new Wallpaper set'; } on PlatformException { print('Platform exception'); wallpaperStatus = 'Platform Error Occured'; } } // If the widget was removed from the tree while the asynchronous platform // message was in flight, we want to discard the reply rather than calling // setState to update our non-existent appearance. if (!mounted) return; setState(() { _wallpaperStatus = wallpaperStatus; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Wallpaper Plugin example app'), ), body: Center( child: Text('Wallpaper Status: $_wallpaperStatus\n'), ), ), ); } ///This code helps in downloading a jpeg to local folder Future<String> _downloadFileUsingDio(String url, String _photoId) async { final Dio dio = Dio(); final String dir = await _localPath; final String localFile = '$dir/$_photoId.jpeg'; final File file = File(localFile); if (!file.existsSync()) { try { await dio.download(url, localFile, onReceiveProgress: (int received, int total) { if (total != -1) { print('Photo downloading : ' + (received / total * 100).toStringAsFixed(0) + '%'); } }); return localFile; } on PlatformException catch (error) { print(error); } } return localFile; } ///returns the local path + /wallpapers, this is where the image file is downloaded. Future<String> get _localPath async { final Directory appDocDirectory = await getExternalStorageDirectory(); final Directory directory = await Directory(appDocDirectory.path + '/wallpapers') .create(recursive: true); // The created directory is returned as a Future. return directory.path; } /// This method checks for permission and if not given will request the user for the same. /// It will return true if permission is given, or else will return null static Future<bool> _checkAndGetPermission() async { // final PermissionStatus permission = await PermissionHandler() // .checkPermissionStatus(PermissionGroup.storage); // if (permission != PermissionStatus.granted) { // final Map<PermissionGroup, PermissionStatus> permissions = // await PermissionHandler() // .requestPermissions(<PermissionGroup>[PermissionGroup.storage]); // if (permissions[PermissionGroup.storage] != PermissionStatus.granted) { // return null; // } // } if(await Permission.storage.isGranted){ return await (Permission.storage.request()).isGranted; } return true; } }
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; import { FetchBaseQueryError } from '@reduxjs/toolkit/query'; import { webhooksActions } from '../features/webhooks'; import { Webhook, WebhookRequest, WebhookRequestCoreInfo, WebhookWithDetails } from '../types'; import { webhookRequestActions } from '../features/webhookRequest'; // eslint-disable-next-line import/no-cycle import { RootState } from '../store'; const websocketURL = `${process.env.REACT_APP_WEBSOCKET_ENDPOINT as string}/api/ws`; export const webhookAPI = createApi({ reducerPath: 'webhook', baseQuery: fetchBaseQuery({ baseUrl: '/api/', }), tagTypes: ['Webhook', 'WebhookRequest'], endpoints: (build) => ({ getWebhooks: build.query<string[], void>({ queryFn: (_, { getState }) => { const { webhooks } = getState() as { webhooks: string[] }; return { data: webhooks }; }, providesTags: ['Webhook'], }), createWebhook: build.mutation<Webhook, void>({ queryFn: async (_, api, _extraOptions, fetchWithBQ) => { const createWebhookResult = await fetchWithBQ({ url: `webhook`, method: 'POST', }); if (createWebhookResult.error) throw createWebhookResult.error; const webhook = createWebhookResult.data as Webhook; api.dispatch(webhooksActions.add(webhook.id)); if (createWebhookResult.data) { return { data: webhook, }; } return { error: createWebhookResult as FetchBaseQueryError, }; }, invalidatesTags: ['Webhook'], }), findWebhook: build.query<WebhookWithDetails, { webhookId: string }>({ queryFn: async (params, api, _extraOptions, fetchWithBQ) => { const findWebhookResult = await fetchWithBQ({ url: `webhook/${params.webhookId}`, method: 'GET', }); if (findWebhookResult.error) throw findWebhookResult.error; const webhook = findWebhookResult.data as WebhookWithDetails; if (webhook.requests && webhook.requests.length > 0) { const firstWebhookRequest = webhook.requests[0]; if (!(api.getState() as RootState).webhookRequest) { api.dispatch(webhookRequestActions.set(firstWebhookRequest.id)); } } if (findWebhookResult.data) { return { data: webhook, }; } return { error: findWebhookResult as FetchBaseQueryError, }; }, onCacheEntryAdded: async (params, api) => { // Connecting to websocket for getting requests const ws = new WebSocket(`${websocketURL}/webhook/${params.webhookId}`); await api.cacheDataLoaded; ws.addEventListener('message', (event: MessageEvent<string>) => { try { const webhookRequest = JSON.parse(event.data) as WebhookRequestCoreInfo; api.updateCachedData((draft) => { draft.requests.unshift(webhookRequest); // auto select first request of webhook received if (draft.requests.length === 1) { const firstWebhookRequest = draft.requests[0]; api.dispatch(webhookRequestActions.set(firstWebhookRequest.id)); } // eslint-disable-next-line no-param-reassign draft.total += 1; }); } catch (error) { // eslint-disable-next-line no-console console.error(error); } }); // Cleanup await api.cacheEntryRemoved; ws.close(); }, }), getWebhook: build.query<Webhook, string>({ query: (id: string) => ({ url: `webhook/${id}` }), }), deleteWebhook: build.mutation<Webhook, string>({ query: (id: string) => ({ url: `webhook/${id}`, method: 'DELETE' }), }), findRequest: build.query<WebhookRequest, string>({ query: (id: string) => ({ url: `webhook-request/${id}` }), }), }), }); export const { useCreateWebhookMutation, useGetWebhooksQuery, useFindWebhookQuery, useFindRequestQuery, } = webhookAPI;
# Spyfall ## About Spyfall is a party game that never fails to entertain. Gather your friends and enter a mysterious location, known to all, except one spy, who lurks among you, hidden. Find the spy before they figure out where you are all located, before time is up! ## Contributors This project uses TypeScript, so be sure to install the relevant NPM packages after cloning the repository: ```shell npm install ``` Next, be sure to compile the TypeScript files before running the server: ```shell tsc ``` Last, the server can be launched as follows: ```shell go run . ```
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Sock; class SockController extends Controller { public function index() { return view('index'); } public function about() { return view('about'); } public function testmonial() { return view('testmonial'); } public function shop() { $shop=Sock::all(); return view('shop',compact('shop')); } public function contact() { return view('contact'); } public function show(Sock $id) { $item=$id; return view('shopshow',compact('item')); } public function create() { return view('newitem'); } public function store(Request $request) { $item=new Sock(); $item->name=request('name'); $item->src=request('src'); $item->price=request('price'); $request->validate([ 'name'=>'required|min:2|max:10', 'src'=>'required', 'price'=>'required' ]); $item->save(); return redirect('/shop'); } public function destroy($id) { $item=Sock::find($id); $item->delete(); return redirect('/shop'); } public function edit(Sock $id) { $item=$id; return view('shopedit',compact('item')); } public function update(Request $request,$id) { $item=Sock::Find($id); $item->name=request('name'); $item->src=request('src'); $item->price=request('price'); $request->validate([ 'name'=>'required|min:3|max:13', 'src'=>'required', 'price'=>'required' ]); $item->save(); return redirect('/shop'); } }
import { Forest } from '../forest'; async function runTests () { const forest = new Forest('nico@haenggi.ch', 'lpic11lpic11', null, null, 'http://localhost:8888'); await forest.login(); const plants = await forest.getAllPlantsSince(new Date().getTime() - 1000*60*60*24*30); console.log(plants); } runTests();
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlueLotus.ObjMas.Model { public class ObjMasModel { /* ObjKy, PrntKy, ObjNm, ObjCaptn, ToolTip, UsrObjKy, Prnt2Ky, DefaultValue, isFreeze, isEnable, Alignment, DefaultKy, */ public int ObjKy { get; set; } public int PrntKy { get; set; } public string ObjNm { get; set; } public string ObjCaptn { get; set; } public string ToolTip { get; set; } public int UsrObjKy { get; set; } public int Prnt2Ky { get; set; } public string DefaultValue { get; set; } public int isFreeze { get; set; } public int isEnable { get; set; } public string Alignment { get; set; } public int DefaultKy { get; set; } public string NxtEntObjNm { get; set; } public string EntKyAction { get; set; } /* DefaultDt, isVisible, Width, Format, Aggregates, FooterTemplate, GrpFooterTemplate, ObjTyp, URLController, URLAction */ public string DefaultDt { get; set; } public int isVisible { get; set; } public double Width { get; set; } public string Format { get; set; } public string DataType { get; set; } public string Aggregates { get; set; } public string Template { get; set; } public string FooterTemplate { get; set; } public string GrpFooterTemplate { get; set; } public string ObjTyp { get; set; } public string URLController { get; set; } public string URLAction { get; set; } public string OurCd { get; set; } public string OurCd2 { get; set; } //Target, ObjTypKy, SO, IcoURL, Des, isAct, CSSClassObjKy, ElementTypKy, TecRef, ReportPath, ReportServerURL public string Target { get; set; } public int ObjTypKy { get; set; } public string SO { get; set; } public string IcoURL { get; set; } public string Des { get; set; } public int isAct { get; set; } public int CSSClassObjKy { get; set; } public string CSSClass { get; set; } public string OnClickAction { get; set; } public int ElementTypKy { get; set; } public string TecRef { get; set; } public string ReportPath { get; set; } public string ReportServerURL { get; set; } public string ReportName { get; set; } public int isMust { get; set; } public string ValidationMesg { get; set; } public string ValidationOrder { get; set; } public int isFirstFocusObj { get; set; } public int IsTelerikRpt { get; set; } //ObjMass new Rows public int DuplicateFill { get; set; } public int ContraAutoFill { get; set; } public string NxtObjTyp { get; set; } //to Get the diffrent between Find FormGrid And FormGrid public string Lvl1ObjNm { get; set; } //Combo Filter Opction public string filterCriteria { get; set; } } }
package x64.directives; /** Uses a label to be used as the target of jumps, calls, and offsets. */ public class LabelInstruction extends Directive { public LabelInstruction(String name) { super(name + ":"); } }
### A Pluto.jl notebook ### # v0.12.7 using Markdown using InteractiveUtils # ╔═╡ 6fd616f6-1ea1-11eb-3814-8bfb4a096c49 using Pkg, DrWatson # ╔═╡ 6ffe2628-1ea1-11eb-24ea-57f985146a72 begin @quickactivate "StatisticsWithJuliaPlutoNotebooks" using DataFrames using HCubature end; # ╔═╡ ed174bc4-1ea0-11eb-1e2f-a32874cec549 md"## Listing 3.33" # ╔═╡ 70179b62-1ea1-11eb-13ce-7fb4d54bad4b begin M = 4.5 maxD = 10 end # ╔═╡ dde25fec-228e-11eb-2ec8-099e48158d12 f(x) = (2*pi)^(-length(x)/2) * exp(-(1/2)*x'x) # ╔═╡ dde2935e-228e-11eb-3074-f3bddb5149fc begin df = DataFrame() for n in 1:maxD a = -M*ones(n) b = M*ones(n) I,e = hcubature(f, a, b, maxevals = 10^7) append!(df, DataFrame(:n => n, :integral => I, :error => e)) end df end # ╔═╡ 70182cd8-1ea1-11eb-094d-8d0d49cf15f3 md"## End of listing 3.33" # ╔═╡ Cell order: # ╟─ed174bc4-1ea0-11eb-1e2f-a32874cec549 # ╠═6fd616f6-1ea1-11eb-3814-8bfb4a096c49 # ╠═6ffe2628-1ea1-11eb-24ea-57f985146a72 # ╠═70179b62-1ea1-11eb-13ce-7fb4d54bad4b # ╠═dde25fec-228e-11eb-2ec8-099e48158d12 # ╠═dde2935e-228e-11eb-3074-f3bddb5149fc # ╟─70182cd8-1ea1-11eb-094d-8d0d49cf15f3
import { Pipe, PipeTransform } from '@angular/core'; import { Player } from './player.model'; @Pipe({ name: 'positionFilter', }) export class PositionFilterPipe implements PipeTransform { transform(input: Player[], filterByPosition) { var output: Player[] = []; if(filterByPosition === "Jammer") { for(var i=0; i<input.length; i++) { if(input[i].position === "Jammer") { output.push(input[i]); } } return output; } else if (filterByPosition === "Blocker") { for(var i=0; i<input.length; i++) { if(input[i].position === "Jammer") { output.push(input[i]); } } return output; } else if (filterByPosition === "Coach") { for(var i=0; i<input.length; i++) { if(input[i].position === "Coach") { output.push(input[i]); } } return output; } else { return input; } } }
<?php namespace Tests\Unit\Flare\Values; use App\Flare\Values\ItemEffectsValue; use App\Flare\Values\ItemUsabilityType; use App\Flare\Values\MaxCurrenciesValue; use App\Flare\Values\NpcCommandTypes; use App\Flare\Values\NpcTypes; use Tests\TestCase; class NpcCommandTypesTest extends TestCase { public function testThrowError() { $this->expectException(\Exception::class); new NpcCommandTypes(67); } public function testIsTakeKingdom() { $this->assertTrue((new NpcCommandTypes(NpcCommandTypes::TAKE_KINGDOM))->isTakeKingdom()); } public function testIsConjure() { $this->assertTrue((new NpcCommandTypes(NpcCommandTypes::CONJURE))->isConjure()); } public function testIsReRoll() { $this->assertTrue((new NpcCommandTypes(NpcCommandTypes::RE_ROLL))->isReRoll()); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See the License.txt file in the project root for full license information. namespace Microsoft.AspNet.WebFormsDependencyInjection.Unity { using System; using System.Web; using global::Unity; /// <summary> /// Extension methods of HttpApplication that help use Unity container /// </summary> public static class HttpApplicationExtensions { /// <summary> /// /// </summary> /// <param name="application"></param> /// <returns></returns> public static IUnityContainer AddUnity(this HttpApplication application) { if (application == null) { throw new ArgumentNullException(nameof(application)); } return UnityAdapter.AddUnity(); } /// <summary> /// /// </summary> /// <returns></returns> public static IUnityContainer GetUnityContainer(this HttpApplication application) { return UnityAdapter.GetContainer(); } } }
--- speaker: Sruthi Sekar (IISc Mathematics) title: "Near-Optimal Non-malleable Codes and Leakage Resilient Secret Sharing Schemes" date: 9 August, 2021 time: 2 pm venue: Microsoft Teams (online) series: Thesis series-prefix: PhD series-suffix: colloquium --- Non-malleable codes (NMCs) are coding schemes that help in protecting crypto-systems under tampering attacks, where the adversary tampers the device storing the secret and observes additional input-output behavior on the crypto-system. NMCs give a guarantee that such adversarial tampering of the encoding of the secret will lead to a tampered secret, which is either same as the original or completely independent of it, thus giving no additional information to the adversary. Leakage resilient secret sharing schemes help a party, called a dealer, to share his secret message amongst $n$ parties in such a way that any $t$ of these parties can combine their shares to recover the secret, but the secret remains hidden from an adversary corrupting $< t$ parties to get their complete shares and additionally getting some bounded bits of leakage from the shares of the remaining parties. For both these primitives, whether you store the non-malleable encoding of a message on some tamper-prone system or the parties store shares of the secret on a leakage-prone system, it is important to build schemes that output codewords/shares that are of optimal length and do not introduce too much redundancy into the codewords/shares. This is, in particular, captured by the rate of the schemes, which is the ratio of the message length to the codeword length/largest share length. The research goal of the thesis is to improve the state of art on rates of these schemes and get near-optimal/optimal rates. In this talk, I will specifically focus on leakage resilient secret sharing schemes, describe the leakage model, and take you through the state of the art on their rates. Finally, I will present a recent construction of an optimal (constant) rate, leakage resilient secret sharing scheme in the so-called "joint and adaptive leakage model" where leakage queries can be made adaptively and jointly on multiple shares.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Restaurant; use App\Type; use App\Dish; class RestaurantController extends Controller { public function show($id) { // QUERY per trovare il ristorante di cui mi passo l'id come parametro $restaurant = Restaurant::where('id', $id)->first(); // Controllo che il ristorante esista if($restaurant) { // QUERY per prendere tutti i tipi relativi al ristorante visualizzato $types = $restaurant->types; // QUERY per prendere tutti i piatti del ristorante visualizzato $dishes = $restaurant->dishes; $data = [ 'restaurant' => $restaurant, 'types' => $types, 'dishes' => $dishes ]; return view('guest.restaurants.show', $data); } else { // Se il ristorante non esiste (l'id passato come parametro è NULL) abort(404); } } }
module Devbot.List ( runList ) where import Data.List (intercalate, sort) import Devbot.Internal.Common import Devbot.Internal.Display import Devbot.Event.Config (Config (..), Data (..), Event (..)) import qualified Devbot.Event.Config as E import Devbot.Service.Config (Service (..)) import qualified Devbot.Service.Config as S runList :: IO () -- ^ build list summaries of all the currently loaded events + services and display them -- to the console runList = do E.events >>= sortDo display S.services >>= sortDo display where sortDo :: (Displayable a, Ord a) => (a -> IO ()) -> [a] -> IO () sortDo f s = mapM_ f $ sort s class Displayable a where display :: a -> IO () instance Displayable Service where -- ^ show name, action, and uptime display (Service n c) = do now <- getTime status <- (\case (Just time) -> "uptime " <> prettyTime (now - time) Nothing -> "not running" ) <$> S.getUptime n putStrLn $ concat [ "service: ", printName n , pad, colorize blue (S.action c) , pad, colorize cyan status, "\n" ] where pad = "\n " instance Displayable Event where display (Event n c d) = do now <- getTime putStrLn $ concat [ printName n, "\n" , printAction c, "\n" , " ", printInterval c , printNext d now , printOptional c d , "\n" ] printName :: String -> String printName = colorize green printAction :: Config -> String printAction c = colorize blue _action where _action = " " <> intercalate pad (E.action c) pad = "\n " printInterval :: Config -> String printInterval c = colorize cyan $ "every " <> time <> ", " where time = clean $ prettyTime $ E.interval c printNext :: Data -> Integer -> String printNext (Data _ w _ _ _) time = colorize yellow $ if w - time > 0 then "next in " <> t else "now" where t = prettyTime $ w - time printOptional :: Config -> Data -> String printOptional (Config _ _ req _ par one) d = concat [ maybe "" printErrors $ _errors d , printDuration $ E._duration d , maybe "" printRequire req , printParallel par , printOneShell one ] where printErrors :: Integer -> String printErrors 1 = ", " <> colorize red "1 error" printErrors x = ", " <> colorize red (show x <> " errors") printDuration :: Integer -> String printDuration 0 = ", " <> colorize cyan "instant" printDuration 1 = ", " <> colorize cyan "took 1 second" printDuration x = ", " <> colorize cyan ("took " <> show x <> " seconds") printRequire :: String -> String printRequire r = ", requires " <> r printParallel :: Bool -> String printParallel True = ", " <> colorize magenta "parallel" printParallel _ = "" printOneShell :: Bool -> String printOneShell False = ", " <> colorize magenta "isolated" printOneShell _ = ""
import React, { Component } from 'react'; import { Text, View, StyleSheet, TouchableOpacity, Image, ImageBackground, StatusBar, SafeAreaView, Platform, } from 'react-native'; export default class HomeScreen extends Component { constructor(props) { super(props); this.state = {}; } render() { return ( <View style={styles.container}> <SafeAreaView style={styles.droidSafeArea} /> <ImageBackground source={require('../assets/space.gif')} style={styles.backgroundImage}> <View style={styles.titleBar}> <Text style={styles.titleText}>Stellar App</Text> </View> <TouchableOpacity style={styles.routeCard} onPress={() => this.props.navigation.navigate('SpaceCrafts')}> <Text style={styles.routeText1}>Space Crafts</Text> <Image source={require('../assets/space_crafts.png')} style={styles.iconImage1}></Image> </TouchableOpacity> <TouchableOpacity style={styles.routeCard} onPress={() => this.props.navigation.navigate('StarMap')}> <Text style={styles.routeText2}>Star Maps</Text> <Image source={require('../assets/star_map.png')} style={styles.iconImage2}></Image> </TouchableOpacity> <TouchableOpacity style={styles.routeCard} onPress={() => this.props.navigation.navigate('DailyPic')}> <Text style={styles.routeText3}>Daily Pictures</Text> <Image source={require('../assets/daily_pictures.png')} style={styles.iconImage3}></Image> </TouchableOpacity> </ImageBackground> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, droidSafeArea: { marginTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0, }, backgroundImage: { flex: 1, resizeMode: 'cover', width: 333, }, titleBar: { flex: 0.15, justifyContent: 'center', alignItems: 'center', marginTop: 30, }, titleText: { fontSize: 40, fontWeight: 'bold', color: 'white', fontFamily: 'Trebuchet MS', }, routeCard: { height: 70, width: 260, marginLeft: 35, marginTop: 60, borderRadius: 15, backgroundColor: '#efeded', }, routeText1:{ fontSize: 27, fontWeight: 'bold', color: 'rgb(2, 8, 119)', marginTop: 18, paddingLeft: 30, fontFamily: 'Trebuchet MS', }, routeText2:{ fontSize: 27, fontWeight: 'bold', color: 'rgb(2, 8, 119)', marginTop: 18, paddingLeft: 95, fontFamily: 'Trebuchet MS', }, routeText3:{ fontSize: 26, fontWeight: 'bold', color: 'rgb(2, 8, 119)', marginTop: 18, paddingLeft: 16, fontFamily: 'Trebuchet MS', }, iconImage1:{ position: 'absolute', height: 80, width: 80, resizeMode: 'contain', right: -10, top: -10, }, iconImage2:{ position: 'absolute', height: 60, width: 80, resizeMode: 'contain', right: 182, top: 5, }, iconImage3:{ position: 'absolute', height: 80, width: 80, resizeMode: 'contain', right: -17, top: -8, } });
import { useRecoilValue } from 'recoil' import { initialStep } from 'lib/state/booking-flow/types' import { useEffect } from 'react' import { useRouter } from 'next/router' import flowStepState, { useFlowStep } from 'lib/state/booking-flow' import { getStepFromPath } from 'lib/utils/stepUtils' import { useCartDataLoadedState, useCartMethods } from 'lib/state/cart' export const useFlowRouting = () => { const router = useRouter() const { setRecoilStep } = useFlowStep() const currentFlowStep = useRecoilValue(flowStepState) const { getCartDataLoadedState } = useCartMethods() const handleHash = (pathname: string) => { if (!getCartDataLoadedState()) { return } let step = getStepFromPath(pathname, initialStep) if (step !== undefined) { if (currentFlowStep.step !== step) { setRecoilStep(step) } } } const handlePath = (pathname: string) => { if (!getCartDataLoadedState()) { return } if (pathname === '/' || pathname === '' || pathname === '/#') { if (currentFlowStep.step !== initialStep) { setRecoilStep(initialStep) } } else { handleHash(pathname) } } useEffect(() => { let cancel = false const onRouteChange = async (pathname: string) => { handlePath(pathname) } router.events.on('routeChangeComplete', onRouteChange) return () => { cancel = true router.events.off('routeChangeComplete', onRouteChange) } // eslint-disable-next-line }, [currentFlowStep]) useEffect(() => { let cancel = false const onRouteChange = async (pathname: string) => { handleHash(pathname) } router.events.on('hashChangeComplete', onRouteChange) return () => { cancel = true router.events.off('hashChangeComplete', onRouteChange) } // eslint-disable-next-line }, [currentFlowStep]) }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.AspNetCore.Mvc.Rendering; using TerribleBankInc.Models.Enums; namespace TerribleBankInc.Models.ViewModels { public class BankTransactionViewModel { [Required] public int SourceClientId { get; set; } [Required] [DataType(DataType.EmailAddress)] public string DestinationClientEmail { get; set; } [Required] public string DestinationAccountNumber { get; set; } public string Details { get; set; } [Required] public string SourceAccountNumber { get; set; } [Required] public CurrencyTypes Currency { get; set; } [Required] public decimal Amount { get; set; } public List<SelectListItem> ActiveAccounts { get; set; } } }
package exercises.ch04 object Ex04 { def sequence[A](a: List[Option[A]]): Option[List[A]] = { val newList = a.flatMap(a => a match { case None => List(); case Some(aa) => List(aa) }) if (newList.size < a.size) None else Some(newList) } def main(args: Array[String]): Unit = { println(sequence(List(None, Some(2), Some(3)))) println(sequence(List(Some(1), None, Some(3)))) println(sequence(List(Some(1), Some(2), Some(3)))) } }
from rest_framework.generics import get_object_or_404 from django.http import HttpRequest import access from access.resources import Resources from api.endpoint.project import ProjectPermission, ProjectResourceEndpoint from db.models.jobs import Job class JobEndpoint(ProjectResourceEndpoint): queryset = Job.objects CONTEXT_KEYS = ProjectResourceEndpoint.CONTEXT_KEYS + ('job_id',) CONTEXT_OBJECTS = ProjectResourceEndpoint.CONTEXT_OBJECTS + ('job',) lookup_url_kwarg = 'job_id' def _initialize_context(self) -> None: # pylint:disable=attribute-defined-outside-init super()._initialize_context() self.job = self.get_object() class JobResourceListEndpoint(ProjectResourceEndpoint): CONTEXT_KEYS = ProjectResourceEndpoint.CONTEXT_KEYS + ('job_id',) CONTEXT_OBJECTS = ProjectResourceEndpoint.CONTEXT_OBJECTS + ('job',) lookup_url_kwarg = 'job' def enrich_queryset(self, queryset): return queryset.filter(job=self.job) def _initialize_context(self) -> None: # pylint:disable=attribute-defined-outside-init super()._initialize_context() self.job = get_object_or_404(Job, id=self.job_id, project=self.project) class JobResourcePermission(ProjectPermission): SCOPE_MAPPING = access.get_scope_mapping_for(Resources.PROJECT_RESOURCE) def has_object_permission(self, request: HttpRequest, view, obj) -> bool: return super().has_object_permission(request, view, obj.job.project) class JobResourceEndpoint(JobResourceListEndpoint): permission_classes = (JobResourcePermission,) AUDITOR_EVENT_TYPES = None lookup_field = 'id' lookup_url_kwarg = 'id'
<?php declare(strict_types=1); /** * This file is part of the Invo. * * (c) Phalcon Team <team@phalcon.io> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Invo\Plugins; use Phalcon\Acl\Adapter\Memory as AclList; use Phalcon\Acl\Component; use Phalcon\Acl\Role; use Phalcon\Acl\Enum; use Phalcon\Di\Injectable; use Phalcon\Events\Event; use Phalcon\Mvc\Dispatcher; /** * SecurityPlugin * * This is the security plugin which controls that users only have access to the modules they're assigned to */ class SecurityPlugin extends Injectable { /** * This action is executed before execute any action in the application * * @param Event $event * @param Dispatcher $dispatcher * @return bool */ public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher) { $auth = $this->session->get('auth'); if (!$auth) { $role = 'Guests'; } else { $role = 'Users'; } $controller = $dispatcher->getControllerName(); $action = $dispatcher->getActionName(); $acl = $this->getAcl(); if (!$acl->isComponent($controller)) { $dispatcher->forward([ 'controller' => 'errors', 'action' => 'show404', ]); return false; } $allowed = $acl->isAllowed($role, $controller, $action); if (!$allowed) { $dispatcher->forward([ 'controller' => 'errors', 'action' => 'show401', ]); $this->session->destroy(); return false; } return true; } /** * Returns an existing or new access control list * * @returns AclList */ protected function getAcl(): AclList { if (isset($this->persistent->acl)) { return $this->persistent->acl; } $acl = new AclList(); $acl->setDefaultAction(Enum::DENY); // Register roles $roles = [ 'users' => new Role( 'Users', 'Member privileges, granted after sign in.' ), 'guests' => new Role( 'Guests', 'Anyone browsing the site who is not signed in is considered to be a "Guest".' ) ]; foreach ($roles as $role) { $acl->addRole($role); } //Private area resources $privateResources = [ 'companies' => ['index', 'search', 'new', 'edit', 'save', 'create', 'delete','test'], 'ana' => ['index', 'search', 'new', 'edit', 'save', 'create', 'delete','test'], 'products' => ['index', 'search', 'new', 'edit', 'save', 'create', 'delete'], 'producttypes' => ['index', 'search', 'new', 'edit', 'save', 'create', 'delete'], 'invoices' => ['index', 'profile'], ]; foreach ($privateResources as $resource => $actions) { $acl->addComponent(new Component($resource), $actions); } //Public area resources $publicResources = [ 'index' => ['index'], 'about' => ['index'], 'register' => ['index'], 'errors' => ['show401', 'show404', 'show500'], 'session' => ['index', 'register', 'start', 'end'], 'contact' => ['index', 'send'], ]; foreach ($publicResources as $resource => $actions) { $acl->addComponent(new Component($resource), $actions); } //Grant access to public areas to both users and guests foreach ($roles as $role) { foreach ($publicResources as $resource => $actions) { foreach ($actions as $action) { $acl->allow($role->getName(), $resource, $action); } } } //Grant access to private area to role Users foreach ($privateResources as $resource => $actions) { foreach ($actions as $action) { $acl->allow('Users', $resource, $action); } } //The acl is stored in session, APC would be useful here too $this->persistent->acl = $acl; return $acl; } }
#!/bin/bash # Reset mmt-probe WORKSPACE=/home/montimage/workspace PUBLIC_PATH=$WORKSPACE/express-server/public/sdk SRC=$WORKSPACE/montimage/mmt-sdk TOHTML=$WORKSPACE/montimage/mmt-test/pythons/cppcheck2html.py cd $SRC/ cppcheck --xml src/* 2> cppcheck_output.xml mkdir -p cppcheck_$1 python $TOHTML --file=cppcheck_output.xml --report-dir=cppcheck_$1 --title=MMT-SDK mv cppcheck_$1 $PUBLIC_PATH rm cppcheck_output.xml
require 'spec_helper' describe "The super keyword" do it "should return s(:zsuper) when no arguments or parans" do opal_parse("super").should == [:zsuper] end it "should return s(:super) for any arguments" do opal_parse("super 1").should == [:super, [:lit, 1]] opal_parse("super 1, 2").should == [:super, [:lit, 1], [:lit, 2]] opal_parse("super 1, *2").should == [:super, [:lit, 1], [:splat, [:lit, 2]]] end it "should always return s(:super) when parans are used" do opal_parse("super()").should == [:super] opal_parse("super(1)").should == [:super, [:lit, 1]] opal_parse("super(1, 2)").should == [:super, [:lit, 1], [:lit, 2]] opal_parse("super(1, *2)").should == [:super, [:lit, 1], [:splat, [:lit, 2]]] end end
--- layout: default --- Some [examples](math_prog) of mathematical programming. [Some](http://vlmeg.eu3.biz/#) of my photos. <!--- [Some](vlmeg.eu3.biz) of my photos. ---> <!--- [...](test) ---> <!--- Check here original theme https://github.com/pages-themes/cayman#usage --->
import 'package:flutter/material.dart'; import 'package:hacktoberfest_flutter/animations/bottom_animation.dart'; import 'package:hacktoberfest_flutter/util/restart_app.dart'; import 'package:hacktoberfest_flutter/widgets/custom_listTile.dart'; class Contributor extends StatelessWidget { // Add your Full Name in this list // Please do not remove any other name :) final contributorsName = [ 'Moh. Absar Rahman', 'Dev Adnani', 'Muhammad Hamza', 'Garima Chandna', 'Keshav Kaushik', 'Prateek SU', 'Muhammad Saif Waheed Raja', 'Eqra Khattak', 'Muhammad Kumail', 'Aman Srivastava', 'Apoorv Maheshwari', 'Oussama Bouchikhi', 'Adeoye Ayomide', 'Muhammad Akif Farhan', 'Zohaib Munir', 'Fatima Shirazi', 'Haseeb Ali Sajid', 'Yusuf Adefolahan', 'Rajit Deb', 'Alen Jojo', 'Ajay Bairwa', 'Samrat Khan', 'Shoaib Ahmed', 'Janhavi Kulkarni', 'Arjun Sinha', 'Muhideen Mujeeb', 'Haris Nazir', 'Yudi Purwanto', 'Muhammad Asif Jawaid', 'Mayukh Sil', 'Muhammad Tabish Khanday', 'Ali Karani', 'Enzo Danjour', 'Amit Verma', 'Usama Ejaz', 'AbuBakar Sheikh', 'Laraib Noor', 'Rishabh Negi', 'Antoni Wijaya', 'Amaldev M V', 'Agus Himawan', 'Tusar Ranjan Mahapatra', 'Habeel Hashmi', 'Rithik Bhandari', 'Muhammad Zain Qadri', 'London Tran', 'Aditya Birangal', 'Sai Nitesh', 'Muhammad Zeeshan', 'Akanksha Singh', 'Praneeth Fernando', 'Abdullateef Olawale Sarafadeen', 'Kamalpreet Kaur', 'Harshal Shree', 'Sohan Kathait', 'Malavika Sreekumar', 'Rida Ayaz', 'Nim Chathu', 'Ahmad Khan', 'Md Zaid Ansari', 'Muhammad Zeeshan', 'Dada Abdulrasheed', 'Hemant', 'Chakshu Salgotra', 'Hannes Kinnunen', 'Ram Gunasekaran A', 'Maximilian Flechtner', 'Matheus Cavalcante Fernandes', 'Dipanshu Kalra', 'Gunvant Chandratre', 'Hari Prasad', 'Lorenzo Pieri', 'Rodolfo Dantas de Oliveira Bezerra', 'Muhammad Hassan Tariq', 'Ahmad Khan', 'Sunday Malgwi', 'Sanjay Soni', // 'Atsuvia Marc', // 'Ariel Roque', // 'Jean Nshuti', // 'Suresh Sharma', 'Michael Dadzie', 'Zwe Mun Htun', 'Srishti Vashistha', 'Neha Ajith', 'Naveena Ramesh Vardhini ', 'Muhammad Hilmy AL Jauzy', 'Pranav Nair' ]; final gitHubUserName = [ 'absarrahman', 'Dev-Adnani', 'mhmzdev', 'garimachandna', 'keshkaush', 'prateekmedia', 'SafuRaja7', 'eqrakhattak', 'mkumail1', 'aman1210', 'bairwa25', 'Apoorv-cloud', 'oussamabouchikhi', 'Ayomilotunde', 'akifarhan', 'Zohaibb-m', 'iamfaatima', 'haseebalisajid', 'sanxy', 'rajitdeb', 'alenjojo', 'Samrat-Khan', 'shobu95', 'Janhavi23', 'ryuukenshi', 'Mujhtech', 'HarisNazir', 'zhiephie', 'aasif1297', 'mayukhsil', 'mtabishk', 'alikarani', 'enzodanjour', 'amitverma-cf', 'UsamaEjaz0', 'onymousproduktions', 'LaraibNoor', 'Rishabh-Negi', 'AntoniKwok', 'AmaldevAD', 'Agushm', 'Tusar6701', 'Habeel786', 'rithik-dev', 'imuhammadzain', 'LondonTran', 'AdityaBirangal', 'sainiteshb', '', 'Akanksha1212', 'praneethfdo', '', 'kamal-kaur04', 'harshalshree', 'Thesohan', 'malavikasreekumar', 'ridaayaz', 'Nimesha1996', // 'olaabdul', // 'praneethfdo', 'rmahmadkhan', 'razorcalhn', 'zeeshanmahar007', 'iamhabee', 'Hemant72', 'chakshu21', 'Steellow', 'ramcalm', 'MaxiTechno1ogy', 'matheusc3m', 'DipanshuKalra', 'GunvantGMC', 'hariprasad1003', 'LRNZ09', 'denpufa', 'iamhsntariq05', 'rmahmadkhan', 'malgwi', 'imSanjaySoni', // 'cucusgeek99', 'michaeldadzie', 'zwe-mun-htun', 'srishtiv27', 'neha-ajith', 'naveeramesh', 'hilmykun', 'PranavNair01', ]; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ SliverAppBar( backgroundColor: Colors.white, leading: BackButton( color: Color(0xfff74700), onPressed: () => RestartWidget.restartApp(context), ), pinned: true, expandedHeight: 220.0, flexibleSpace: FlexibleSpaceBar( centerTitle: true, title: Text( "Hacktoberfest Contributors", style: TextStyle( color: Color(0xfff74700), fontSize: 17.0, fontWeight: FontWeight.w600, ), ), background: Center( child: Image.asset( 'assets/banner2021.png', height: 180.0, ), ), ), ), ], body: ListView.separated( physics: BouncingScrollPhysics(), padding: const EdgeInsets.all(8.0), separatorBuilder: (context, index) => Divider(color: Colors.transparent), itemCount: contributorsName.length, itemBuilder: (context, index) { return WidgetAnimator( child: CustomListTile( contributorGitHubUserName: gitHubUserName[index], contributorName: contributorsName[index], ), ); }, ), ), ); } }
'use strict'; require('../common'); // This test ensures that `addRequest`'s Legacy API accepts `localAddress` // correctly instead of accepting `path`. // https://github.com/nodejs/node/issues/5051 const assert = require('assert'); const agent = require('http').globalAgent; // Small stub just so we can call addRequest directly const req = { getHeader: () => {} }; agent.maxSockets = 0; // `localAddress` is used when naming requests / sockets while using the Legacy // API. Port 8080 is hardcoded since this does not create a network connection. agent.addRequest(req, 'localhost', 8080, '127.0.0.1'); assert.strictEqual(Object.keys(agent.requests).length, 1); assert.strictEqual( Object.keys(agent.requests)[0], 'localhost:8080:127.0.0.1'); // `path` is *not* used when naming requests / sockets. // Port 8080 is hardcoded since this does not create a network connection agent.addRequest(req, { host: 'localhost', port: 8080, localAddress: '127.0.0.1', path: '/foo' }); assert.strictEqual(Object.keys(agent.requests).length, 1); assert.strictEqual( Object.keys(agent.requests)[0], 'localhost:8080:127.0.0.1');
2020年10月19日17时数据 Status: 200 1.王祖蓝女儿2岁身高 微博热度:4291891 2.酸汤子中毒事件唯一幸存者去世 微博热度:2136231 3.佟丽娅被儿子嫌弃太瘦了 微博热度:2034054 4.倪妮锁骨 微博热度:1646581 5.韩国韵达 微博热度:1570642 6.微博电商直播 微博热度:1295152 7.酒店称未开除与辛巴起冲突保安 微博热度:783526 8.湖人创始人去世 微博热度:593376 9.中国驻斐济使馆回应 微博热度:567709 10.张若昀瘦了 微博热度:567425 11.四川一娃娃机里现真娃娃 微博热度:566736 12.制药学院男生自制唇膏送女友 微博热度:565215 13.银行考试像低配版最强大脑 微博热度:514245 14.韩国1棵白菜79元 微博热度:514029 15.司机遇险暗打手势收费员秒懂报警 微博热度:512630 16.美国男子吊在特朗普大厦16楼外 微博热度:512473 17.罗志祥方拒绝综艺主持邀约 微博热度:511284 18.一个人演了一村人 微博热度:510558 19.爱萝莉 微博热度:509407 20.主持人口误称郭麒麟宋轶演的是姐妹 微博热度:508673 21.上海野生动物园群熊伤人救援画面 微博热度:508007 22.今年是特别难的一年 微博热度:507764 23.1921定档 微博热度:451354 24.斐济 微博热度:374543 25.翟潇闻口罩 微博热度:369911 26.胡歌不担心粉丝流失 微博热度:363793 27.铁路回应男子拒让靠窗女子入座 微博热度:356186 28.神似豪门姐弟的明星神图 微博热度:346910 29.山东省考 微博热度:310376 30.毛不易被周扬青发微博提到了 微博热度:303467 31.防弹少年团 微博热度:303444 32.谁说男生不懂细节 微博热度:294058 33.小伙上树救猫双双被困 微博热度:266547 34.安倍晋三参拜靖国神社 微博热度:240329 35.邓紫棋怼粉丝 微博热度:229712 36.李佳琦新歌 微博热度:226968 37.乐观的人有多可爱 微博热度:217949 38.刘强任成都大学党委书记 微博热度:208119 39.天官赐福动画片头曲 微博热度:176402 40.日本乳业品牌回收40万罐婴儿奶 微博热度:169365 41.如何成功地弹一次舌 微博热度:159475 42.鹿晗西装沙漠大片 微博热度:138000 43.左拆家原声 微博热度:120244 44.很难毕业的动画片 微博热度:107932 45.赘婿片花 微博热度:107222 46.童瑶 这个奖属于所有不言放弃的女演员 微博热度:106794 47.金鹰节提词器穿帮 微博热度:105609 48.人类幼崽的可爱巅峰 微博热度:104584 49.一男子拒绝给内侧座位旅客让行 微博热度:103650 50.王俊凯中分造型 微博热度:103263
package io.jenkins.plugins.analysis.core.history; import java.util.Optional; import io.jenkins.plugins.analysis.core.views.ResultAction; import hudson.model.Run; /** * Selects a {@link ResultAction} from all registered actions in a given job. * * @author Ullrich Hafner */ public interface ResultSelector { /** * Tries to find a result action of the specified build that should be used to compute the history. * * @param build * the build * * @return the result action, if there is one attached to the job */ Optional<ResultAction> get(Run<?, ?> build); }
@TestOn('browser') import 'package:test/test.dart'; import 'package:angular/src/security/dom_sanitization_service.dart'; import 'package:angular/src/security/dom_sanitization_service_impl.dart'; void main() { final DomSanitizationService sanitizer = DomSanitizationServiceImpl(); const safeHtml = '<p>poodle power</p>'; const unsafeHtml = 'a <script>alert("hi")</script> b'; group('sanitizeHtml', () { test('passes null through', () { expect(sanitizer.sanitizeHtml(null), null); }); test('passes safe strings through untouched', () { expect(sanitizer.sanitizeHtml(safeHtml), safeHtml); }); test('removes unsafe tags', () { expect(sanitizer.sanitizeHtml(unsafeHtml), 'a b'); }); test('passes SafeHtml through untouched', () { expect( sanitizer.sanitizeHtml(sanitizer.bypassSecurityTrustHtml(unsafeHtml)), unsafeHtml); }); test('rejects other SafeValues', () { expect( () => sanitizer.sanitizeHtml( sanitizer.bypassSecurityTrustUrl('https://google.com')), throwsUnsupportedError); }); }); group('sanitizeStyle', () { const safeStyle = 'color: red;'; const unsafeStyle = 'background-image: url("javascript:uh-oh")'; test('passes null through', () { expect(sanitizer.sanitizeStyle(null), null); }); test('passes normal styles untouched', () { expect(sanitizer.sanitizeStyle(safeStyle), safeStyle); }); test('rejects unsafe styles', () { expect( sanitizer.sanitizeStyle(unsafeStyle), isNot(contains('javascript'))); }); test('passes SafeStyle through untouched', () { expect( sanitizer .sanitizeStyle(sanitizer.bypassSecurityTrustStyle(unsafeStyle)), unsafeStyle); }); test('rejects other SafeValues', () { expect( () => sanitizer.sanitizeStyle( sanitizer.bypassSecurityTrustUrl('https://google.com')), throwsUnsupportedError); }); }); group('sanitizeUrl', () { const safeUrl = 'https://google.com'; const unsafeUrl = 'javascript:alert("arghhhh")'; test('passes null through', () { expect(sanitizer.sanitizeUrl(null), null); }); test('passes normal URLs untouched', () { expect(sanitizer.sanitizeUrl(safeUrl), safeUrl); }); test('rejects unsafe URLs', () { expect(sanitizer.sanitizeUrl(unsafeUrl), equals('unsafe:$unsafeUrl')); }); test('passes SafeUrl through untouched', () { expect(sanitizer.sanitizeUrl(sanitizer.bypassSecurityTrustUrl(unsafeUrl)), unsafeUrl); }); test('rejects other SafeValues', () { expect( () => sanitizer .sanitizeUrl(sanitizer.bypassSecurityTrustHtml('<p>egg</p>')), throwsUnsupportedError); }); }); group('sanitizeResourceUrl', () { const resourceUrl = 'https://google.com/some_script.js'; test('passes null through', () { expect(sanitizer.sanitizeResourceUrl(null), null); }); test('rejects all strings', () { expect(() => sanitizer.sanitizeResourceUrl(resourceUrl), throwsUnsupportedError); }); test('passes SafeResourceUrl through untouched', () { expect( sanitizer.sanitizeResourceUrl( sanitizer.bypassSecurityTrustResourceUrl(resourceUrl)), resourceUrl); }); test('rejects other SafeValues', () { expect( () => sanitizer.sanitizeResourceUrl( sanitizer.bypassSecurityTrustUrl('https://google.com')), throwsUnsupportedError); }); }); }
const { h, Component } = require('preact'); const styles = require('./scss/canvas.scss'); class aniCanvas extends Component { render(props) { return ( <canvas className={animationCanvas}></canvas> ); } } module.exports = aniCanvas;
#include <iostream> #include <opencv2/highgui/highgui.hpp> #define TV_FUNC_DEBUG #define TV_FUNC_DEBUG_VERBOSE #include <mtvmtl/core/data.hpp> #include <mtvmtl/core/functional.hpp> #include <vpp/vpp.hh> #include <vpp/utils/opencv_bridge.hh> int main(int argc, const char *argv[]) { using namespace tvmtl; Eigen::initParallel(); if (argc != 2){ std::cerr << "Usage : " << argv[0] << " image" << std::endl; return 1; } typedef Manifold< EUCLIDIAN, 1 > mf_t; typedef typename mf_t::value_type vec1d; typedef Data< mf_t, 2> data_t; typedef typename data_t::storage_type store_type; data_t myData=data_t(); myData.rgb_readBrightness(argv[1]); typedef Functional<FIRSTORDER, ISO, mf_t, data_t> func_t; func_t myFunc(3.0, myData); func_t::result_type result = 0.0; //Functional evaluation std::cout << "Evaluate Functional..." << std::endl; result = myFunc.evaluateJ(); std::cout << "Functional evaluation for Picture " << argv[1] << ": " << result << std::endl; //Gradient std::cout << "Evaluate Gradient..." << std::endl; myFunc.evaluateDJ(); //Hessian std::cout << "Evaluate Hessian..." << std::endl; myFunc.evaluateHJ(); return 0; }
#include <stdio.h> #include <time.h> int main (void) { time_t t0; int i = 7; int y; t0 = time(NULL); while (i > 0) { i--; y = 0xFFFFFFF; while (y > 0) y--; } printf("Executed in %lf seconds.\n", difftime(time(NULL), t0)); return 0; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpGL { /// <summary> /// /// </summary> public class TexStorage3D : TexStorageBase { private int width; private int height; private int depth; internal static readonly GLDelegates.void_uint_int_uint_int_int_int glTexStorage3D; static TexStorage3D() { glTexStorage3D = GL.Instance.GetDelegateFor("glTexStorage3D", GLDelegates.typeof_void_uint_int_uint_int_int_int) as GLDelegates.void_uint_int_uint_int_int_int; } /// <summary> /// /// </summary> /// <param name="target"></param> /// <param name="internalFormat"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="depth"></param> /// <param name="mipmapLevelCount"></param> public TexStorage3D(Target target, uint internalFormat, int width, int height, int depth, int mipmapLevelCount = 1) : base((TextureTarget)target, internalFormat, mipmapLevelCount) { this.width = width; this.height = height; this.depth = depth; } /// <summary> /// /// </summary> public override void Apply() { glTexStorage3D((uint)target, mipmapLevelCount, internalFormat, width, height, depth); } /// <summary> /// /// </summary> public enum Target : uint { /// <summary> /// /// </summary> Texture2DArray = GL.GL_TEXTURE_2D_ARRAY, /// <summary> /// /// </summary> Texture3D = GL.GL_TEXTURE_3D, } } }
# impala-client 请求 impala 并返回数据以表格形式显示
<?php namespace Dykyi\CommandBus\Handler; use Dykyi\CommandBus\Command\BuildRouteCommand; use Dykyi\Response\ResponseFactory; use Dykyi\Services\CardService\CardRequest; use Dykyi\Services\CardService\CardService; use Dykyi\Services\CardService\Clients\InMemoryCardClient; use Dykyi\Services\CardService\Repository\InMemoryCardRepository; use Dykyi\Transformer\Transformer; use Stash\Driver\FileSystem; use Symfony\Component\HttpFoundation\Response; /** * Class BuildRouteCommandHandler * @package Dykyi\Command\Handler */ class BuildRouteCommandHandler { /** * @param BuildRouteCommand $command * @throws \Throwable */ public function handle(BuildRouteCommand $command) { try { $request = new CardRequest( $command->getResponseFormat() ); $service = new CardService( new InMemoryCardRepository(), new InMemoryCardClient(['url' => getenv('API_CLIENT_URL')]), new FileSystem() ); $sortCards = $service->execute(); $responseObject = ResponseFactory::create($request->getResponseFormat()); $response = new Response($responseObject->response($sortCards, new Transformer())); $response->send(); } catch (\InvalidArgumentException $exception) { $response = new Response($exception->getMessage()); $response->send(); } catch (\Throwable $exception) { throw $exception; } } }
<?php namespace Flow\Node; use Flow\Node; final class ForNode extends Node { private $seq; private $key; private $value; private $body; private $else; public function __construct($seq, $key, $value, $body, $else, $line) { parent::__construct($line); $this->seq = $seq; $this->key = $key; $this->value = $value; $this->body = $body; $this->else = $else; } public function compile($compiler, $indent = 0) { $compiler->addTraceInfo($this, $indent); $compiler->pushContext('loop', $indent); if ($this->key) { $compiler->pushContext($this->key, $indent); } $compiler->pushContext($this->value, $indent); $else = false; if (!is_null($this->else)) { $compiler->raw('if (Flow\Helper::is_iterable(', $indent); $this->seq->compile($compiler); $compiler->raw(') && !Flow\Helper::is_empty('); $this->seq->compile($compiler); $compiler->raw(")) {\n"); $else = true; } $compiler->raw( 'foreach (($context[\'loop\'] = $this->iterate($context, ', $else ? ($indent + 1) : $indent ); $this->seq->compile($compiler); if ($this->key) { $compiler->raw( ')) as $context[\'' . $this->key . '\'] => $context[\'' . $this->value . '\']) {' . "\n" ); } else { $compiler->raw( ')) as $context[\'' . $this->value . '\']) {' . "\n" ); } $this->body->compile($compiler, $else ? ($indent + 2) : ($indent + 1)); $compiler->raw("}\n", $else ? ($indent + 1) : $indent); if ($else) { $compiler->raw("} else {\n", $indent); $this->else->compile($compiler, $indent + 1); $compiler->raw("}\n", $indent); } $compiler->popContext('loop', $indent); if ($this->key) { $compiler->popContext($this->key, $indent); } $compiler->popContext($this->value, $indent); } }
#ifndef JUDYLARRAY_H #define JUDYLARRAY_H /****************************************************************************//** * \file judyLArray.h C++ wrapper for judyL array implementation * * A judyL array maps JudyKey's to corresponding memory cells, each containing * a JudyValue. Each cell must be set to a non-zero value by the caller. * * Author: Mark Pictor. Public domain. * ********************************************************************************/ #include "judy.h" #include "assert.h" template< typename JudyKey, typename JudyValue > struct judylKVpair { JudyKey key; JudyValue value; }; /** A judyL array maps JudyKey's to corresponding memory cells, each containing * a JudyValue. Each cell must be set to a non-zero value by the caller. * * Both template parameters must be the same size as a void* * \param JudyKey the type of the key, i.e. uint64_t, pointer-to-object, etc * \param JudyValue the type of the value */ template< typename JudyKey, typename JudyValue > class judyLArray { public: typedef judylKVpair< JudyKey, JudyValue > pair; protected: Judy * _judyarray; unsigned int _maxLevels, _depth; JudyValue * _lastSlot; JudyKey _buff[1]; bool _success; pair _kv; public: judyLArray(): _maxLevels( sizeof( JudyKey ) ), _depth( 1 ), _lastSlot( 0 ), _success( true ) { assert( sizeof( JudyKey ) == JUDY_key_size && "JudyKey *must* be the same size as a pointer!" ); assert( sizeof( JudyValue ) == JUDY_key_size && "JudyValue *must* be the same size as a pointer!" ); _judyarray = judy_open( _maxLevels, _depth ); _buff[0] = 0; } explicit judyLArray( const judyLArray< JudyKey, JudyValue > & other ): _maxLevels( other._maxLevels ), _depth( other._depth ), _success( other._success ) { _judyarray = judy_clone( other._judyarray ); _buff[0] = other._buff[0]; find( *_buff ); //set _lastSlot } ~judyLArray() { judy_close( _judyarray ); } void clear( bool deleteContents = false ) { JudyKey key = 0; while( 0 != ( _lastSlot = ( JudyValue * ) judy_strt( _judyarray, ( const unsigned char * ) &key, 0 ) ) ) { if( deleteContents ) { delete *_lastSlot; } judy_del( _judyarray ); } } JudyValue getLastValue() { assert( _lastSlot ); return &_lastSlot; } void setLastValue( JudyValue value ) { assert( _lastSlot ); &_lastSlot = value; } bool success() { return _success; } //TODO // allocate data memory within judy array for external use. // void *judy_data (Judy *judy, unsigned int amt); /// insert or overwrite value for key bool insert( JudyKey key, JudyValue value ) { assert( value != 0 ); _lastSlot = ( JudyValue * ) judy_cell( _judyarray, ( const unsigned char * ) &key, _depth * JUDY_key_size ); if( _lastSlot ) { *_lastSlot = value; _success = true; } else { _success = false; } return _success; } /// retrieve the cell pointer greater than or equal to given key /// NOTE what about an atOrBefore function? const pair atOrAfter( JudyKey key ) { _lastSlot = ( JudyValue * ) judy_strt( _judyarray, ( const unsigned char * ) &key, _depth * JUDY_key_size ); return mostRecentPair(); } /// retrieve the cell pointer, or return NULL for a given key. JudyValue find( JudyKey key ) { _lastSlot = ( JudyValue * ) judy_slot( _judyarray, ( const unsigned char * ) &key, _depth * JUDY_key_size ); if( _lastSlot ) { _success = true; return *_lastSlot; } else { _success = false; return 0; } } /// retrieve the key-value pair for the most recent judy query. inline const pair & mostRecentPair() { judy_key( _judyarray, ( unsigned char * ) _buff, _depth * JUDY_key_size ); if( _lastSlot ) { _kv.value = *_lastSlot; _success = true; } else { _kv.value = ( JudyValue ) 0; _success = false; } _kv.key = _buff[0]; return _kv; } /// retrieve the first key-value pair in the array const pair & begin() { JudyKey key = 0; _lastSlot = ( JudyValue * ) judy_strt( _judyarray, ( const unsigned char * ) &key, 0 ); return mostRecentPair(); } /// retrieve the last key-value pair in the array const pair & end() { _lastSlot = ( JudyValue * ) judy_end( _judyarray ); return mostRecentPair(); } /// retrieve the key-value pair for the next key in the array. const pair & next() { _lastSlot = ( JudyValue * ) judy_nxt( _judyarray ); return mostRecentPair(); } /// retrieve the key-value pair for the prev key in the array. const pair & previous() { _lastSlot = ( JudyValue * ) judy_prv( _judyarray ); return mostRecentPair(); } /** delete a key-value pair. If the array is not empty, * getLastValue() will return the entry before the one that was deleted * \sa isEmpty() */ bool removeEntry( JudyKey * key ) { if( judy_slot( _judyarray, key, _depth * JUDY_key_size ) ) { _lastSlot = ( JudyValue * ) judy_del( _judyarray ); return true; } else { return false; } } /// true if the array is empty bool isEmpty() { JudyKey key = 0; return ( ( judy_strt( _judyarray, ( const unsigned char * ) &key, _depth * JUDY_key_size ) ) ? false : true ); } }; #endif //JUDYLARRAY_H
<?php session_start(); if(isset($_SESSION['username'])) { include 'connectdb2.php'; $dispCategory = mysqli_real_escape_string($conn,$_GET['id']); $querys = "SELECT * FROM volunteers WHERE category =?"; $st = mysqli_prepare($conn,$querys); mysqli_stmt_bind_param($st,'s',$dispCategory); mysqli_stmt_execute($st); $result = mysqli_stmt_get_result($st); $users = mysqli_fetch_all($result, MYSQLI_ASSOC); } else { session_unset(); session_destroy(); header("Location: http://localhost/dbms_crud_website/log_out.php"); } ?>
package main import ( "fmt" "io" "log" "os" "path/filepath" "strings" "github.com/hpcloud/tail" stan "github.com/nats-io/go-nats-streaming" ) func getEnv(key, fallback string) string { value, exists := os.LookupEnv(key) if !exists { value = fallback } return value } func connectionCloser(c io.Closer) { if err := c.Close(); err != nil { log.Printf("close error: %s", err) } } func main() { clusterName := getEnv("CLUSTER_NAME", "test-cluster") natsServer := getEnv("NATS_SERVER", "nats://localhost:4222") natsClientName := getEnv("NATS_CLIENT_NAME", "tailnats") tailFile := getEnv("TAIL_FILE", "/var/log/test.log") if len(os.Args) > 1 { tailFile = os.Args[1] } natsSubject := strings.TrimSuffix(filepath.Base(tailFile), filepath.Ext(tailFile)) conn, err := stan.Connect( clusterName, natsClientName, stan.NatsURL(natsServer), ) if err != nil { log.Fatalf("error opening file: %v", err) } defer connectionCloser(conn) err = conn.Publish("natslog.subscribe", []byte(natsSubject)) if err != nil { log.Fatalf("error subscribing: %v", err) } t, err := tail.TailFile(tailFile, tail.Config{Follow: true}) for line := range t.Lines { perr := conn.Publish(natsSubject, []byte(fmt.Sprintf("%s\n", line.Text))) if perr != nil { log.Printf("Publish error %v", perr) } } }
export type BadgeModifiers = "pill" | "filled"; export type BadgeTypes = "success" | "warning" | "error"; export type BadgeProps = { className?: string; customStyles?: { [x: string]: any }; disableStyles?: boolean; modifier?: BadgeModifiers; type?: BadgeTypes; } & { [x: string]: any }; declare const Badge: React.RefForwardingComponent<HTMLDivElement, BadgeProps>; export default Badge;
#!/bin/bash psql createuser --createdb --no-createrole --no-superuser --no-password openhrms exit
import { styled } from "@styles"; import { keyframes } from "styled-components"; import { getContentWindowHeight } from "@utils/styles"; const firstItem = keyframes` 0% { left: 0; } 12.5% { left: 2rem; } 25% { left: 4rem; } 37.5% { left: 2rem; } 50% { left: 0; } 100% { left: 0; } `; const secondItem = keyframes` 0% { left: 2rem; } 12.5% { left: 2rem; } 25% { left: 4rem; } 37.5% { left: 2rem; } 62.5% { left: 2rem; } 75% { left: 0; } 87.5% { left: 2rem; } 100% { left: 2rem; } `; const thirdItem = keyframes` 0% { left: 4rem; } 50% { left: 4rem; } 62.5% { left: 2rem; } 75% { left: 0; } 87.5% { left: 2rem; } 100% { left: 4rem; } `; export const Wrapper = styled.div<{ fullScreen: boolean }>` display: flex; align-items: center; width: 100%; height: ${props => props.fullScreen ? `${getContentWindowHeight()}px` : "100%"}; padding: ${props => props.theme.spacing.spacer} 0; `; export const Items = styled.div` position: relative; width: 5rem; height: 1rem; margin: 0 auto; span { background-color: ${props => props.theme.colors.secondary}; width: 1rem; height: 1rem; border-radius: 1rem; position: absolute; &:nth-child(1) { left: 0; animation: ${firstItem} 2s infinite; animation-timing-function: linear; } &:nth-child(2) { left: 2rem; animation: ${secondItem} 2s infinite; animation-timing-function: linear; } &:nth-child(3) { right: 0; animation: ${thirdItem} 2s infinite; animation-timing-function: linear; } } `;
cpio === 用来建立、还原备份档的工具程序 ## 补充说明 **cpio命令** 主要是用来建立或者还原备份档的工具程序,cpio命令可以复制文件到归档包中,或者从归档包中复制文件。 ### 语法 ```shell cpio(选项) ``` ### 选项 ```shell -0或--null:接受新增列控制字符,通常配合find指令的“-print0”参数使用; -a或--rest-access-time:重新设置文件的存取时间; -A或--append:附加到已存在的备份文档中,且这个备份文档必须存放在磁盘上,而不能放置于磁带机里; -b或--awap:此参数的效果和同时指定“-ss”参数相同; -B:将输入/输出的区块大小改成5210Bytes; -c:使用旧ASCII备份格式; -C<区块大小>或--io-size=<区块大小>:设置输入/输出的区块大小,单位是Byte; -d或--make-directories:如有需要cpio会自行建立目录; -E<范本文件>或--pattern-file=<范本文件>:指定范本文件,其内含有一个或多个范本样式,让cpio解开符合范本条件的文件,格式为每列一个范本样式; -f或--nonmatching:让cpio解开所有不符合范本条件的文件; -F<备份档>或--file=<备份档>:指定备份档的名称,用来取代标准输入或输出,也能借此通过网络使用另一台主机的保存设备存取备份档; -H<备份格式>:指定备份时欲使用的文件格式; -i或--extract:执行copy-in模式,还原备份档; -l<备份档>:指定备份档的名称,用来取代标准输入,也能借此通过网络使用另一台主机的保存设备读取备份档; -k:此参数将忽略不予处理,仅负责解决cpio不同版本间的兼容性问题; -l或--link:以硬连接的方式取代复制文件,可在copy-pass模式下运用; -L或--dereference:不建立符号连接,直接复制该连接所指向的原始文件; -m或preserve-modification-time:不去更改文件的更改时间; -M<回传信息>或--message=<回传信息>:设置更换保存媒体的信息; -n或--numeric-uid-gid:使用“-tv”参数列出备份档的内容时,若再加上参数“-n”,则会以用户识别和群组识别码替代拥有者和群组名称列出文件清单; -o或--create:执行copy-out模式,建立备份档; -O<备份档>:指定备份档的名称,用来取代标准输出,也能借此通过网络使用另一台主机的保存设备存放备份档; -p或--pass-through:执行copy-pass模式,略过备份步骤,直接将文件复制到目的目录; -r或--rename:当有文件名称需要更改时,采用互动模式; -R<拥有者><:/.><所属群组>或----owner<拥有者><:/.><所属群组> 在copy-in模式还原备份档,或copy-pass模式复制文件时,可指定这些备份,复制的文件的拥有者与所属群组; -s或--swap-bytes:交换每队字节的内容; -S或--swap-halfwords:交换每半个字节的内容; -t或--list:将输入的内容呈现出来; -u或--unconditional:置换所有文件,不论日期时间的新旧与否,皆不予询问而直接覆盖; -v或--verbose:详细显示指令的执行过程; -V或--dot:执行指令时。在每个文件的执行程序前面加上“.”号; --block-size=<区块大小>:设置输入/输出的区块大小,假如设置数值为5,则区块大小为2500,若设置成10,则区块大小为5120,以此类推; --force-local:强制将备份档存放在本地主机; --help:在线帮助; --no-absolute-filenames:使用相对路径建立文件名称; --no-preserve-owner:不保留文件的拥有者,谁解开了备份档,那些文件就归谁所有; -only-verify-crc:当备份档采用CRC备份格式时,可使用这项参数检查备份档内的每个文件是否正确无误; --quiet:不显示复制了多少区块; --sparse:倘若一个文件内含有大量的连续0字节,则将此文件存在稀疏文件; --version:显示版本信息。 ``` ### 实例 **将`/etc`下的所有普通文件都备份到`/opt/etc.cpio`,使用以下命令:** ```shell find /etc –type f | cpio –ocvB >/opt/etc.cpio ``` **将系统上所有资料备份到磁带机内,使用以下命令:** ```shell find / -print | cpio -covB > /dev/st0 ``` 这里的`/dev/st0`是磁带的设备名,代表SCSI磁带机。 **查看上例磁带机上备份的文件,使用以下命令:** ```shell cpio -icdvt < /dev/st0 > /tmp/st_content ``` 有时可能因为备份的文件过多,一个屏幕无法显示完毕,此时我们利用下面命令,让磁带机的文件信息输出到文件。 **将示例1中的备份包还原到相应的位置,如果有相同文件进行覆盖,使用以下命令:** ```shell cpio –icduv < /opt/etc.cpio ``` 注意,cpio恢复的路径,如果cpio在打包备份的时候用的是绝对路径,那么在恢复的时候会自动恢复到这些绝对路径下,本例就会将备份文件全部还原到/etc路径下对应的目录中。同理,如果在打包备份用的是相对路径,还原时也将恢复到相对路径下。 通过上面的示例,可以看出,cpio无法直接读取文件,它需要每个文件或者目录的完整路径名才能识别读取,而find命令的输出刚好做到了这点,因此,cpio命令一般和find命令配合使用。其实,上面的示例我们已经看到了它们的组合用法。
import { fromJS } from 'immutable'; import * as Actions from './actions'; const initialState = fromJS({ todos: [], }); export default function todoReducer(state = initialState, action) { let todoIndex; switch(action.type){ case Actions.ADD_TODO: return state.update('todos', (todos) => todos.push(fromJS(action.todo))); case Actions.COMPLETE_TODO: todoIndex = state.get('todos').findIndex((todo) => todo.get('id') === action.id); return state.updateIn(['todos', todoIndex], (todo) => { return todo.set('complete', !todo.get('complete')); }); case Actions.REMOVE_TODO: todoIndex = state.get('todos').findIndex((todo) => todo.get('id') === action.id); return state.deleteIn(['todos', todoIndex]); default: return state; } };
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.Background; namespace NittyGritty.Uwp.Activation.Operations { public abstract class BackgroundTask { public BackgroundTask(string name = null) { Name = name ?? GetType().FullName; } public string Name { get; } public virtual void Register(BackgroundTaskBuilder builder) { builder.Register(); } public abstract Task Run(IBackgroundTaskInstance taskInstance); } }
/** * Copyright (c) 2011-2016, James Zhan 詹波 (jfinal@126.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jfinal.ext.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jfinal.handler.Handler; import com.jfinal.kit.StrKit; /** * Provide a context path to view if you need. * <br> * Example:<br> * In JFinalFilter: handlers.add(new ContextPathHandler("CONTEXT_PATH"));<br> * in freemarker: <img src="${BASE_PATH}/images/logo.png" /> */ public class ContextPathHandler extends Handler { private String contextPathName; public ContextPathHandler() { contextPathName = "CONTEXT_PATH"; } public ContextPathHandler(String contextPathName) { if (StrKit.isBlank(contextPathName)) throw new IllegalArgumentException("contextPathName can not be blank."); this.contextPathName = contextPathName; } public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { request.setAttribute(contextPathName, request.getContextPath()); next.handle(target, request, response, isHandled); } }
# f_shake_animation_widget 原作者: https://pub.dev/packages/shake_animation_widget ## Getting Started shake_animation_widget 空安全版本 ### 抖动Widget: ShakeAnimationWidget ```dart /// 抖动动画控制器 final ShakeAnimationController _shakeAnimationController = ShakeAnimationController(); /// 构建抖动效果 ShakeAnimationWidget buildShakeAnimationWidget() { return ShakeAnimationWidget( // 抖动控制器 shakeAnimationController: _shakeAnimationController, // 微旋转的抖动 shakeAnimationType: ShakeAnimationType.skew, // 设置不开启抖动 isForward: false, // 默认为 0 无限执行 shakeCount: 0, // 抖动的幅度 取值范围为[0,1] shakeRange: 0.2, // 执行抖动动画的子Widget child: ElevatedButton( child: const Text( '测试', style: TextStyle(color: Colors.white), ), onPressed: () { // 判断抖动动画是否正在执行 if (_shakeAnimationController.animationRunning) { // 停止抖动动画 _shakeAnimationController.stop(); } else { // 开启抖动动画 // 参数shakeCount 用来配置抖动次数 // 通过 controller start 方法默认为 1 _shakeAnimationController.start(shakeCount: 1); } }, ), ); } ``` ### 仿开源中国自定义底部菜单 ```dart buildBottomRoundFlowMenu() { return BottomRoundFlowMenu( // 子菜单按钮选项 iconList: iconList, // 子菜单按钮的点击事件回调 clickCallback: (int index) { print("点击了按钮$index"); }, ); } ``` ### 动画按钮 ```dart /// 抖动动画控制器 final ShakeAnimationController _shakeAnimationController = ShakeAnimationController(); /// 构建抖动效果 ShakeAnimationWidget buildShakeAnimationWidget() { return ShakeAnimationWidget( // 抖动控制器 shakeAnimationController: _shakeAnimationController, // 微旋转的抖动 shakeAnimationType: ShakeAnimationType.skew, // 设置不开启抖动 isForward: false, // 默认为 0 无限执行 shakeCount: 0, // 抖动的幅度 取值范围为[0,1] shakeRange: 0.2, // 执行抖动动画的子Widget child: ElevatedButton( child: const Text( '测试', style: TextStyle(color: Colors.white), ), onPressed: () { // 判断抖动动画是否正在执行 if (_shakeAnimationController.animationRunning) { // 停止抖动动画 _shakeAnimationController.stop(); } else { // 开启抖动动画 // 参数shakeCount 用来配置抖动次数 // 通过 controller start 方法默认为 1 _shakeAnimationController.start(shakeCount: 1); } }, ), ); } ``` ### 垂直向上弹出菜单 ```dart /// 垂直向上弹出菜单 buildRoteFloatingButton() { return RoteFloatingButton( // 子菜单按钮选项 iconList: iconList, // 子菜单按钮的点击事件回调 clickCallback: (int index) { print("点击了按钮$index"); }, ); } ```
#include <ssm_lht_ref.h> int ssm_lht_cmp(void *va, void *vb) { ssm_lhtcmp a = va; ssm_lhtcmp b = vb; return memcmp(a->key, b, a->len); }
<?php declare(strict_types=1); /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @link https://phpdoc.org */ namespace phpDocumentor\Compiler\Linker; use phpDocumentor\Compiler\CompilerPassInterface; use phpDocumentor\Descriptor\ClassDescriptor; use phpDocumentor\Descriptor\Collection; use phpDocumentor\Descriptor\Descriptor; use phpDocumentor\Descriptor\DescriptorAbstract; use phpDocumentor\Descriptor\FileDescriptor; use phpDocumentor\Descriptor\InterfaceDescriptor; use phpDocumentor\Descriptor\NamespaceDescriptor; use phpDocumentor\Descriptor\ProjectDescriptor; use phpDocumentor\Descriptor\TraitDescriptor; use phpDocumentor\Reflection\Fqsen; use phpDocumentor\Reflection\Type; use Webmozart\Assert\Assert; use function get_class; use function is_array; use function is_iterable; use function is_object; use function is_string; use function spl_object_hash; use function ucfirst; /** * The linker contains all rules to replace FQSENs in the ProjectDescriptor with aliases to objects. * * This object contains a list of class FQCNs for Descriptors and their associated linker rules. * * An example scenario should be: * * The Descriptor ``\phpDocumentor\Descriptor\ClassDescriptor`` has a *Substitute* rule determining that the * contents of the ``Parent`` field should be substituted with another ClassDescriptor with the FQCN * represented by the value of the Parent field. In addition (second element) it has an *Analyse* rule * specifying that the contents of the ``Methods`` field should be interpreted by the linker. Because that field * contains an array or Descriptor Collection will each element be analysed by the linker. * * As can be seen in the above example is it possible to analyse a tree structure and substitute FQSENs where * encountered. */ class Linker implements CompilerPassInterface { public const COMPILER_PRIORITY = 10000; /** @var array<class-string, array<string>> */ private $substitutions; /** @var string[] Prevent cycles by tracking which objects have been analyzed */ private $processedObjects = []; /** @var DescriptorRepository */ private $descriptorRepository; public function getDescription(): string { return 'Replace textual FQCNs with object aliases'; } /** * Initializes the linker with a series of Descriptors to link to. * * @param array<class-string, array<string>> $substitutions */ public function __construct(array $substitutions, DescriptorRepository $descriptorRepository) { $this->substitutions = $substitutions; $this->descriptorRepository = $descriptorRepository; } public function execute(ProjectDescriptor $project): void { $this->descriptorRepository->setObjectAliasesList($project->getIndexes()->elements->getAll()); $this->substitute($project); } /** * Returns the list of substitutions for the linker. * * @return string[][] */ public function getSubstitutions(): array { return $this->substitutions; } /** * Substitutes the given item or its children's FQCN with an object alias. * * This method may do either of the following depending on the item's type * * FQSEN or String * If the given item is a string then this method will attempt to find an appropriate Class, Interface or * TraitDescriptor object and return that. See {@see DescriptorRepository::findAlias()} for more information * on the normalization of these strings. * * Array or Traversable * Iterate through each item, pass each key's contents to a new call to substitute and replace the key's * contents if the contents is not an object (objects automatically update and this saves performance). * * Object * Determines all eligible substitutions using the substitutions property, construct a getter and retrieve * the field's contents. Pass these contents to a new call of substitute and use a setter to replace the field's * contents if anything other than null is returned. * * The Container is a descriptor that acts as container for all elements underneath or null if there is no current * container. * * This method will return null if no substitution was possible and all of the above should not update the parent * item when null is passed. * * @param string|Fqsen|Type|Collection<mixed>|array<mixed>|Descriptor $item * * @return string|DescriptorAbstract|Collection<string|DescriptorAbstract>|array<string|DescriptorAbstract>|null */ public function substitute($item, ?DescriptorAbstract $container = null) { if ($item instanceof Type) { return null; } if ($item instanceof Fqsen) { return $this->descriptorRepository->findAlias((string) $item, $container); } if (is_string($item)) { return $this->descriptorRepository->findAlias($item, $container); } if (is_iterable($item)) { Assert::true(is_array($item) || $item instanceof Collection); return $this->substituteChildrenOfCollection($item, $container); } if (!is_object($item)) { return null; } $this->substituteMembersOfObject($item, $container); return null; } /** * @param array<string|DescriptorAbstract>|Collection<string|DescriptorAbstract> $collection * * @return array<string|DescriptorAbstract>|Collection<string|DescriptorAbstract>|null */ private function substituteChildrenOfCollection(iterable $collection, ?DescriptorAbstract $container): ?iterable { $isModified = false; foreach ($collection as $key => $element) { $element = $this->substitute($element, $container); if ($element === null) { continue; } $isModified = true; $collection[$key] = $element; } if ($isModified) { return $collection; } return null; } /** * Returns the value of a field in the given object. * * @return string|object */ private function findFieldValue(object $object, string $fieldName) { $getter = 'get' . ucfirst($fieldName); return $object->{$getter}(); } /** * Returns true if the given Descriptor is a container type. * * @psalm-assert DescriptorAbstract $item */ private function isDescriptorContainer(object $item): bool { return $item instanceof FileDescriptor || $item instanceof NamespaceDescriptor || $item instanceof ClassDescriptor || $item instanceof TraitDescriptor || $item instanceof InterfaceDescriptor; } private function substituteMembersOfObject(object $object, ?DescriptorAbstract $container): void { $hash = spl_object_hash($object); if (isset($this->processedObjects[$hash])) { // if analyzed; just return null to indicate processing is already done return; } $newContainer = $this->isDescriptorContainer($object) ? $object : $container; $this->processedObjects[$hash] = $hash; $objectClassName = get_class($object); $fieldNames = $this->substitutions[$objectClassName] ?? []; foreach ($fieldNames as $fieldName) { $fieldValue = $this->findFieldValue($object, $fieldName); $response = $this->substitute($fieldValue, $newContainer); if ($response === null) { continue; } // TODO Can we find another solution for this? $setter = 'set' . ucfirst($fieldName); $object->{$setter}($response); } } }
#!/usr/bin/env python from urllib.parse import urljoin import httpretty import os import unittest # import urlparse import ari import requests class AriTestCase(unittest.TestCase): """Base class for mock ARI server. """ BASE_URL = "http://ari.py/ari" def setUp(self): """Setup httpretty; create ARI client. """ super(AriTestCase, self).setUp() httpretty.enable() self.serve_api() self.uut = ari.connect('http://ari.py/', 'test', 'test') def tearDown(self): """Cleanup. """ super(AriTestCase, self).tearDown() httpretty.disable() httpretty.reset() @classmethod def build_url(cls, *args): """Build a URL, based off of BASE_URL, with the given args. >>> AriTestCase.build_url('foo', 'bar', 'bam', 'bang') 'http://ari.py/ari/foo/bar/bam/bang' :param args: URL components :return: URL """ url = cls.BASE_URL for arg in args: # url = urlparse.urljoin(url + '/', arg) url = urljoin(url + '/', arg) return url def serve_api(self): """Register all api-docs with httpretty to serve them for unit tests. """ for filename in os.listdir('sample-api'): if filename.endswith('.json'): with open(os.path.join('sample-api', filename)) as fp: body = fp.read() self.serve(httpretty.GET, 'api-docs', filename, body=body) def serve(self, method, *args, **kwargs): """Serve a single URL for current test. :param method: HTTP method. httpretty.{GET,PUT,POST,DELETE}. :param args: URL path segments. :param kwargs: See httpretty.register_uri() """ url = self.build_url(*args) if kwargs.get('body') is None and 'status' not in kwargs: kwargs['status'] = requests.codes.no_content httpretty.register_uri(method, url, content_type="application/json", **kwargs)
alias Euler alias zerosd (reg) { pxor reg, reg } alias reset () { mov count, len mov psrc, src mov pdst, dst alias zerosd (temp1) } Euler: alias [linux] { alias src, rdi alias dst, rsi alias len, edx } alias [windows] { alias src, rcx alias dst, rdx alias len, r8d } alias EulerCount, xmm0 alias EulerStep, xmm1 alias EulerMax, xmm2 alias EulerHalf, xmm3 alias temp1, xmm4 alias temp2, xmm5 alias count, r9d alias psrc, r10 alias pdst, r11 alias Kolmogorov, L10 alias Leave_Kolmogorov, L11 alias Kolmogorov2, L12 alias Leave_Kolmogorov2, L13 alias QuitProcedure, L14 movsd EulerStep, [dst] movsd EulerMax, 8[dst] movsd EulerHalf, 16[dst] alias zerosd (EulerCount) alias reset() .Kolmogorov: movsd temp2, 16[psrc] movsd [pdst], temp2 add pdst, 8 movsd temp2, [psrc] addsd temp2, 8[psrc] mulsd temp2, 16[psrc] subsd temp1, temp2 add psrc, 24 sub count, 1 cmp count, 1 jl .Leave_Kolmogorov movsd temp2, 8[psrc] mulsd temp2, 16[psrc] addsd temp2, temp1 movsd [pdst], temp2 add pdst, 8 movsd temp1, -16[pdst] mulsd temp2, EulerStep addsd temp1, temp2 movsd [pdst], temp1 add pdst, 8 movsd temp1, -24[psrc] mulsd temp1, -8[psrc] jmp .Kolmogorov .Leave_Kolmogorov: alias reset() .Kolmogorov2: movsd temp2, [psrc] addsd temp2, 8[psrc] mulsd temp2, 16[pdst] subsd temp1, temp2 add psrc, 24 add pdst, 24 sub count, 1 cmp count, 1 jl .Leave_Kolmogorov2 movsd temp2, 8[psrc] mulsd temp2, 16[pdst] addsd temp2, temp1 addsd temp2, -16[pdst] mulsd temp2, EulerHalf addsd temp2, -24[pdst] movsd -8[psrc], temp2 movsd temp1, -24[psrc] mulsd temp1, -8[pdst] jmp .Kolmogorov2 .Leave_Kolmogorov2: addsd EulerCount, EulerStep ucomisd EulerMax, EulerCount jbe .QuitProcedure alias reset() jmp .Kolmogorov .QuitProcedure: movsd [dst], EulerStep movsd 8[dst], EulerMax movsd 16[dst], EulerHalf ret
# Docker Essentials Image A Docker image with essential tooling for development and CI/CD. ## Installed Packages - bash - gawk - sed - grep - bc - coreutils - openssh-client - curl - rsync - ncftp - git
<?php // * @copyright OPENCART.PRO 2011 - 2017. // * @forum http://forum.opencart.pro // * @source See SOURCE.txt for source and other copyright. // * @license GNU General Public License version 3; see LICENSE.txt class ControllerExtensionModuleGoogleHangouts extends Controller { public function index() { $this->load->language('extension/module/google_hangouts'); $data['heading_title'] = $this->language->get('heading_title'); if ($this->request->server['HTTPS']) { $data['code'] = str_replace('http', 'https', html_entity_decode($this->config->get('google_hangouts_code'))); } else { $data['code'] = html_entity_decode($this->config->get('google_hangouts_code')); } return $this->load->view('extension/module/google_hangouts', $data); } }
class Streams::ParentChild::LinksProcessor def self.update_parent_and_sort_siblings(edition, parent_warehouse_id) new(edition, parent_warehouse_id).update_parent_and_sort_siblings end def initialize(edition, parent_warehouse_id) @edition = edition @parent_warehouse_id = parent_warehouse_id end def update_parent_and_sort_siblings children = get_children update_parent_and_sort(children) unless children.empty? parent = get_parent Streams::ParentChild::LinksProcessor.update_parent_and_sort_siblings(parent, nil) unless parent.nil? end private attr_reader :edition, :parent_warehouse_id def get_children Dimensions::Edition.where(warehouse_item_id: edition.child_sort_order, live: true) end def get_parent Dimensions::Edition.where(warehouse_item_id: parent_warehouse_id, live: true).first end def update_parent_and_sort(children) children.each do |child| child.update(parent: @edition, sibling_order: sort_order_for(child.warehouse_item_id)) end end def sort_order_for(warehouse_item_id) edition.child_sort_order.find_index(warehouse_item_id) + 1 end end
package com.github.roarappstudio.btkontroller.reports import kotlin.experimental.and import kotlin.experimental.or @Suppress("EXPERIMENTAL_FEATURE_WARNING") inline class ScrollableTrackpadMouseReport ( val bytes: ByteArray = ByteArray(7) {0} ) { var leftButton: Boolean get() = bytes[0] and 0b1 != 0.toByte() set(value) { bytes[0] = if (value) bytes[0] or 0b1 else bytes[0] and 0b110 } var rightButton: Boolean get() = bytes[0] and 0b10 != 0.toByte() set(value) { bytes[0] = if (value) bytes[0] or 0b10 else bytes[0] and 0b101 } var dxLsb: Byte get() = bytes[1] set(value) { bytes[1] = value } var dxMsb: Byte get() = bytes[2] set(value) { bytes[2] = value } var dyLsb: Byte get() = bytes[3] set(value) { bytes[3] = value } var dyMsb: Byte get() = bytes[4] set(value) { bytes[4] = value } var vScroll : Byte get() = bytes[5] set(value) { bytes[5]=value } var hScroll : Byte get() = bytes[6] set(value) { bytes[6]=value } fun reset() = bytes.fill(0) companion object { const val ID = 4 } }
import logging import os import subprocess import urllib.request UNIT_FILE_PAYLOAD = """\ [Unit] Description=C Camera Recorder Service StartLimitInterval=400 StartLimitBurst=5 [Service] Type=simple ExecStart=/usr/local/bin/ccam Restart=always RestartSec=30 WatchdogSec=60 KillMode=process User=pi Group=pi [Install] WantedBy=multi-user.target """ FILENAME_FOR_UNITFILE = "ccam.service" PATH_FOR_UNITFILE = "/etc/systemd/system" unitfile_fullpath = "%s/%s" % (PATH_FOR_UNITFILE, FILENAME_FOR_UNITFILE) WEB_FILE_PATH = os.environ.get("S3_BUCKET_ARTIFACTS") + "/ccam" LOCAL_FILE_PATH = "/usr/local/bin/ccam" COMMANDS_TO_START_AND_ENABLE_SERVICE = [ ["systemctl", "daemon-reload"], ["systemctl", "enable", FILENAME_FOR_UNITFILE], ["systemctl", "start", FILENAME_FOR_UNITFILE], ] COMMANDS_TO_RESTART_SERVICE = [ ["systemctl", "restart", FILENAME_FOR_UNITFILE], ] if not os.path.exists(unitfile_fullpath): logging.info( "unitfile_fullpath %s does not exist, continuing with systemd install", unitfile_fullpath, ) # copy in binary logging.info("copying in binary from url %s", WEB_FILE_PATH) urllib.request.urlretrieve(WEB_FILE_PATH, LOCAL_FILE_PATH) logging.info("creating unitfile at path %s", unitfile_fullpath) # write unit file with open(unitfile_fullpath, "w") as f: f.write(UNIT_FILE_PAYLOAD) # enable unit file for command in COMMANDS_TO_START_AND_ENABLE_SERVICE: logging.info("running command to start and enable services %s", repr(command)) subprocess.check_output(command)
# Scatterplot Charts Basic Scatterplot Chart ```javascript render() { let data = [ [{ "title": "Amapá", "rating": 4.47, "episode": 0 }, { "title": "Santa Catarina", "rating": 3.3, "episode": 1 }, { "title": "Minas Gerais", "rating": 6.46, "episode": 2 }, { "title": "Amazonas", "rating": 3.87, "episode": 3 }, { "title": "Mato Grosso do Sul", "rating": 2.8, "episode": 4 }, { "title": "Mato Grosso do Sul", "rating": 2.05, "episode": 5 }, { "title": "Tocantins", "rating": 7.28, "episode": 6 }, { "title": "Roraima", "rating": 5.23, "episode": 7 }, { "title": "Roraima", "rating": 7.76, "episode": 8 }, { "title": "Amazonas", "rating": 2.26, "episode": 9 }, { "title": "Mato Grosso do Sul", "rating": 2.46, "episode": 10 }, { "title": "Santa Catarina", "rating": 7.59, "episode": 11 }, { "title": "Acre", "rating": 3.74, "episode": 12 }, { "title": "Amapá", "rating": 5.03, "episode": 13 }, { "title": "Paraíba", "rating": 4.16, "episode": 14 }, { "title": "Mato Grosso", "rating": 0.81, "episode": 15 }, { "title": "Rio de Janeiro", "rating": 3.01, "episode": 16 }, { "title": "Rio de Janeiro", "rating": 0, "episode": 17 }, { "title": "Distrito Federal", "rating": 5.46, "episode": 18 }, { "title": "São Paulo", "rating": 9.71, "episode": 19 }, { "title": "Mato Grosso", "rating": 7.9, "episode": 20 }, { "title": "Tocantins", "rating": 4.2, "episode": 21 }, { "title": "Amapá", "rating": 6, "episode": 22 }, { "title": "Paraná", "rating": 7.99, "episode": 23 }, { "title": "Mato Grosso do Sul", "rating": 1.07, "episode": 24 }, { "title": "Tocantins", "rating": 1.42, "episode": 25 }, { "title": "Paraná", "rating": 5.94, "episode": 26 }, { "title": "Maranhão", "rating": 3.17, "episode": 27 }, { "title": "Maranhão", "rating": 1.58, "episode": 28 }, { "title": "Rondônia", "rating": 6.12, "episode": 29 }, { "title": "Roraima", "rating": 7.28, "episode": 30 }, { "title": "Mato Grosso", "rating": 4.74, "episode": 31 }, { "title": "Roraima", "rating": 1.47, "episode": 32 }, { "title": "Alagoas", "rating": 9, "episode": 33 }, { "title": "Amazonas", "rating": 0.43, "episode": 34 }, { "title": "Mato Grosso do Sul", "rating": 8.61, "episode": 35 }, { "title": "Tocantins", "rating": 0.6, "episode": 36 }, { "title": "Maranhão", "rating": 9.62, "episode": 37 }, { "title": "Rio de Janeiro", "rating": 4.79, "episode": 38 }, { "title": "Santa Catarina", "rating": 7.71, "episode": 39 }, { "title": "Piauí", "rating": 3.83, "episode": 40 }, { "title": "Pernambuco", "rating": 8.19, "episode": 41 }, { "title": "Bahia", "rating": 6.98, "episode": 42 }, { "title": "Minas Gerais", "rating": 4.52, "episode": 43 }] ] let options = { width: 290, height: 290, r: 2, margin: { top: 20, left: 40, bottom: 30, right: 30 }, fill: "#2980B9", stroke: "#3E90F0", animate: { type: 'delayed', duration: 200 }, label: { fontFamily: 'Arial', fontSize: 8, fontWeight: true, fill: '#34495E' }, axisX: { showAxis: true, showLines: true, showLabels: true, showTicks: true, zeroAxis: false, orient: 'bottom', label: { fontFamily: 'Arial', fontSize: 8, fontWeight: true, fill: '#34495E' } }, axisY: { showAxis: true, showLines: true, showLabels: true, showTicks: true, zeroAxis: false, orient: 'left', label: { fontFamily: 'Arial', fontSize: 8, fontWeight: true, fill: '#34495E' } } } return ( <View> <Scatterplot data={data} options={options} xKey="episode" yKey="rating" /> </View> ) } ```
package org.jetbrains.plugins.scala.lang.structureView.element import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.psi.PsiElement import org.jetbrains.plugins.scala.lang.psi.api.statements.ScExtension import org.jetbrains.plugins.scala.lang.psi.api.statements.params.ScParameterClause import org.jetbrains.plugins.scala.lang.structureView.element.Extension.clauseText // TODO: improve in SCL-19224 // - inherited extensions final class Extension(extension: ScExtension) extends AbstractTreeElementDelegatingChildrenToPsi(extension) { override def getPresentableText: String = { val typeParameters = extension.typeParametersClause.fold("")(_.getTextByStub) val parametersText = extension.allClauses.map(clauseText).mkString s"extension $typeParameters$parametersText" } override protected def location: Option[String] = None // TODO: extension can be inherited override def getTextAttributesKey: TextAttributesKey = super.getTextAttributesKey override protected def children: Seq[PsiElement] = extension.extensionMethods override def isAlwaysLeaf: Boolean = false override def isAlwaysShowsPlus: Boolean = super.isAlwaysShowsPlus } object Extension { private def clauseText(paramsClause: ScParameterClause): String = { val prefix = if (paramsClause.isUsing) "?=> " else "" val parametersTexts = paramsClause.parameters.map(p => s"${p.typeElement.fold("")(_.getText)}") "(" + prefix + parametersTexts.mkString(", ") + ")" } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EquipmentManagement.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace EquipmentManagement.Controllers { public class AutoClaveRoomsController : Controller { [Authorize(Roles = Pages.MainMenu.ACR_PumpOnGround.RoleName)] public IActionResult PumpOnGround() { return View(); } [Authorize(Roles = Pages.MainMenu.ACR_ShihlinCtrl.RoleName)] public IActionResult ShihlinCtrl() { return View(); } [Authorize(Roles = Pages.MainMenu.ACR_SteamSterilizerMSTV.RoleName)] public IActionResult SteamSterilizerMSTV() { return View(); } } }
package cc.uncarbon.framework.rocketmq.core.serializer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import java.io.IOException; /** * 基于 Jackson JSON 的 MQ Message 序列化器 * * @author Uncarbon */ @Slf4j public class JacksonJsonSerializer implements RocketSerializer { private final ObjectMapper objectMapper = new ObjectMapper(); @Override public <T> byte[] serialize(T object) { if (object != null) { try { return objectMapper.writeValueAsBytes(object); } catch (JsonProcessingException jpe) { log.error("[Rocket MQ-Aliyun][JacksonJsonSerializer] 序列化时发生异常 >> 堆栈", jpe); } } return new byte[0]; } @Override public <T> T deSerialize(byte[] bytes, Class<T> clazz) { if (bytes.length > 0 && clazz != null) { try { return objectMapper.readValue(bytes, clazz); } catch (IOException e) { log.error("[Rocket MQ-Aliyun][JacksonJsonSerializer] 反序列化时发生异常 >> 堆栈", e); } } return null; } }
/* * Scala (https://www.scala-lang.org) * * Copyright EPFL and Lightbend, Inc. * * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package scala.tools.nsc.symtab.classfile trait DataReader { def bp: Int def bp_=(i: Int): Unit /** read a byte */ @throws(classOf[IndexOutOfBoundsException]) def nextByte: Byte /** read some bytes */ def nextBytes(len: Int): Array[Byte] /** read a character */ def nextChar: Char /** read an integer */ def nextInt: Int /** extract a character at position bp from buf */ def getChar(mybp: Int): Char /** extract an integer at position bp from buf */ def getByte(mybp: Int): Byte def getBytes(mybp: Int, bytes: Array[Byte]): Unit /** extract an integer at position bp from buf */ def getInt(mybp: Int): Int /** extract a long integer at position bp from buf */ def getLong(mybp: Int): Long /** extract a float at position bp from buf */ def getFloat(mybp: Int): Float /** extract a double at position bp from buf */ def getDouble(mybp: Int): Double def getUTF(mybp: Int, len: Int): String /** skip next 'n' bytes */ def skip(n: Int): Unit }
<?php namespace Admingenerator\GeneratorBundle\Builder\Admin; use Admingenerator\GeneratorBundle\Generator\Column; use Admingenerator\GeneratorBundle\Generator\Action; use Admingenerator\GeneratorBundle\Generator\Action\Generic\ExcelAction; /** * This builder generates php for list actions * * @author cedric Lombardot * @author Piotr Gołębiewski <loostro@gmail.com> * @author Stéphane Escandell <stephane.escandell@gmail.com> */ class ListBuilder extends BaseBuilder { /** * @var array */ protected $excelActions = null; /** * @var array */ protected $batchActions = null; /** * @var array */ protected $scopeColumns = null; /** * @var array */ protected $filterColumns = null; /** * (non-PHPdoc) * @see Admingenerator\GeneratorBundle\Builder.BaseBuilder::getYamlKey() */ public function getYamlKey() { return 'list'; } /** * Retrieve the FQCN formType used by this builder * * @return string */ public function getFormType() { return sprintf( '%s%s\\Form\Type\\%s\\FiltersType', $this->getVariable('namespace_prefix') ? $this->getVariable('namespace_prefix') . '\\' : '', $this->getVariable('bundle_name'), $this->getBaseGeneratorName() ); } public function getFilterColumns() { if (null === $this->filterColumns) { $this->filterColumns = array(); $this->findFilterColumns(); } return $this->filterColumns; } protected function findFilterColumns() { $columnsName = $this->getVariable('filters'); $fromFilterConfiguration = true; if (null === $columnsName) { $fromFilterConfiguration = false; $columnsName = $this->getAllFields(); } foreach ($columnsName as $columnName) { $column = $this->createColumn($columnName, true); if ($fromFilterConfiguration || $column->isFilterable()) { $this->addFilterColumn($column); } } } protected function addFilterColumn(Column $column) { $this->filterColumns[$column->getName()] = $column; } public function getFilterColumnsCredentials() { $credentials = array(); foreach($this->getFilterColumns() as $column) { if (! $filterCredentials = $column->getFiltersCredentials()) { // If one column has no Credentials constraint, we always // have to display the filter panel return array(); } $credentials[] = $filterCredentials; } return $credentials; } /** * Find scopes parameters */ public function getScopes() { return $this->getGenerator()->getFromYaml('builders.list.params.scopes'); } /** * @return array */ public function getScopeColumns() { if (null === $this->scopeColumns) { $this->scopeColumns = array(); $this->findScopeColumns(); } return $this->scopeColumns; } protected function findScopeColumns() { foreach ($this->getScopesDisplayColumns() as $columnName) { $column = $this->createColumn($columnName, true); // Set the user parameters $this->addScopeColumn($column); } } /** * @return array Scopes display column names */ protected function getScopesDisplayColumns() { $scopeGroups = $this->getGenerator()->getFromYaml('builders.list.params.scopes', array()); $scopeColumns = array(); foreach ($scopeGroups as $scopeGroup) { foreach ($scopeGroup as $scopeFilter) { if (array_key_exists('filters', $scopeFilter) && is_array($scopeFilter['filters'])) { foreach ($scopeFilter['filters'] as $field => $value) { $scopeColumns[] = $field; } } } } return $scopeColumns; } protected function addScopeColumn(Column $column) { $this->scopeColumns[$column->getName()] = $column; } /** * Return a list of batch action from list.batch_actions * @return array */ public function getBatchActions() { if (null === $this->batchActions) { $this->batchActions = array(); $this->findBatchActions(); } return $this->batchActions; } protected function setUserBatchActionConfiguration(Action $action) { $batchActions = $this->getVariable('batch_actions', array()); $builderOptions = is_array($batchActions) && array_key_exists($action->getName(), $batchActions) ? $batchActions[$action->getName()] : array(); $globalOptions = $this->getGenerator()->getFromYaml( 'params.batch_actions.'.$action->getName(), array() ); if (null !== $builderOptions) { foreach ($builderOptions as $option => $value) { $action->setProperty($option, $value); } } elseif (null !== $globalOptions) { foreach ($globalOptions as $option => $value) { $action->setProperty($option, $value); } } } protected function addBatchAction(Action $action) { $this->batchActions[$action->getName()] = $action; } protected function findBatchActions() { $batchActions = $this->getVariable('batch_actions', array()); foreach ($batchActions as $actionName => $actionParams) { $action = $this->findBatchAction($actionName); if (!$action) { $action = new Action($actionName); } if ($globalCredentials = $this->getGenerator()->getFromYaml('params.credentials')) { // If generator is globally protected by credentials // batch actions are also protected $action->setCredentials($globalCredentials); } $this->setUserBatchActionConfiguration($action); $this->addBatchAction($action); } } /** * Return a list of actions from excel.export * * @return array */ public function getExcelActions() { if (null === $this->excelActions) { $this->excelActions = array(); $this->fillExportActions(); } return $this->excelActions; } protected function fillExportActions() { $export = $this->getGenerator()->getFromYaml('builders.excel.params.export', []); if (!count($export)) return; foreach ($export as $keyName => $params ) { if (!isset($params['show_button']) || (isset($params['show_button']) && filter_var($params['show_button'], FILTER_VALIDATE_BOOLEAN))) { $action = new ExcelAction($keyName, $this); $action->setCredentials($this->getExportParamsForKey($keyName, 'credentials', 'AdmingenAllowed')); $action->setClass($this->getExportParamsForKey($keyName, 'class', 'btn-info')); $action->setIcon($this->getExportParamsForKey($keyName, 'icon', 'fa-file-excel-o')); $action->setLabel($this->getExportParamsForKey($keyName, 'label', 'action.generic.excel')); $this->excelActions[$keyName] = $action; } } } public function getExportParamsForKey($key, $name, $default) { if (!$key) return $default; $export = $this->getGenerator()->getFromYaml('builders.excel.params.export', []); if (!count($export) || !isset($export[$key]) || !count($export[$key]) || !isset($export[$key][$name])) return $default; return $export[$key][$name]; } }
package io.vaan.asare import io.gatling.core.Predef._ import io.gatling.http.Predef._ import io.gatling.http.request._ import scala.concurrent.duration._ import scala.util.Random class LoadSimulation extends Simulation { import LoadSimulation.genRebalanceV3Request val users = System.getProperty("users", "1").toInt val baseUrl = System.getProperty("url", "http://localhost:8090") val scn = scenario("rebalance v3") .exec( repeat(10) { exec( http("rebalance v3 request") .post(baseUrl + "/v3/rebel/rebalance") .body(StringBody(_ => genRebalanceV3Request)) .header("Content-Type", "application/json") ).pause(1 second, 2 seconds) } ) setUp( scn.inject(rampUsers(users) during (10 seconds)) ) } object LoadSimulation { def genRebalanceV3Request: String = { def genBetween: Double = Random.between(10_000, 100_000) val allocation: (Int, Int, Int) = { val a1: Int = Random.between(25, 40) val a2: Int = Random.between(25, 40) val a3: Int = 100 - (a1 + a2) (a1, a2, a3) } s""" { "currentPortfolio": { "A": $genBetween, "B": $genBetween, "C": $genBetween }, "requiredAllocation": { "A": ${allocation._1}, "B": ${allocation._2}, "C": ${allocation._3} } } """ } }
package slogo.exceptions; import slogo.visualcontroller.ErrorSeverity; /** * Exception is thrown when there is an Invalid XML Configuration file, for configuring aesthetics. * @author Alex Xu */ public class InvalidXMLConfigException extends LogicalException { private static final String message = "Could not configure XML"; public InvalidXMLConfigException() { super(); this.myErrorSeverity = ErrorSeverity.CRITICAL; this.myString = message; } @Override public ErrorSeverity getErrorSeverity() { return this.myErrorSeverity; } }
# Represents a path in an SVG drawing class Plottr::Path < Plottr::Object tag_type "path" attr_accessor :d, :fill, :stroke options :d, :fill, :stroke def initialize(hsh={}) self.d = "" super(hsh) end def origin= p self.d = "M#{p[0]},#{p[1]}" end def line p self.d += " L#{p[0]},#{p[1]}" end def close self.d += " z" end end
/* * MIT License * * Copyright (c) 2020-2021 KhoaTran Programmer * * 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. */ /****************** * VERSION: 1.1.9 * *****************/ /******************************************************************** * PURPOSE * ******************************************************************** * This file is the main function of KOCQLauncher. It manipulates * * all of Plugins * *******************************************************************/ /******************************************************************** * VERSION HISTORY * ******************************************************************** * 1.0.0: Apr-05-2020 * * Initial version uses KOCQPluginManager to load all of * * Plugins * * 1.1.0: May-25-2020 * * Support to load Plugins for Android: KOCQDraw, KOCQPics * * June-04-2020 * * Fix library location for Windows * * June-13-2020 * * Support to load Plugins for Android: KOCQQrcode * * 1.1.1: Aug-10-2020 * * Support to load Plugins for Windows by setting correct * * plugin name * * 1.1.2: Aug-17-2020 * * Support to load Plugins KOCQSegmentation for Windows * * 1.1.3: Aug-22-2020 * * Support to load Plugins KOCQAKAZE for Windows * * 1.1.4: Aug-25-2020 * * Support to load Plugins KOCQHISTOGRAM for Windows * * 1.1.5: Aug-26-2020 * * Support to load Plugins KOCQAffine for Windows * * 1.1.6: Aug-29-2020 * * Support to load Plugins KOCQFaceDetection for Windows * * 1.1.7: Jan-24-2021 * * Support to load Plugins KOCQSegmentation for Android * * 1.1.8: Feb-09-2021 * * Support to load Plugins KOCQAKAZE for Android * * 1.1.9: Feb-10-2021 * * Support to load Plugins KOCQHISTOGRAM for Android * * 1.1.10: Feb-12-2021 * * Support to load Plugins KOCQAffine for Android * * 1.1.11: Feb-13-2021 * * Support to load Plugins KOCQFaceDetection for Android * *******************************************************************/ #include <QGuiApplication> #include <QQuickView> #include <QQmlEngine> #include <QQmlComponent> #include <QQmlContext> #include <QtQuick> #include "KOCQPluginManager.h" #include <QDebug> int main(int argc, char *argv[]) { QGuiApplication app(argc,argv); QQuickView view; view.setSource(QUrl("qrc:///main.qml")); QObject::connect((QObject*)view.engine(), SIGNAL(quit()), &app, SLOT(quit())); view.showFullScreen(); KOCQPluginManager::getInstance()->setQmlEngine(view.engine()); KOCQPluginManager::getInstance()->setRootObject(view.rootObject()); KOCQPluginManager::getInstance()->setSource(view.source()); #if defined(Q_OS_ANDROID) QDir dir; dir.cdUp(); QString libLocation = dir.absolutePath() + "/lib"; // Load KOCQDraw KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQDraw.so"); // Load KOCQPics KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQPics.so"); // Load KOCQQrcode KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQQrcode.so"); // Load KOCQSegmentation KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQSegmentation.so"); // Load KOCQAKAZE KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQAKAZE.so"); // Load KOCQHISTOGRAM KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQHISTOGRAM.so"); // Load KOCQAffine KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQAffine.so"); // Load KOCQFaceDetection KOCQPluginManager::getInstance()->loadPlugin(libLocation + "/libKOCQFaceDetection.so"); #else QDir dir; dir.cdUp(); QString libLocation = dir.absolutePath() + "/lib/plugins/"; // Load KOCQDraw KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQDraw.dll"); // Load KOCQPics KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQPics.dll"); // Load KOCQQrcode KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQQrcode.dll"); // Load KOCQSegmentation KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQSegmentation.dll"); // Load KOCQSegmentation KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQAKAZE.dll"); // Load KOCQHISTOGRAM KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQHISTOGRAM.dll"); // Load KOCQAffine KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQAffine.dll"); // Load KOCQFaceDetection KOCQPluginManager::getInstance()->loadPlugin(libLocation + "KOCQFaceDetection.dll"); #endif return app.exec(); }
using Common; namespace Server.Services { class PingService : IServiceModule { public string AnswerCommand(string command) => Ping.Pong(command); } }
import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class MoveBackTest { // 延迟初始化属性与变量 lateinit var area: Area @BeforeEach fun setUp() { val A = Point(10, 10, Direction.SOUTH) val B = Point(-10, 10, Direction.SOUTH) val C = Point(-10, -10, Direction.SOUTH) val D = Point(10, -10, Direction.SOUTH) area = Area(A, B, C, D) } @Test @DisplayName("后退指令") fun excute() { assertEquals(-1, MoveBack(area).excute(Point(0, 0, Direction.SOUTH)).y) assertEquals(-1, MoveBack(area).excute(Point(0, 0, Direction.EAST)).x) // 越界 assertThrows<RuntimeException> { MoveBack(area).excute(Point(-10, -10, Direction.EAST)).x } } }
/* eslint-disable semi */ /* eslint-disable fp/no-unused-expression */ /* eslint-disable no-magic-numbers */ import { describe, it } from 'mocha' import { expect } from 'chai' // eslint-disable-next-line sort-imports import { BitSmush } from '@johntalton/bitsmush' describe('BitSmush', () => { describe('#smushBits', () => { // it('should run README example', () => { const source = [1, 3, 2]; const template = [ [6, 1], [5, 3], [1, 2] ]; const expected = 0b0_1_011_0_10; const outRegister = BitSmush.smushBits(template, source); expect(outRegister).to.equal(expected); }); it('should run README example second half', () => { const inRegister = 0x5A; const template = [ [6, 1], [5, 3], [1, 2] ]; const [one, three, two] = BitSmush.unSmushBits(template, inRegister); expect(one).to.equal(1); expect(two).to.equal(2); expect(three).to.equal(3); }); it('should throw error if template (type violation zero) @typeViolation', () => { const pm = [[]]; expect(() => BitSmush.smushBits(pm, [])).to.throw('smush not exactly two items: offset / length'); }); it('should throw error if template (type violation gt 2) @typeViolation', () => { const pm = [[1, 2, 3]]; expect(() => BitSmush.smushBits(pm, [])).to.throw('smush not exactly two items: offset / length'); }); it('should throw error if template (type violation offset) @typeViolation', () => { const pm = [['offset', 1]]; expect(() => BitSmush.smushBits(pm, [])).to.throw('offset'); }); it('should throw error if template (type violation length) @typeViolation', () => { const pm = [[0, 'length']]; expect(() => BitSmush.smushBits(pm, [])).to.throw('length'); }); it('should throw error if template (type violation type) @typeViolation', () => { const pm = [false]; expect(() => BitSmush.smushBits(pm, [])).to.throw('smush is not an Array'); }); it.skip('should throw error if template (overlap) @broken', () => { expect(() => BitSmush.smushBits([[3, 2], [2, 3]], [])).to.throw('overlapping'); }); it.skip('should throw error if template (overlap ends) @broken', () => { expect(() => BitSmush.smushBits([[3, 2], [2, 2]], [])).to.throw('overlapping'); }); it('should truncate values to template lengths', () => { expect(BitSmush.smushBits([[1, 2]], [0b101])).to.equal(1); }); it('should throw error (single number array) @slow', () => { expect(() => BitSmush.smushBits([3], [1])).to.throw('smush is not an Array'); }); it('should throw error (array of arrays of single number)', () => { expect(() => BitSmush.smushBits([[3]], [1])).to.throw('mush not exactly two items: offset / length') }); it('should normalize pack example (already normal array of arrays of two numbers)', () => { expect(BitSmush.smushBits([[3, 1]], [1])).to.equal(8); }); it('should pack multiple bits', () => { expect(BitSmush.smushBits([[3, 1], [7, 2]], [1, 3])).to.equal(0b11001000); }); it('should pack multiple bits (extra)', () => { expect(BitSmush.smushBits([[3, 3], [7, 2]], [5, 3])).to.equal(0b11001010); }); it('should pack multiple bits (first bit)', () => { expect(BitSmush.smushBits([[7, 1]], [1])).to.equal(0b10000000); }); it('should pack multiple bits (last bit)', () => { expect(BitSmush.smushBits([[0, 1]], [1])).to.equal(0b00000001); }); it('should pack multiple bits (last bit zero)', () => { expect(BitSmush.smushBits([[0, 1]], [0])).to.equal(0b00000000); }); it('should pack multiple bits (support overlap)', () => { expect(BitSmush.smushBits([[3, 4], [0, 1]], [9, 0])).to.equal(0b00001000); }); }); describe('#unSmushBits', () => { it('should throw error (single number array)', () => { expect(() => BitSmush.unSmushBits([3], 0b1000)).to.throw('smush is not an Array') }) it('should unpack multi byte handcrafted example', () => { const sourceData = 0b00_101_110 expect(BitSmush.unSmushBits([[7, 2], [5, 3], [2, 3]], sourceData)).to.deep.equal([0, 5, 6]) }) }) })
#include "astar.hpp" #include <iostream> #include <vector> #include <ctime> /** * @brief A 2D node. */ struct Node : public astar::Neighbour<Node *> { Node(int x, int y, bool accesable) : x_(x), y_(y), accesable_(accesable), path_(false) { } int x_; int y_; bool accesable_; bool path_; }; using Grid = std::vector<std::vector<Node>>; inline bool operator==(const Node &lhs, const Node &rhs) NOEXCEPT { return lhs.x_ == rhs.x_ && lhs.y_ == rhs.y_; } /** * @brief The logic of the A* algorithm. */ struct logic { inline astar::Logic operator()(const Node * /*node*/, const Node *neighbour, const Node *goal) const NOEXCEPT { using namespace astar; return Logic(Heuristic(manhattan(neighbour->x_, neighbour->y_, goal->x_, goal->y_)), MoveCost(1), Accesable(neighbour->accesable_)); } }; /** * @brief Create a 2D grid, and set the nodes' neighbours. * * @param width width of the grid * @param height height of the grid * * @return 2D grid */ Grid create_map(int width, int height) { Grid nodes; // create a 2d grid nodes.reserve(width); for (int x = 0; x < width; ++x) { nodes.emplace_back(); nodes[x].reserve(height); for (int y = 0; y < height; ++y) { nodes[x].emplace_back(x, y, static_cast<bool>(rand() % 10)); } } // straight direction offsets (x, y, ...) int offset[8] = {+0, -1, +1, +0, +0, +1, -1, +0}; // check the (x,y) coordinate auto is_valid = [&](int x, int y) NOEXCEPT { return x >= 0 && y >= 0 && x < width && y < height; }; // set the neghbours for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { for (int dir = 0; dir < 8; dir += 2) { auto nx = x + offset[dir]; auto ny = y + offset[dir + 1]; if (is_valid(nx, ny)) { nodes[x][y].add_neighbour(&nodes[nx][ny]); } } } } return nodes; } /** * @brief Print a 2D grid with path. * * @param grid 2D grid */ void print_map(const Grid &grid) { for (unsigned x = 0; x < grid.size(); ++x) { for (unsigned y = 0; y < grid[x].size(); ++y) { if (grid[x][y].path_) { std::cout << "O"; } else if (grid[x][y].accesable_ == false) { std::cout << "#"; } else { std::cout << " "; } } std::cout << std::endl; } } int main(int, char const *[]) { // set the seed value srand(time(NULL)); // create a 2D grid const int map_size = 20; Grid nodes = create_map(map_size, map_size); // find the path auto solution = astar::find(&nodes[0][0], &nodes[map_size - 1][map_size - 1], logic()); // mark the path for (auto &element : solution) { element->path_ = true; } // print the grid print_map(nodes); return 0; }
package com.pointr.tcp.util //import org.json4s.DefaultFormats //import org.json4s._ //import org.json4s.jackson.Serialization //import org.json4s.jackson.Serialization.read //import org.json4s.native.JsonMethods._ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.module.scala.DefaultScalaModule case class Prop(url: List[String]) object YamlUtils { // def extract[T: Manifest](strJson: String) = { // implicit val formats = DefaultFormats // val jobj = parse(strJson) // jobj.extract[T] // } import scala.reflect._ def toScala[T](strJson: String)(implicit ctag: ClassTag[T]): T = { val mapper: ObjectMapper = new ObjectMapper(new YAMLFactory()) mapper.registerModule(DefaultScalaModule) mapper.readValue(strJson, ctag.runtimeClass.asInstanceOf[Class[T]]) } }
/** * @license * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://github.com/IDuxFE/idux/blob/main/LICENSE */ import { type ComputedRef, type Ref, computed } from 'vue' import { type VKey } from '@idux/cdk/utils' import { type TablePagination, type TableProps } from '../types' import { type ActiveFilter } from './useFilterable' import { type GetRowKey } from './useGetRowKey' import { type ActiveSortable } from './useSortable' export function useDataSource( props: TableProps, getRowKey: ComputedRef<GetRowKey>, activeSortable: ActiveSortable, activeFilters: ComputedRef<ActiveFilter[]>, expandedRowKeys: Ref<VKey[]>, mergedPagination: ComputedRef<TablePagination | null>, ): DataSourceContext { const mergedData = computed(() => { const { dataSource, childrenKey } = props const getKey = getRowKey.value return dataSource.map(record => covertMergeData(record, getKey, childrenKey)) }) const mergedMap = computed(() => { const map = new Map<VKey, MergedData>() covertDataMap(mergedData.value, map) return map }) const filteredData = computed(() => filterData(mergedData.value, activeFilters.value, expandedRowKeys.value)) const sortedData = computed(() => sortData(filteredData.value, activeSortable, expandedRowKeys.value)) const paginatedData = computed(() => { const pagination = mergedPagination.value const data = sortedData.value if (pagination === null || !pagination.pageSize) { return data } else { const { total } = pagination if (total && data.length < total) { return data } const pageSize = pagination.pageSize! const startIndex = (pagination.pageIndex! - 1) * pageSize return data.slice(startIndex, startIndex + pageSize) } }) const paginatedMap = computed(() => { const map = new Map<VKey, MergedData>() covertDataMap(paginatedData.value, map) return map }) const flattedData = computed(() => { const expandedKeys = expandedRowKeys.value if (expandedKeys.length > 0) { return flatData(paginatedData.value, expandedKeys, 0) } return paginatedData.value }) return { filteredData, flattedData, mergedMap, paginatedMap } } export interface DataSourceContext { filteredData: ComputedRef<MergedData[]> flattedData: ComputedRef<FlattedData[]> mergedMap: ComputedRef<Map<VKey, MergedData>> paginatedMap: ComputedRef<Map<VKey, MergedData>> } export interface MergedData { children?: MergedData[] parentKey?: VKey record: unknown rowKey: VKey } export interface FlattedData extends MergedData { expanded?: boolean level?: number } function covertMergeData(record: unknown, getRowKey: GetRowKey, childrenKey: string, parentKey?: VKey) { const rowKey = getRowKey(record) const result: MergedData = { record, rowKey, parentKey } const subData = (record as Record<string, unknown>)[childrenKey] as unknown[] if (subData) { result.children = subData.map(subRecord => covertMergeData(subRecord, getRowKey, childrenKey, rowKey)) } return result } function covertDataMap(mergedData: MergedData[], map: Map<VKey, MergedData>) { mergedData.forEach(item => { const { rowKey, children } = item map.set(rowKey, item) if (children) { covertDataMap(children, map) } }) } function sortData(mergedData: MergedData[], activeSortable: ActiveSortable, expandedRowKeys: VKey[]) { const { sorter, orderBy } = activeSortable if (!sorter || !orderBy) { return mergedData } const tempData = mergedData.slice() const orderFlag = orderBy === 'ascend' ? 1 : -1 tempData.forEach(item => { if (expandedRowKeys.includes(item.rowKey) && item.children && item.children.length > 0) { item.children = sortData(item.children, activeSortable, expandedRowKeys) } }) return tempData.sort((curr, next) => orderFlag * sorter(curr.record, next.record)) } function filterData(mergedData: MergedData[], activeFilters: ActiveFilter[], expandedRowKeys: VKey[]): MergedData[] { if (activeFilters.length === 0) { return mergedData } return mergedData .map(item => { const valid = activeFilters.every(({ filter, filterBy }) => filter(filterBy, item.record)) const { rowKey, children } = item const isExpanded = expandedRowKeys.includes(rowKey) let newItem = item if (isExpanded && children && children.length) { const newChildren = filterData(children, activeFilters, expandedRowKeys) if (newChildren.length !== children.length) { newItem = { ...item, children: newChildren } } } return valid || (isExpanded && newItem.children) ? newItem : null }) .filter(item => item !== null) as MergedData[] } // TODO: performance optimization // when virtual scrolling is enabled, this do not need to traverse all nodes function flatData(mergedData: MergedData[], expandedRowKeys: VKey[], level: number) { return mergedData.reduce((result, item) => { const { children, parentKey, record, rowKey } = item const expanded = expandedRowKeys.includes(rowKey) result.push({ children, parentKey, record, rowKey, level, expanded }) if (expanded && item.children) { const childrenFlatData = flatData(item.children, expandedRowKeys, level + 1) result.push(...childrenFlatData) } return result }, [] as FlattedData[]) }
<?php return [ "client" => "http://localhost", "port" => "8000" ];