text
stringlengths
1
1.05M
<filename>houdini/scripts/html/ctrl_script.js /* author = "<NAME>" copyright = "2019 All rights reserved. See LICENSE for more details." status = "Prototype" */ // Playback Hotkeys (i/o/p) var video = document.getElementById("video_player"); document.onkeydown = function(event) { switch (event.keyCode) { //time skipping "i/o" case 74: event.preventDefault(); vid_currentTime = video.currentTime; video.currentTime = vid_currentTime - 0.33; break; case 76: event.preventDefault(); vid_currentTime = video.currentTime; video.currentTime = vid_currentTime + 0.33; break; //play/stop "p" case 75: event.preventDefault(); if (video.paused) { video.play(); } else { video.pause(); } } }; /* // HTML5 Custom Player disbaled window.onload = function() { var video = document.getElementById("video_player"); var playButton = document.getElementById("play_pause"); var seekBar = document.getElementById("seek_bar"); // Event listener for the play/pause button playButton.addEventListener("click", function() { if (video.paused == true) { // Play the video video.play(); // Update the button text to 'Pause' playButton.innerHTML = "Play/Pause"; } else { // Pause the video video.pause(); // Update the button text to 'Play' playButton.innerHTML = "Play/Pause"; } }); // Event listener for the seek bar seekBar.addEventListener("change", function() { // Calculate the new time var time = video.duration * (seekBar.value / 100); // Update the video time video.currentTime = time; }); // Update the seek bar as the video plays video.addEventListener("timeupdate", function() { // Calculate the slider value var value = (100 / video.duration) * video.currentTime; // Update the slider value seekBar.value = value; }); // Pause the video when the seek handle is being dragged seekBar.addEventListener("mousedown", function() { video.pause(); }); } */
Sub Combinations(ByVal nChars() As Char, ByVal nPos As Integer) dim x As Integer For x = 0 To UBound(nChars) If(nPos = 1) Then Console.WriteLine(nChars(x)) Else Combinations nChars, nPos - 1 Console.WriteLine(nchars(x)+combos(nchars, npos)) End If Next End Sub
package string_handle; import java.io.BufferedReader; import java.io.InputStreamReader; /** * * @author minchoba * 백준 9971번 : The Hardest Problem Ever * * @see https://www.acmicpc.net/problem/9971/ * */ public class Boj9971 { private static final String START = "START"; private static final String END = "END"; private static final String TERMINATE = "ENDOFINPUT"; private static final String NEW_LINE = "\n"; public static void main(String[] args) throws Exception{ // 버퍼를 통한 값 입력 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); while(true){ String line = br.readLine(); if(line.equals(TERMINATE)){ // ENDOFINPUT이 입력으로 들어올 경우 반복문 종료 break; } if(line.equals(START)){ // START가 입력으로 들어올 경우 다음으로 넘어가 반복 수행 continue; } if(line.equals(END)){ // END가 입력으로 들어올 경우 다음으로 넘어가 반복 수행 continue; } for(char word : line.toCharArray()){ // 입력으로 들어온 문장을 문자 배열로 변환 후 향상된 for문을 이용해 하나씩 가져와서 연산을 실행 if(word >= 'A' && word <= 'Z'){ sb.append(converter(word)); // 들어온 word의 값이 알파벳 범위내에 존재 할 경우 converter 함수 실행 } else{ sb.append(word); // 알파벳이 아닌경우 출력 버퍼에 바로 담아줌 } } sb.append(NEW_LINE); // 문장별로 나누기 위해 끝에 개행문자 삽입 } System.out.println(sb.toString()); // 결과값 한번에 출력 } /** * * @param word : 알파벳 범위내에 있는 문자 * @return : 변환된 word */ private static char converter(char word){ if(word >= 'A' && word <= 'E'){ // A~E 내의 알파벳인 경우 +21 word = (char) (word + 21); } else{ // 그 외 -5 word = (char) (word - 5); } return word; } }
<reponame>ctuning/ck-spack<gh_stars>1-10 ############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RNp(RPackage): """This package provides a variety of nonparametric (and semiparametric) kernel methods that seamlessly handle a mix of continuous, unordered, and ordered factor data types. We would like to gratefully acknowledge support from the Natural Sciences and Engineering Research Council of Canada (NSERC:www.nserc.ca), the Social Sciences and Humanities Research Council of Canada (SSHRC:www.sshrc.ca), and the Shared Hierarchical Academic Research Computing Network (SHARCNET:www.sharcnet.ca).""" homepage = "https://github.com/JeffreyRacine/R-Package-np/" url = "https://cran.r-project.org/src/contrib/np_0.60-2.tar.gz" list_url = "https://cran.r-project.org/src/contrib/Archive/np" version('0.60-2', 'e094d52ddff7280272b41e6cb2c74389') depends_on('r-boot', type=('build', 'run')) depends_on('r-cubature', type=('build', 'run'))
<reponame>pulsar-chem/BPModule<gh_stars>0 import pulsar as psr def load_ref_system(): """ Returns cubane as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C 1.2455 0.5367 -0.0729 C 0.9239 -0.9952 0.0237 C -0.1226 -0.7041 1.1548 C 0.1989 0.8277 1.0582 C 0.1226 0.7042 -1.1548 C -0.9239 0.9952 -0.0237 C -1.2454 -0.5367 0.0729 C -0.1989 -0.8277 -1.0582 H 2.2431 0.9666 -0.1313 H 1.6638 -1.7924 0.0426 H -0.2209 -1.2683 2.0797 H 0.3583 1.4907 1.9059 H 0.2208 1.2681 -2.0799 H -1.6640 1.7922 -0.0427 H -2.2430 -0.9665 0.1313 H -0.3583 -1.4906 -1.9058 """)
/* * */ package net.community.chest.spring.test.beans; import java.util.List; import javax.inject.Inject; import net.community.chest.spring.test.entities.EmbeddingEntity; import org.springframework.stereotype.Service; /** * <P>Copyright as per GPLv2</P> * @author <NAME>. * @since Jan 20, 2011 10:32:35 AM */ @Service public class TestEmbeddingServiceImpl implements TestEmbeddingService { private final EmbeddingEntityDao _dao; protected final EmbeddingEntityDao getEmbeddingEntityDao () { return _dao; } @Inject public TestEmbeddingServiceImpl (EmbeddingEntityDao dao) { _dao = dao; } /* * @see net.community.chest.spring.test.beans.TestEmbeddingService#list() */ @Override public List<EmbeddingEntity> list () { final EmbeddingEntityDao dao=getEmbeddingEntityDao(); return dao.findAll(); } /* * @see net.community.chest.spring.test.beans.TestEmbeddingService#create(net.community.chest.spring.test.entities.EmbeddingEntity) */ @Override public Long create (EmbeddingEntity entity) { final EmbeddingEntityDao dao=getEmbeddingEntityDao(); dao.create(entity); return entity.getId(); } }
#!/bin/bash export CRTDIR=$(pwd) export TMPDIR=/tmp/testgendocs mkdir $TMPDIR cp -r sig* Makefile generator $TMPDIR cd $TMPDIR make all mismatches=0 break=$(printf "=%.0s" $(seq 1 68)) for file in $(ls $CRTDIR/sig-*/README.md $CRTDIR/sig-list.md); do real=${file#$CRTDIR/} if ! diff -q <(sed -e '/Last generated/d' $file) <(sed -e '/Last generated/d' $TMPDIR/$real) &>/dev/null; then echo "$file does not match $TMPDIR/$real"; mismatches=$((mismatches+1)) fi; done if [ $mismatches -gt "0" ]; then echo "" echo $break noun="mismatch was" if [ $mismatches -gt "0" ]; then noun="mismatches were" fi echo "$mismatches $noun detected." echo "Do not manually edit sig-list.md or anything inside the sig folders." echo "Instead make your changes to sigs.yaml and run \`make all\`."; echo $break exit 1; fi rm -rf $TMPDIR exit 0
package org.clever.storage.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.PatternConstant; import org.clever.common.model.request.BaseRequest; import org.clever.common.validation.ValidIntegerStatus; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; /** * 作者: lzw<br/> * 创建时间:2018-12-26 16:18 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class FileUploadLazyReq extends BaseRequest { @ApiModelProperty("是否公开可以访问(0不是,1是)") @ValidIntegerStatus({0, 1}) private Integer publicRead; @ApiModelProperty("是否公开可以修改(0不是,1是)") @ValidIntegerStatus({0, 1}) private Integer publicWrite; @ApiModelProperty("文件来源") @NotBlank @Pattern(regexp = PatternConstant.Name_Pattern + "{3,64}") private String fileSource; @ApiModelProperty("上传文件原名称") @NotBlank(message = "上传文件原名称不能为空") private String fileName; @ApiModelProperty("上传文件的文件签名") @NotBlank(message = "上传文件的文件签名不能为空") private String fileDigest; @ApiModelProperty("文件签名类型,目前只支持MD5和SHA1两种(1:MD5;2:SHA-1;)") @ValidIntegerStatus(value = {1, 2}, message = "文件签名类型只能是:1(MD5)、2(SHA-1)") private Integer digestType; }
@connect / set echo on set termout off alter session set query_rewrite_enabled = true; alter session set query_rewrite_integrity = trusted; drop table t; set termout on set feedback off clear screen create table t ( x int not null, y int not null, z int ); insert into t values ( 1, 4, 55 ); insert into t values ( 1, 4, 55 ); insert into t values ( 2, 3, 42 ); insert into t values ( 2, 3, 42 ); pause set feedback on set linesize 121 clear screen set autotrace on explain select x, y, sum(z) from t group by x, y / pause clear screen create index t_idx on t(y,x,z); select x, y, sum(z) from t group by x, y / pause set autotrace off clear screen create or replace view v as select x, y, sum(z) "SUM(Z)" from t group by x, y order by x, y; pause clear scr begin sys.dbms_advanced_rewrite.declare_rewrite_equivalence ( name => 'DEMO_TIME', source_stmt => 'select x, y, sum(z) from t group by x, y', destination_stmt => 'select * from v', validate => FALSE, rewrite_mode => 'TEXT_MATCH' ); end; / pause clear screen set autotrace on explain select x, y, sum(z) from t group by x, y / pause clear scr select x, y, sum(z) from t FOR_REAL group by x, y / set autotrace off pause clear screen exec sys.dbms_advanced_rewrite.drop_rewrite_equivalence( 'DEMO_TIME' );
<reponame>james-wills/Flixster package com.example.james_wills.flixster.utils; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.TypedValue; public class DeviceDimensionsHelper { // DeviceDimensionsHelper.getDisplayWidth(context) => (display width in pixels) public static boolean isLandscape(Context context) { return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } }
<gh_stars>1-10 package net.zomis.spring.games.generic; import com.fasterxml.jackson.core.TreeNode; import com.fasterxml.jackson.databind.ObjectMapper; import net.zomis.spring.games.messages.GameMoveResult; import java.util.Map; import java.util.function.Function; @Deprecated public class GroovyGameHelper implements GameHelper<Object, Object> { public Function<Object, Object> constructor; public Function<Object, Object> details; public Map<String, GroovyGames.GroovyAction> actions; @Override public Object constructGame(Object configuration) { return constructor.apply(configuration); } @Override public void addPlayer(Object playerConfig) { } @Override public Object start() { return null; } @Override public GameMoveResult performAction(PlayerInGame playerInGame, String actionType, TreeNode data) { GroovyGames.GroovyAction action = actions.get(actionType); Object actionData = new ObjectMapper().convertValue(data, action.parameter); action.perform.call(new Action(null, playerInGame, actionData)); return new GameMoveResult("ok"); } @Override public Object gameDetails(Object game) { return details.apply(game); } }
# # Add jquery to project # mkdir ../Source/js mkdir ../Source/js/vendor mkdir ../Source/js/vendor/jquery curl -o ../Source/js/vendor/jquery/jquery-3.2.1.js https://code.jquery.com/jquery-3.2.1.min.js
#!/bin/bash for filename in `find . -type f -name '*.cpp'`; do echo $filename obj=$(echo $filename | sed -e s/src/build/ -e s/cpp/o/) echo $obj gcov-5 -r -p -o $obj $filename done
var dir_0e467354ced3595f0aa9578c498f5e57 = [ [ "TfResNext_Quantized-Armnn.cpp", "_tf_res_next___quantized-_armnn_8cpp.xhtml", "_tf_res_next___quantized-_armnn_8cpp" ] ];
<filename>cmd/govim/internal/golang_org_x_tools/lsp/template/highlight.go // Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package template import ( "context" "fmt" "regexp" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/protocol" "github.com/govim/govim/cmd/govim/internal/golang_org_x_tools/lsp/source" ) func Highlight(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, loc protocol.Position) ([]protocol.DocumentHighlight, error) { buf, err := fh.Read() if err != nil { return nil, err } p := parseBuffer(buf) pos := p.FromPosition(loc) var ans []protocol.DocumentHighlight if p.ParseErr == nil { for _, s := range p.symbols { if s.start <= pos && pos < s.start+s.length { return markSymbols(p, s) } } } // these tokens exist whether or not there was a parse error // (symbols require a successful parse) for _, tok := range p.tokens { if tok.Start <= pos && pos < tok.End { wordAt := findWordAt(p, pos) if len(wordAt) > 0 { return markWordInToken(p, wordAt) } } } // find the 'word' at pos, etc: someday // until then we get the default action, which doesn't respect word boundaries return ans, nil } func markSymbols(p *Parsed, sym symbol) ([]protocol.DocumentHighlight, error) { var ans []protocol.DocumentHighlight for _, s := range p.symbols { if s.name == sym.name { kind := protocol.Read if s.vardef { kind = protocol.Write } ans = append(ans, protocol.DocumentHighlight{ Range: p.Range(s.start, s.length), Kind: kind, }) } } return ans, nil } // A token is {{...}}, and this marks words in the token that equal the give word func markWordInToken(p *Parsed, wordAt string) ([]protocol.DocumentHighlight, error) { var ans []protocol.DocumentHighlight pat, err := regexp.Compile(fmt.Sprintf(`\b%s\b`, wordAt)) if err != nil { return nil, fmt.Errorf("%q: unmatchable word (%v)", wordAt, err) } for _, tok := range p.tokens { got := pat.FindAllIndex(p.buf[tok.Start:tok.End], -1) for i := 0; i < len(got); i++ { ans = append(ans, protocol.DocumentHighlight{ Range: p.Range(got[i][0], got[i][1]-got[i][0]), Kind: protocol.Text, }) } } return ans, nil } var wordRe = regexp.MustCompile(`[$]?\w+$`) var moreRe = regexp.MustCompile(`^[$]?\w+`) // findWordAt finds the word the cursor is in (meaning in or just before) func findWordAt(p *Parsed, pos int) string { if pos >= len(p.buf) { return "" // can't happen, as we are called with pos < tok.End } after := moreRe.Find(p.buf[pos:]) if len(after) == 0 { return "" // end of the word } got := wordRe.Find(p.buf[:pos+len(after)]) return string(got) }
fn resolve_dependencies(modules: Vec<&str>) -> Vec<&str> { let mut graph = std::collections::HashMap::new(); let mut visited = std::collections::HashSet::new(); let mut result = Vec::new(); for module in &modules { graph.insert(module.to_string(), Vec::new()); } for module in &modules { let dependencies = get_dependencies(module); graph.insert(module.to_string(), dependencies); } for module in &modules { if !visited.contains(module) { dfs(module, &graph, &mut visited, &mut result); } } result } fn get_dependencies(module: &str) -> Vec<String> { // Implement logic to read the module file and extract dependencies // For simplicity, assume a predefined mapping of modules to their dependencies match module { "cookie" => vec!["protocol".to_string()], "protocol" => vec!["router".to_string()], "router" => vec!["websocket".to_string()], "websocket" => Vec::new(), _ => Vec::new(), } } fn dfs( module: &str, graph: &std::collections::HashMap<String, Vec<String>>, visited: &mut std::collections::HashSet<String>, result: &mut Vec<String>, ) { visited.insert(module.to_string()); for dependency in &graph[module] { if !visited.contains(dependency) { dfs(dependency, graph, visited, result); } } result.push(module.to_string()); }
<filename>src/types/Item.js class DocumentedItem { constructor(parent, data) { this.parent = parent; const { name, comment, flags, sources } = data; this.name = name; this.description = comment ? comment.shortText || comment.text : 'No description available'; this.flags = this.parseFlags(flags); this.sources = this.parseSources(sources); } parseFlags(flags = []) { const formatted = {}; Object.keys(flags) .forEach(f => formatted[f.substr(2).toLowerCase()] = true); return formatted; } parseSources(sources) { return sources ? sources[0] : undefined; } parseType(type) { if (type.type !== 'array') { return { name: type.name || type.value, arrayOf: false } } else { return { name: type.elementType.name, arrayOf: true } } } serializer() { return {...{ name: this.name, description: this.description, flags: this.flags, sources: this.sources }, ...this.serialize() }; } } module.exports = DocumentedItem;
var armnn_tf_parser_2test_2_test_multi_inputs_outputs_8cpp = [ [ "BOOST_FIXTURE_TEST_CASE", "armnn_tf_parser_2test_2_test_multi_inputs_outputs_8cpp.xhtml#ade2300c7c66d25f6b8626df6fb0d82b3", null ] ];
<html> <head> <title>Weather App</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $(document).ready(function() { $.getJSON('https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOUR_API_KEY', function(data) { $('#city').html(data.name); $('#temp').html(data.main.temp); $('#desc').html(data.weather[0].description); }); }); </script> </head> <body> <h1>Current Weather in <span id="city"></span></h1> <p>Temperature: <span id="temp"></span>° Celcius</p> <p>Description: <span id="desc"></span></p> </body> </html>
#!/bin/sh set -e set -x # cleanup and create new rootfs dir rm -fr rootfs/ mkdir -p rootfs/etc/ssl/certs/ # add latest ca-certificates.crt from Debian upstream (cd rootfs/etc/ssl/certs/; \ wget https://github.com/hypriot/rpi-swarm/raw/master/certs/ca-certificates.crt) # add latest etcd binary ETCD_VERSION="2.0.10" (cd rootfs; \ wget https://github.com/coreos/etcd/releases/download/v${ETCD_VERSION}/etcd-v${ETCD_VERSION}-linux-amd64.tar.gz; \ tar --strip-components=1 -xvzf etcd-v${ETCD_VERSION}-linux-amd64.tar.gz \ etcd-v${ETCD_VERSION}-linux-amd64/etcd \ etcd-v${ETCD_VERSION}-linux-amd64/etcdctl; \ rm -f etcd-v${ETCD_VERSION}-linux-amd64.tar.gz; \ ls -al etcd*) # create complete tarball (cd rootfs; \ tar cvzf ../rootfs.tar.gz .) # remove etcd binary rm -fr rootfs/etcd*
#!/bin/bash if [ -z "$BASH_VERSION" ]; then echo "** MUST RUN FROM bash, please run again from bash! **" exit 15 fi ZONAMADEV_URL='https://github.com/Zonama/ZonamaDev' ZONAMADEV_BRANCH='release-1.5' OS='unknown' main() { case $HOME in *' '* ) echo echo 'Your $HOME has spaces in it:' echo echo " HOME=[$HOME]" echo echo 'Vagrant is based on Ruby which has issues with spaces in $HOME' echo echo 'In order to use this system you must have a username without spaces' echo 'or you must manually override HOME to a directory without spaces.' echo echo 'You could try working around this by doing the following:' echo echo ' mkdir /c/swgemudev' echo ' export HOME=/c/swgemudev' echo ' cd $HOME' echo ' curl -Lk http://downloads.zonamaserver.org/zonamadev/bootstrap.sh | bash '"$@" echo echo 'However, every time you want to work with this system you will need to reset' echo 'your HOME when you open the bash shell window.' echo echo '** Process aborted, Spaces in HOME **' exit 13 ;; esac case $(uname -s) in Darwin ) OS='osx' ;; *Linux* ) OS='linux' ;; *_NT* ) OS='win';; * ) echo "Not sure what OS you are on, guessing Windows"; OS='win';; esac # Handle destroy or uninstall if [ "X$1" = "Xdestroy" -o "X$1" = "Xuninstall" ]; then if reset_zd "$1"; then echo "######################################" echo "## ZonamaDev Host Environment Reset ##" echo "######################################" if [ "X$1" = "Xuninstall" ]; then echo "** ZonamaDev has been uninstalled from this computer **" exit 0 fi else echo "** Aborted by user **" exit 14 fi shift fi # Handle release {x.y} if [ "X$1" = "Xrelease" -a "X$2" != "X" ]; then shift ZONAMADEV_BRANCH="release-$1" shift fi # Handle branch {branchName} if [ "X$1" = "Xbranch" -a "X$2" != "X" ]; then shift ZONAMADEV_BRANCH="$1" shift fi if [ -z "${ZONAMADEV_BRANCH}" ]; then echo "ERROR: No branch to boot from?, GET HELP" exit 126 fi echo "######################################" echo "## Using branch ${ZONAMADEV_BRANCH}" echo "######################################" check_versions # Used by fasttrack/upgrade.sh to verify host software versions if [ "X$1" = "Xcheck-versions" ]; then shift exit 0 fi if [ -n "$1" ]; then [ "$1" != "help" ] && echo "** Unexpected arguments: [$@]" echo echo "Usage: $0 (help|destroy|uninstall|branch {branchName}|release {x.y})" echo exit 0 fi # If we're under the ZonamaDev dir back out to parent cd ${PWD/ZonamaDev*/} echo "** ZDHOME=${PWD} **" ## Clone Repo echo "Using ${ZONAMADEV_URL} branch ${ZONAMADEV_BRANCH}" if git clone -b ${ZONAMADEV_BRANCH} ${ZONAMADEV_URL}; then : else case $PWD in *ZonamaDev* ) : ;; * ) if [ -d ZonamaDev ]; then cd ZonamaDev else echo "** Something is wrong, did you try and run this in the right directory? **" echo "** We suggest you run it from $HOME **" exit 1 fi ;; esac git stash git fetch --all if git pull --all; then : else echo "** Failed to pull too, you might need help!" exit 1 fi if git checkout "${ZONAMADEV_BRANCH}"; then : else echo "** Failed to checkout branch ${ZONAMADEV_BRANCH}, GET HELP!" exit 125 fi fi ## hand off to next script cd ${PWD/ZonamaDev*/}"/ZonamaDev/fasttrack" echo "** Running in $PWD **" exec ./setup.sh echo "** Something went wrong, get help **" exit 11 } check_versions() { ## Check for git if git --version > /dev/null 2>&1; then : else eval install_git_$OS fi if [ "$OS" = "win" ]; then echo "** Checking for Git Bash **" check_gitbash_$OS fi echo "** Checking for VirtualBox **" check_virtualbox_$OS echo "** Checking for Vagrant **" check_vagrant_$OS return 0 } install_git_win() { echo "** Please download and install git-for-windows at: https://git-for-windows.github.io/" echo "** When that is complete, please use Git Bash shell to run this script again" exit 0 } install_git_osx() { echo "** Please download XCode for OSX at: https://developer.apple.com/xcode/downloads/" open https://developer.apple.com/xcode/downloads/ echo "** When that is complete, please restart this script." exit 0 } install_git_linux() { # Assume deb for now? sudo apt-get install git < /dev/tty if git --version > /dev/null 2>&1; then : else echo "** Failed to install git, **ABORT**" exit 12 fi } check_gitbash_win() { local ver_min="4.3.0" local ver=$("${vbm}" --version) if [ -z "${MSYSTEM}" ]; then echo "** MUST RUN FROM GITBASH SHELL NOT CYGWIN, ABORTING **" exit 16 fi if version_error "${ver_min}" "${BASH_VERSION}"; then echo "Unsupported version of BASH (${BASH_VERSION}), please upgrade to BASH 4.3.x+" exit 1 fi for i in tty mktemp sed scp ssh find cygpath do if type -P $i > /dev/null; then : else echo "** You're missing the $i command, you need to upgrade git for windows" echo "** Please download and install the latest from: https://git-for-windows.github.io/" exit 1 fi done echo "** BASH_VERSION: ${BASH_VERSION} **" return 0 } check_virtualbox_win() { local ver_min="5.2.14" local ve=$(wmic cpu get VirtualizationFirmwareEnabled/value | grep TRUE) if [ -z "$ve" ]; then echo "############################################################################" echo "## ERROR: YOU MUST ENABLE VIRTUALIZATION IN YOUR BIOS BEFORE YOU CONTINUE ##" echo "############################################################################" echo echo "** Unless you know what you're doing most likely you will not be able to start the VM **" echo if yorn "Do you want to stop and fix the BIOS setting now?"; then echo "** Please close this window, boot into your BIOS, enable virtualization and try again **" exit 202 fi echo echo "** USER IGNORING VT WARNING **" wmic cpu get VirtualizationFirmwareEnabled/value echo "*****" fi if [ -z "$VBOX_INSTALL_PATH" -a -z "$VBOX_MSI_INSTALL_PATH" ]; then echo -e "** You need to install VirtualBox for windows **\n" if yorn "Would you like me to take you to: https://www.virtualbox.org/wiki/Downloads?"; then explorer "https://www.virtualbox.org/wiki/Downloads" fi echo "** Please close this window, install VirtualBox, REBOOT and try again **" exit 1 fi local ver=$("${VBOX_MSI_INSTALL_PATH:-${VBOX_INSTALL_PATH}}/VBoxManage" --version) if version_error "${ver_min}" "${ver}"; then echo "Unsupported version of virtualbox ($ver), please upgrade to ${ver_min} or higher" exit 1 fi echo "** Virtualbox version $ver **" return 0 } check_virtualbox_linux() { local ver_min="5.2.14" local vbm=$(type -P VBoxManage) if [ -z "${vbm}" ]; then echo -e "** You need to install VirtualBox (${ver_min} or higher) for Linux **\n" echo -e '** Please go to https://www.virtualbox.org/wiki/Linux_Downloads and follow directions there to install virtualbox' echo -e '** After you have virtualbox installed re-try this command.' exit 1 fi local ver=$("${vbm}" --version) if version_error "${ver_min}" "${ver}"; then echo "Unsupported version of virtualbox ($ver), please upgrade to ${ver_min} or higher" exit 1 fi echo "** Virtualbox version $ver **" return 0 } check_virtualbox_osx() { local ver_min="5.2.14" local vbm=$(type -P VBoxManage) if [ -z "${vbm}" ]; then echo -e "** You need to install VirtualBox (${ver_min} or higher) for OSX**\n" echo -e '** Please go to https://www.virtualbox.org/wiki/Linux_Downloads and follow directions there to install virtualbox' echo -e '** After you have virtualbox installed re-try this command.' exit 1 fi local ver=$("${vbm}" --version) if version_error "${ver_min}" "${ver}"; then echo "Unsupported version of virtualbox ($ver), please upgrade to ${ver_min} or higher" exit 1 fi echo "** Virtualbox version $ver **" } check_vagrant_base() { local ver_min="2.1.2" local ver=$(vagrant --version | cut -d' ' -f2 2> /dev/null) if [ -z "$ver" ]; then if [ -n "$(type -P vagrant)" ]; then echo -e "** You might have a broken version of vagrant installed\n\nvagrant -v" vagrant -v if yorn "Is the version of vagrant installed ${ver_min} or higher?"; then echo "** Please note that you could have problems unless you downgrade to ${ver_min}" return 0 else echo "** Please close this window, install Vagrant ${ver_min} or higher and try again **" exit 1 fi fi echo -e "** You need to install Vagrant ${ver_min} or higher **\n" if yorn "Would you like me to take you to: https://www.vagrantup.com/downloads.html?"; then explorer "https://www.vagrantup.com/downloads.html" fi echo "** Please close this window, install Vagrant and try again **" exit 1 fi if version_error "${ver_min}" "${ver}"; then echo "Unsupported version of Vagrant ($ver), please upgrade to v${ver_min} or higher" exit 1 fi echo "** Vagrant version $ver **" return 0 } check_vagrant_win() { check_vagrant_base return $? } check_vagrant_osx() { check_vagrant_base return $? } check_vagrant_linux() { check_vagrant_base local dp=$(type -P dpkg) if [ -z "${dp}" ]; then echo "** WARNING: Without dpkg we can not check for zlib, you may need to manually install it for vagrant to work **" else if dpkg -s zlib1g-dev > /dev/null 2>&1; then : else echo "** please make sure zlib1g-dev is installed **" exit fi fi return 0 } reset_zd() { echo "##################################################################################" echo "## WARNING THIS WILL REMOVE ALL ZonamaDev VM's AND REMOVE YOUR ZonamaDev FOLDER ##" echo "##################################################################################" local msg="Are you sure you want to destroy the old setup?" if [ "X$1" = "Xuninstall" ]; then msg="Are you sure you want to uninstall ZonamaDev?" fi if yorn "\n${msg}"; then : else return 1 fi ( cd / echo "** Checking for ZonamaDev vagrant VM images..." found=false vagrant global-status|grep ZonamaDev|while read id name provider state dir do echo "Destroy VMid $id from $dir" vagrant destroy "${id}" --force found=true done if $found; then echo "** Removed all ZonamaDev VM images **" else echo "** No ZonamaDev VM images where found **" fi ) echo "** Removing any cached copies of base box **" vagrant box list | awk '/^zonama/ { print $1 }' | while read basebox do vagrant box remove ${basebox} --all --force done echo "** Looking for the ZonamaDev host directory..." local found_zd=false for i in "$PWD" "$HOME" do local zddir="${i}/ZonamaDev" if [ -d "${zddir}" ]; then echo "** Removing ${zddir} **" rm -fr "${zddir}" found_zd=true fi done if $found_zd; then echo "** Removed ZonamaDev host directory **" else echo "** Did not find the ZonamaDev host directory **" fi if [ -d ~/.vagrant.d ]; then echo "** Removing vagrant settings directory **" rm -fr ~/.vagrant.d fi return 0 } yorn() { local yorn if tty -s; then echo -n -e "$@ Y\b" > /dev/tty read yorn < /dev/tty case $yorn in [Nn]* ) return 1;; esac fi return 0 } version_error() { local want="$1" local have="$2" read have_maj have_min have_sub have_misc <<<${have//[^0-9]/ } read want_maj want_min want_sub want_misc <<<${want//[^0-9]/ } if [ "${have_maj}" -lt "${want_maj}" ]; then return 0 fi if [ "${have_maj}" -gt "${want_maj}" ]; then return 1 fi if [ "${have_min}" -gt "${want_min}" ]; then return 2 fi if [ "${have_sub}" -gt "${want_sub}" ]; then return 3 fi if [ "${have_maj}" -eq "${want_maj}" -a "${have_min}" -eq "${want_min}" -a "${have_sub}" -eq "${want_sub}" ]; then return 4 fi return 0 } main "$@" < /dev/tty exit 0
#!/bin/bash -e ################################################################################ ## File: rust.sh ## Desc: Installs Rust ################################################################################ echo "skipping"
def test_login(client): # Retrieve the first user from the database user = User.query.first() # Append a log entry with the title "Golf" to the user's logs user.my_logs.append(Log(title="Golf")) # Add the user to the session db.session.add(user) # Commit the changes to the database db.session.commit() # Send a post request using the provided client to test the login functionality response = client.post('/login', data=dict( username=user.username, password=user.password )) # Additional assertions or checks can be added to validate the response assert response.status_code == 200 assert b'Login successful' in response.data
<reponame>lgarciaaco/cos-fleetshard<filename>cos-fleetshard-sync/src/test/java/org/bf2/cos/fleetshard/sync/connector/ConnectorStatusExtractorTest.java package org.bf2.cos.fleetshard.sync.connector; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bf2.cos.fleet.manager.model.ConnectorDeploymentStatus; import org.bf2.cos.fleet.manager.model.ConnectorDeploymentStatusOperators; import org.bf2.cos.fleetshard.api.Conditions; import org.bf2.cos.fleetshard.api.ConnectorStatusSpecBuilder; import org.bf2.cos.fleetshard.api.DeploymentSpecBuilder; import org.bf2.cos.fleetshard.api.ManagedConnectorBuilder; import org.bf2.cos.fleetshard.api.ManagedConnectorSpecBuilder; import org.bf2.cos.fleetshard.api.ManagedConnectorStatus; import org.bf2.cos.fleetshard.api.ManagedConnectorStatusBuilder; import org.bf2.cos.fleetshard.api.OperatorSelectorBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import io.fabric8.kubernetes.api.model.Condition; import io.fabric8.kubernetes.api.model.ConditionBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.bf2.cos.fleetshard.api.ManagedConnector.DESIRED_STATE_DELETED; import static org.bf2.cos.fleetshard.api.ManagedConnector.DESIRED_STATE_READY; import static org.bf2.cos.fleetshard.api.ManagedConnector.DESIRED_STATE_STOPPED; import static org.bf2.cos.fleetshard.api.ManagedConnector.STATE_DE_PROVISIONING; import static org.bf2.cos.fleetshard.api.ManagedConnector.STATE_FAILED; import static org.bf2.cos.fleetshard.api.ManagedConnector.STATE_PROVISIONING; import static org.bf2.cos.fleetshard.api.ManagedConnector.STATE_READY; import static org.junit.jupiter.params.provider.Arguments.arguments; public class ConnectorStatusExtractorTest { public static Stream<Arguments> defaultIfPhaseIsNotSet() { return Stream.of( arguments( DESIRED_STATE_READY, STATE_PROVISIONING), arguments( DESIRED_STATE_STOPPED, STATE_DE_PROVISIONING), arguments( DESIRED_STATE_DELETED, STATE_DE_PROVISIONING)); } public static Stream<Arguments> extractFromConnectorStatus() { return Stream.of( arguments( DESIRED_STATE_READY, STATE_FAILED, STATE_FAILED, List.of(new ConditionBuilder() .withType("Ready") .withStatus("False") .withReason("reason") .withMessage("message") .build())), arguments( DESIRED_STATE_READY, STATE_READY, STATE_READY, List.of(new ConditionBuilder() .withType("Ready") .withStatus("False") .withReason("reason") .withMessage("message") .build())), arguments( DESIRED_STATE_READY, null, STATE_PROVISIONING, List.of(new ConditionBuilder() .withType("Ready") .withStatus("False") .withReason("reason") .withMessage("message") .build()))); } /* * Test that if no phase can be computed, then phase is set to a transient * phase according to the desired state. */ @ParameterizedTest @MethodSource void defaultIfPhaseIsNotSet( String statusDesiredState, String expectedState) { var status = ConnectorStatusExtractor.extract( new ManagedConnectorBuilder() .withSpec(new ManagedConnectorSpecBuilder() .withOperatorSelector(new OperatorSelectorBuilder() .withId("1") .build()) .build()) .withStatus(new ManagedConnectorStatusBuilder() .withPhase(ManagedConnectorStatus.PhaseType.Monitor) .withDeployment(new DeploymentSpecBuilder() .withDeploymentResourceVersion(1L) .withDesiredState(statusDesiredState) .build()) .build()) .build()); assertThat(status.getPhase()).isEqualTo(expectedState); assertThat(status.getConditions()).isNullOrEmpty(); assertThat(status.getResourceVersion()).isEqualTo(1L); assertThat(status) .extracting(ConnectorDeploymentStatus::getOperators) .extracting(ConnectorDeploymentStatusOperators::getAssigned) .hasAllNullFieldsOrProperties(); assertThat(status) .extracting(ConnectorDeploymentStatus::getOperators) .extracting(ConnectorDeploymentStatusOperators::getAvailable) .hasAllNullFieldsOrProperties(); } /* * Test that if the status sub resource is provided and the phase is * "monitor", then the status extractor compute the phase according * to the reported deployment status */ @ParameterizedTest @MethodSource void extractFromConnectorStatus( String statusDesiredState, String connectorPhase, String expectedState, List<Condition> conditions) { var status = ConnectorStatusExtractor.extract( new ManagedConnectorBuilder() .withSpec(new ManagedConnectorSpecBuilder() .withOperatorSelector(new OperatorSelectorBuilder() .withId("1") .build()) .build()) .withStatus(new ManagedConnectorStatusBuilder() .withPhase(ManagedConnectorStatus.PhaseType.Monitor) .withDeployment(new DeploymentSpecBuilder() .withDeploymentResourceVersion(1L) .withDesiredState(statusDesiredState) .build()) .withConnectorStatus(new ConnectorStatusSpecBuilder() .withPhase(connectorPhase) .withConditions(conditions) .build()) .build()) .build()); var v1Conditions = conditions.stream() .map(ConnectorStatusExtractor::toMetaV1Condition) .collect(Collectors.toList()); assertThat(status.getPhase()).isEqualTo(expectedState); assertThat(status.getConditions()).hasSameSizeAs(conditions).hasSameElementsAs(v1Conditions); assertThat(status.getResourceVersion()).isEqualTo(1L); assertThat(status) .extracting(ConnectorDeploymentStatus::getOperators) .extracting(ConnectorDeploymentStatusOperators::getAssigned) .hasAllNullFieldsOrProperties(); assertThat(status) .extracting(ConnectorDeploymentStatus::getOperators) .extracting(ConnectorDeploymentStatusOperators::getAvailable) .hasAllNullFieldsOrProperties(); } @Test void errorIfNoOperatorId() { var status = ConnectorStatusExtractor.extract( new ManagedConnectorBuilder() .withSpec(new ManagedConnectorSpecBuilder() .withOperatorSelector(new OperatorSelectorBuilder() .build()) .build()) .withStatus(new ManagedConnectorStatusBuilder() .withPhase(ManagedConnectorStatus.PhaseType.Monitor) .withDeployment(new DeploymentSpecBuilder() .withDeploymentResourceVersion(1L) .withDesiredState(DESIRED_STATE_READY) .build()) .build()) .build()); assertThat(status.getPhase()).isEqualTo(STATE_FAILED); assertThat(status.getConditions()).anySatisfy(c -> { assertThat(c.getType()).isEqualTo(Conditions.TYPE_READY); assertThat(c.getStatus()).isEqualTo(Conditions.STATUS_FALSE); assertThat(c.getReason()).isEqualTo(Conditions.NO_ASSIGNABLE_OPERATOR_REASON); }); assertThat(status.getResourceVersion()).isEqualTo(1L); } @Test void errorIfNoOperatorSelector() { var status = ConnectorStatusExtractor.extract( new ManagedConnectorBuilder() .withSpec(new ManagedConnectorSpecBuilder() .build()) .withStatus(new ManagedConnectorStatusBuilder() .withPhase(ManagedConnectorStatus.PhaseType.Monitor) .withDeployment(new DeploymentSpecBuilder() .withDeploymentResourceVersion(1L) .withDesiredState(DESIRED_STATE_READY) .build()) .build()) .build()); assertThat(status.getPhase()).isEqualTo(STATE_FAILED); assertThat(status.getConditions()).anySatisfy(c -> { assertThat(c.getType()).isEqualTo(Conditions.TYPE_READY); assertThat(c.getStatus()).isEqualTo(Conditions.STATUS_FALSE); assertThat(c.getReason()).isEqualTo(Conditions.NO_ASSIGNABLE_OPERATOR_REASON); }); assertThat(status.getResourceVersion()).isEqualTo(1L); } }
<filename>src/main/java/_1_Add_two_numbers_as_a_linked_list.java /* Hi, here's your problem today. This problem was recently asked by Microsoft: You are given two linked-lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ package main.java; class Node { int val; Node next; Node(int val) { this.val = val; } Node() { } } public class _1_Add_two_numbers_as_a_linked_list { public static void main(String[] args) { Node firstnum = new Node(2); firstnum.next = new Node(4); firstnum.next.next = new Node(3); Node secondnum = new Node(5); secondnum.next = new Node(6); secondnum.next.next = new Node(4); Node sum = addTwoNumbers(firstnum, secondnum); while(sum!=null) { System.out.print(sum.val+" "); sum = sum.next; } } public static Node addTwoNumbers(Node firstnum, Node secondnum) { Node sum = null; Node sumtail = null; int carry = 0; while(firstnum != null && secondnum != null) { int digitsum = firstnum.val + secondnum.val + carry; if(sum == null) { sum = new Node(); sum.val = digitsum % 10; sumtail = sum; } else { sumtail.next = new Node(); sumtail = sumtail.next; sumtail.val = digitsum % 10; } carry = digitsum / 10; firstnum = firstnum.next; secondnum = secondnum.next; } while(firstnum != null) { int digitsum = firstnum.val + carry; if(sum == null) { sum = new Node(); sum.val = digitsum % 10; sumtail = sum; } else { sumtail.next = new Node(); sumtail = sumtail.next; sumtail.val = digitsum % 10; } carry = digitsum / 10; } while(secondnum != null) { int digitsum = secondnum.val + carry; if(sum == null) { sum = new Node(); sum.val = digitsum % 10; sumtail = sum; } else { sumtail.next = new Node(); sumtail = sumtail.next; sumtail.val = digitsum % 10; } carry = digitsum / 10; } if(carry > 0) { sumtail.next = new Node(); sumtail = sumtail.next; sumtail.val = carry; } return sum; } }
import tkinter # Create main window. main_window = tkinter.Tk() main_window.title("User Data Entry") main_window.geometry("200x100") # Create entry boxes name_label = tkinter.Label(main_window, text="Name") name_label.grid(row=0, column=0, sticky="w") name_entry = tkinter.Entry(main_window) name_entry.grid(row=0, column=1, sticky="w") age_label = tkinter.Label(main_window, text="Age") age_label.grid(row=1, column=0, sticky="w") age_entry = tkinter.Entry(main_window) age_entry.grid(row=1, column=1, sticky="w") # Create button save_button = tkinter.Button(main_window, text="Save") save_button.grid(row=2, column=0, sticky="w") main_window.mainloop()
import dsReducerGenerator from 'ember-data-on-redux/reducers/ds-reducer-generator'; import initialState from '../constants/initial-state'; const noOp = {}; export default { ds: dsReducerGenerator(initialState, noOp) };
package network_flow; import java.io.*; import java.util.*; /** * * @author exponential-e * 백준 1960번: 행렬만들기 * * @see https://www.acmicpc.net/problem/1960 * Java get OOM & I dont know reason -> C++17 * */ public class Boj1960 { private static int[][] capacity; private static int[][] flow; private static ArrayList<Integer>[] connection; private static int[] row, col; private static int[] counter = new int[2]; private static int S, T, N; private static int size; public static void main(String[] args) { InputReader in = new InputReader(System.in); N = in.readInt(); init(); for(int i = 1; i <= N; i++) { int x = in.readInt(); linker(S, i, x); row[i] = x; counter[0] += x; } for(int i = 1; i <= N; i++){ int x = in.readInt(); linker(i + N, T, x); col[i] = x; counter[1] += x; } if(counter[0] != counter[1]) System.out.println(-1); else networkFlow(); } private static void networkFlow() { int[] prev = new int[size]; while(true) { Arrays.fill(prev, -1); Queue<Integer> q = new LinkedList<>(); q.offer(S); while(!q.isEmpty() && prev[T] == -1) { int current = q.poll(); for(int next: connection[current]) { if(capacity[current][next] <= flow[current][next]) continue; if(prev[next] != -1) continue; prev[next] = current; q.offer(next); } } if(prev[T] == -1) break; for(int i = T; i != S; i = prev[i]){ flow[prev[i]][i] += 1; flow[i][prev[i]] -= 1; } } int[][] result = new int[N + 1][N + 1]; for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ if(flow[i][j + N] > 0) result[i][j] = 1; } } OutputWriter out = new OutputWriter(System.out); if(!counting(result)) { out.print(-1); return; } out.printLine(1); for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { out.print(result[i][j]); } out.printLine(); } } private static boolean counting(int[][] arr){ for(int i = 1; i <= N; i++){ int[] sum = {0, 0}; for(int j = 1; j <= N; j++){ sum[0] += arr[i][j]; sum[1] += arr[j][i]; } if(sum[0] != row[i] || sum[1] != col[i]) return false; } return true; } private static void init () { size = (N << 1) + 2; row = new int[N + 1]; col = new int[N + 1]; capacity = new int[size][size]; flow = new int[size][size]; connection = new ArrayList[size]; for(int i = 0 ; i < size; i++) { connection[i] = new ArrayList<>(); } S = 0; T = size - 1; for(int i = 1; i <= N; i++){ for(int j = 1; j <= N; j++){ linker(i, j + N, 1); } } } private static void linker(int from, int to, int cap){ connection[from].add(to); connection[to].add(from); capacity[from][to] = cap; } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } private static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } writer.flush(); } public void printLine(Object... objects) { print(objects); writer.println(); writer.flush(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } } /** * * C++ 17 * * #include <iostream> * #include <vector> * #include <cstring> * #include <queue> * using namespace std; * * int capacity[1002][1002]; * int flow[1002][1002]; * int result[501][501]; * * int N; * int S = 0, T = 1001; * * vector<int> connection[1002]; * vector<int> row, col; * * void linker(int from, int to, int cap); * bool counting(); * void networkFlow(); * * int main(){ * ios_base::sync_with_stdio(0); cin.tie(0); * cin >> N; * row.resize(N + 1); * col.resize(N + 1); * * for(int i = 1; i <= N; i++){ * int x; cin >> x; * * linker(S, i, x); * row[i] = x; * } * * for(int i = 1; i <= N; i++){ * int x; cin >> x; * * linker(i + N, T, x); * col[i] = x; * } * * for(int i = 1; i <= N; i++){ * for(int j= 1; j <= N; j++){ * linker(i, j + N, 1); * } * } * * networkFlow(); * } * * void networkFlow(){ * int prev[1002]; * * while(1){ * int mx = 1e9; * memset(prev, -1, sizeof prev); * * queue<int> q; * q.push(S); * * while(q.size()){ * int current = q.front(); q.pop(); * * for(auto next : connection[current]){ * if(prev[next] != -1) continue; * if(capacity[current][next] <= flow[current][next]) continue; * prev[next] = current; * * q.push(next); * } * } * * if(prev[T] == -1) break; * * for(int i = T; i != S; i = prev[i]){ * flow[prev[i]][i] += 1; * flow[i][prev[i]] -= 1; * } * * } * * for(int i = 1; i <= N; i++){ * for(int j = 1; j <= N; j++){ * if(flow[i][j + N]) result[i][j] = 1; * } * } * * if(!counting()) printf("-1"); * else{ * printf("1\n"); * for(int i = 1; i <= N; i++){ * for(int j = 1; j <= N; j++){ * printf("%d", result[i][j]); * } * printf("\n"); * } * } * } * * void linker(int from, int to, int cap){ * connection[from].push_back(to); * connection[to].push_back(from); * capacity[from][to] = cap; * } * * bool counting(){ * int sum[2]; * * for(int i = 1; i <= N; i++){ * sum[0] = 0; * sum[1] = 0; * * for(int j = 1; j <= N; j++) { * sum[0] += result[i][j]; * sum[1] += result[j][i]; * } * * if(sum[0] != row[i] || sum[1] != col[i]) return 0; * } * * return 1; * } * */
#!/bin/bash unameOut="$(uname -s)" case "${unameOut}" in Linux*) machine=Linux;; Darwin*) machine=Mac;; CYGWIN*) machine=Cygwin;; MINGW*) machine=MinGw;; *) machine="UNKNOWN:${unameOut}" esac # where am i? move to where I am. This ensures source is properly sourced DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $DIR cd .. rm -rf node_modules/@lrnwebcomponents mkdir node_modules/@lrnwebcomponents # go back a level so we can snag everything cd elements/ # walk each directory and update it's demo automatically for project in */ ; do cd ${project} p="$(basename -- $project)" rm -rf node_modules mkdir ../../node_modules/@lrnwebcomponents/${p} if [ "${machine}" == "MinGw" ]; then if [ -f "${p}.js" ]; then symlink-dir ../../../elements/${p}/${p}.js ../../node_modules/@lrnwebcomponents/${p}/${p}.js fi if [ -d "lib" ]; then symlink-dir ../../../elements/${p}/lib ../../node_modules/@lrnwebcomponents/${p}/lib fi if [ -d "locales" ]; then symlink-dir ../../../elements/${p}/locales ../../node_modules/@lrnwebcomponents/${p}/locales fi if [ -d "server" ]; then symlink-dir ../../../elements/${p}/server ../../node_modules/@lrnwebcomponents/${p}/server fi if [ -d "build" ]; then symlink-dir ../../../elements/${p}/build ../../node_modules/@lrnwebcomponents/${p}/build fi if [ -d "src" ]; then symlink-dir ../../../elements/${p}/src ../../node_modules/@lrnwebcomponents/${p}/src fi if [ -d "dist" ]; then symlink-dir ../../../elements/${p}/dist ../../node_modules/@lrnwebcomponents/${p}/dist fi else if [ -f "${p}.js" ]; then ln -s ../../../elements/${p}/${p}.js ../../node_modules/@lrnwebcomponents/${p}/${p}.js fi if [ -d "lib" ]; then ln -s ../../../elements/${p}/lib ../../node_modules/@lrnwebcomponents/${p}/lib fi if [ -d "locales" ]; then ln -s ../../../elements/${p}/locales ../../node_modules/@lrnwebcomponents/${p}/locales fi if [ -d "server" ]; then ln -s ../../../elements/${p}/server ../../node_modules/@lrnwebcomponents/${p}/server fi if [ -d "build" ]; then ln -s ../../../elements/${p}/build ../../node_modules/@lrnwebcomponents/${p}/build fi if [ -d "src" ]; then ln -s ../../../elements/${p}/src ../../node_modules/@lrnwebcomponents/${p}/src fi if [ -d "dist" ]; then ln -s ../../../elements/${p}/dist ../../node_modules/@lrnwebcomponents/${p}/dist fi fi cd ../ done
from flask import Flask, render_template app = Flask(__name__) @app.route('/city_jobs') def city_jobs(): city_jobs = [ { 'job': 'Developer', 'salary': 75000 }, { 'job': 'Doctor', 'salary': 80000 }, { 'job': 'Teacher', 'salary': 45000 }, { 'job': 'Chef', 'salary': 55000 } ] return render_template('city_jobs.html', city_jobs=city_jobs) if __name__ == '__main__': app.run(debug=True)
/* FWDU3DCarSlideshowButton */ (function(window) { var FWDU3DCarSlideshowButton = function(data) { var self = this; var prototype = FWDU3DCarSlideshowButton.prototype; this.playButtonNImg = data.playButtonNImg; this.playButtonSImg = data.playButtonSImg; this.pauseButtonImg = data.pauseButtonImg; this.timerButtonImg = data.slideshowTimerImg; this.playButtonDO; this.playButtonNDO; this.playButtonSDO; this.pauseButtonDO; this.timerButtonDO; this.timerButtonBgDO; this.timerButtonTextDO; this.delay = data.slideshowDelay; this.autoplay = data.autoplay; this.curSeconds = data.slideshowDelay/1000; this.isPlaying = false; this.isCounting = false; this.btnWidth = self.playButtonNImg.width; this.btnHeight = self.playButtonNImg.height; this.isMobile = FWDU3DCarUtils.isMobile; this.hasPointerEvent = FWDU3DCarUtils.hasPointerEvent; this.timeoutId; this.timerIntervalId; // ##########################################// /* initialize this */ // ##########################################// this.init = function() { self.setupMainContainers(); }; // ##########################################// /* setup main containers */ // ##########################################// this.setupMainContainers = function() { self.setButtonMode(true); self.setWidth(self.btnWidth); self.setHeight(self.btnHeight); self.setPauseButton(); self.settimerButton(); self.setPlayButton(); if (self.isMobile) { if (self.hasPointerEvent) { self.screen.addEventListener("MSPointerOver", self.onMouseOver); self.screen.addEventListener("MSPointerOut", self.onMouseOut); self.screen.addEventListener("MSPointerUp", self.onClick); } else { self.screen.addEventListener("touchend", self.onClick); } } else { if (window.addEventListener) { self.screen.addEventListener("mouseover", self.onMouseOver); self.screen.addEventListener("mouseout", self.onMouseOut); self.screen.addEventListener("click", self.onClick); } else { self.screen.attachEvent("onmouseover", self.onMouseOver); self.screen.attachEvent("onmouseout", self.onMouseOut); self.screen.attachEvent("onclick", self.onClick); } } }; this.settimerButton = function() { self.timerButtonDO = new FWDU3DCarDisplayObject("div"); self.addChild(self.timerButtonDO); self.timerButtonDO.setWidth(self.btnWidth); self.timerButtonDO.setHeight(self.btnHeight); self.timerButtonBgDO = new FWDU3DCarSimpleDisplayObject("img"); self.timerButtonBgDO.setScreen(self.timerButtonImg); self.timerButtonDO.addChild(self.timerButtonBgDO); self.timerButtonTextDO = new FWDU3DCarDisplayObject("div"); self.timerButtonDO.addChild(self.timerButtonTextDO); self.timerButtonTextDO.getStyle().fontSmoothing = "antialiased"; self.timerButtonTextDO.getStyle().webkitFontSmoothing = "antialiased"; self.timerButtonTextDO.getStyle().textRendering = "optimizeLegibility"; self.timerButtonTextDO.getStyle().fontFamily = "Arial, Helvetica, sans-serif"; self.timerButtonTextDO.getStyle().fontSize = "10px"; self.timerButtonTextDO.getStyle().color = data.slideshowTimerColor; if (self.curSeconds < 10) self.timerButtonTextDO.setInnerHTML("0" + self.curSeconds); else self.timerButtonTextDO.setInnerHTML(self.curSeconds); self.setTextPositionId = setTimeout(self.setTextPosition, 10); }; this.setTextPosition = function() { self.timerButtonTextDO.setX(Math.floor((self.btnWidth - self.timerButtonTextDO.getWidth())/2)); self.timerButtonTextDO.setY(Math.floor((self.btnHeight - self.timerButtonTextDO.getHeight())/2)); }; this.setPauseButton = function() { self.pauseButtonDO = new FWDU3DCarSimpleDisplayObject("img"); self.pauseButtonDO.setScreen(self.pauseButtonImg); self.addChild(self.pauseButtonDO); self.pauseButtonDO.setWidth(self.btnWidth); self.pauseButtonDO.setHeight(self.btnHeight); }; this.setPlayButton = function() { self.playButtonDO = new FWDU3DCarDisplayObject("div"); self.addChild(self.playButtonDO); self.playButtonSDO = new FWDU3DCarSimpleDisplayObject("img"); self.playButtonSDO.setScreen(self.playButtonSImg); self.playButtonDO.addChild(self.playButtonSDO); self.playButtonNDO = new FWDU3DCarSimpleDisplayObject("img"); self.playButtonNDO.setScreen(self.playButtonNImg); self.playButtonDO.addChild(self.playButtonNDO); self.playButtonDO.setWidth(self.btnWidth); self.playButtonDO.setHeight(self.btnHeight); }; this.onMouseOver = function() { if (self.isPlaying) { FWDU3DCarModTweenMax.to(self.timerButtonDO, .8, {alpha:0, ease : Expo.easeOut}); } else { FWDU3DCarModTweenMax.to(self.playButtonNDO, .8, {alpha:0, ease : Expo.easeOut}); } }; this.onMouseOut = function() { if (self.isPlaying) { FWDU3DCarModTweenMax.to(self.timerButtonDO, .8, {alpha:1, ease : Expo.easeOut}); } else { FWDU3DCarModTweenMax.to(self.playButtonNDO, .8, {alpha:1, ease : Expo.easeOut}); } }; this.onClick = function(e) { if (self.isPlaying) { self.stop(); self.dispatchEvent(FWDU3DCarSlideshowButton.PAUSE_CLICK); } else { self.start(); self.dispatchEvent(FWDU3DCarSlideshowButton.PLAY_CLICK); } if (!self.isMobile) { self.onMouseOver(); } }; this.start = function() { self.isPlaying = true; self.isCounting = true; self.playButtonDO.setAlpha(0); self.curSeconds = self.delay/1000; clearTimeout(self.timeoutId); clearInterval(self.timerIntervalId); self.timeoutId = setTimeout(self.onTimeHandler, self.delay); self.timerIntervalId = setInterval(self.onTickHandler, 1000); if (self.curSeconds < 10) self.timerButtonTextDO.setInnerHTML("0" + self.curSeconds); else self.timerButtonTextDO.setInnerHTML(self.curSeconds); }; this.stop = function() { self.isPlaying = false; self.isCounting = false; self.playButtonDO.setAlpha(1); clearTimeout(self.timeoutId); clearInterval(self.timerIntervalId); }; this.resetCounter = function() { self.isCounting = false; clearTimeout(self.timeoutId); clearInterval(self.timerIntervalId); self.curSeconds = self.delay/1000; if (self.curSeconds < 10) self.timerButtonTextDO.setInnerHTML("0" + self.curSeconds); else self.timerButtonTextDO.setInnerHTML(self.curSeconds); }; this.onTimeHandler = function() { self.isCounting = false; clearTimeout(self.timeoutId); clearInterval(self.timerIntervalId); self.onTickHandler(); self.dispatchEvent(FWDU3DCarSlideshowButton.TIME); }; this.onTickHandler = function() { self.curSeconds--; if (self.curSeconds < 10) self.timerButtonTextDO.setInnerHTML("0" + self.curSeconds); else self.timerButtonTextDO.setInnerHTML(self.curSeconds); }; // ##############################// /* destroy */ // ##############################// this.destroy = function() { clearTimeout(self.timeoutId); clearTimeout(self.setTextPositionId); clearInterval(self.timerIntervalId); if (self.isMobile) { if (self.hasPointerEvent) { self.screen.removeEventListener("MSPointerOver", self.onMouseOver); self.screen.removeEventListener("MSPointerOut", self.onMouseOut); self.screen.removeEventListener("MSPointerUp", self.onClick); } else { self.screen.removeEventListener("touchend", self.onClick); } } else { if (window.addEventListener) { self.screen.removeEventListener("mouseover", self.onMouseOver); self.screen.removeEventListener("mouseout", self.onMouseOut); self.screen.removeEventListener("click", self.onClick); } else { self.screen.detachEvent("onmouseover", self.onMouseOver); self.screen.detachEvent("onmouseout", self.onMouseOut); self.screen.detachEvent("onclick", self.onClick); } } FWDU3DCarModTweenMax.killTweensOf(self.timerButtonDO); FWDU3DCarModTweenMax.killTweensOf(self.playButtonNDO); self.playButtonDO.destroy(); self.playButtonNDO.destroy(); self.playButtonSDO.destroy(); self.pauseButtonDO.destroy(); self.timerButtonDO.destroy(); self.timerButtonBgDO.destroy(); self.timerButtonTextDO.destroy(); prototype.destroy(); self = null; prototype = null; FWDU3DCarSlideshowButton.prototype = null; }; this.init(); }; /* set prototype */ FWDU3DCarSlideshowButton.setPrototype = function() { FWDU3DCarSlideshowButton.prototype = new FWDU3DCarDisplayObject("div"); }; FWDU3DCarSlideshowButton.PLAY_CLICK = "onPlayClick"; FWDU3DCarSlideshowButton.PAUSE_CLICK = "onPauseClick"; FWDU3DCarSlideshowButton.TIME = "onTime"; FWDU3DCarSlideshowButton.prototype = null; window.FWDU3DCarSlideshowButton = FWDU3DCarSlideshowButton; }(window));
/* * Copyright (C) 2012 Atlassian * * 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.atlassian.jira.tests.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation allows to ignore tests depending on build number of JIRA. * * @since v0.1 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface JiraBuildNumberDependent { long value(); LongCondition condition() default LongCondition.GREATER_OR_EQUAL; }
#!/bin/sh # $Id: vboxguest.sh 69500 2017-10-28 15:14:05Z vboxsync $ ## @file # VirtualBox Guest Additions kernel module control script for Solaris. # # # Copyright (C) 2008-2017 Oracle Corporation # # This file is part of VirtualBox Open Source Edition (OSE), as # available from http://www.virtualbox.org. This file is free software; # you can redistribute it and/or modify it under the terms of the GNU # General Public License (GPL) as published by the Free Software # Foundation, in version 2 as it comes in the "COPYING" file of the # VirtualBox OSE distribution. VirtualBox OSE is distributed in the # hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. # # The contents of this file may alternatively be used under the terms # of the Common Development and Distribution License Version 1.0 # (CDDL) only, as it comes in the "COPYING.CDDL" file of the # VirtualBox OSE distribution, in which case the provisions of the # CDDL are applicable instead of those of the GPL. # # You may elect to license modified versions of this file under the # terms and conditions of either the GPL or the CDDL or both. # LC_ALL=C export LC_ALL LANG=C export LANG SILENTUNLOAD="" MODNAME="vboxguest" VFSMODNAME="vboxfs" VMSMODNAME="vboxms" MODDIR32="/usr/kernel/drv" MODDIR64="/usr/kernel/drv/amd64" VFSDIR32="/usr/kernel/fs" VFSDIR64="/usr/kernel/fs/amd64" abort() { echo 1>&2 "## $1" exit 1 } info() { echo 1>&2 "$1" } check_if_installed() { cputype=`isainfo -k` modulepath="$MODDIR32/$MODNAME" if test "$cputype" = "amd64"; then modulepath="$MODDIR64/$MODNAME" fi if test -f "$modulepath"; then return 0 fi abort "VirtualBox kernel module ($MODNAME) NOT installed." } module_loaded() { if test -z "$1"; then abort "missing argument to module_loaded()" fi modname=$1 # modinfo should now work properly since we prevent module autounloading. loadentry=`/usr/sbin/modinfo | grep "$modname "` if test -z "$loadentry"; then return 1 fi return 0 } vboxguest_loaded() { module_loaded $MODNAME return $? } vboxfs_loaded() { module_loaded $VFSMODNAME return $? } vboxms_loaded() { module_loaded $VMSMODNAME return $? } check_root() { # the reason we don't use "-u" is that some versions of id are old and do not # support this option (eg. Solaris 10) and do not have a "--version" to check it either # so go with the uglier but more generic approach idbin=`which id` isroot=`$idbin | grep "uid=0"` if test -z "$isroot"; then abort "This program must be run with administrator privileges. Aborting" fi } start_module() { /usr/sbin/add_drv -i'pci80ee,cafe' -m'* 0666 root sys' $MODNAME if test ! vboxguest_loaded; then abort "Failed to load VirtualBox guest kernel module." elif test -c "/devices/pci@0,0/pci80ee,cafe@4:$MODNAME"; then info "VirtualBox guest kernel module loaded." else info "VirtualBox guest kernel module failed to attach." fi } stop_module() { if vboxguest_loaded; then /usr/sbin/rem_drv $MODNAME || abort "Failed to unload VirtualBox guest kernel module." info "VirtualBox guest kernel module unloaded." elif test -z "$SILENTUNLOAD"; then info "VirtualBox guest kernel module not loaded." fi } start_vboxfs() { if vboxfs_loaded; then info "VirtualBox FileSystem kernel module already loaded." else /usr/sbin/modload -p fs/$VFSMODNAME || abort "Failed to load VirtualBox FileSystem kernel module." if test ! vboxfs_loaded; then info "Failed to load VirtualBox FileSystem kernel module." else info "VirtualBox FileSystem kernel module loaded." fi fi } stop_vboxfs() { if vboxfs_loaded; then vboxfs_mod_id=`/usr/sbin/modinfo | grep $VFSMODNAME | cut -f 1 -d ' ' ` if test -n "$vboxfs_mod_id"; then /usr/sbin/modunload -i $vboxfs_mod_id || abort "Failed to unload VirtualBox FileSystem module." info "VirtualBox FileSystem kernel module unloaded." fi elif test -z "$SILENTUNLOAD"; then info "VirtualBox FileSystem kernel module not loaded." fi } start_vboxms() { /usr/sbin/add_drv -m'* 0666 root sys' $VMSMODNAME if test ! vboxms_loaded; then abort "Failed to load VirtualBox pointer integration module." elif test -c "/devices/pseudo/$VMSMODNAME@0:$VMSMODNAME"; then info "VirtualBox pointer integration module loaded." else info "VirtualBox pointer integration module failed to attach." fi } stop_vboxms() { if vboxms_loaded; then /usr/sbin/rem_drv $VMSMODNAME || abort "Failed to unload VirtualBox pointer integration module." info "VirtualBox pointer integration module unloaded." elif test -z "$SILENTUNLOAD"; then info "VirtualBox pointer integration module not loaded." fi } status_module() { if vboxguest_loaded; then info "Running." else info "Stopped." fi } stop_all() { stop_vboxms stop_vboxfs stop_module return 0 } restart_all() { stop_all start_module start_vboxfs start_vboxms return 0 } check_root check_if_installed if test "$2" = "silentunload"; then SILENTUNLOAD="$2" fi case "$1" in stopall) stop_all ;; restartall) restart_all ;; start) start_module start_vboxms ;; stop) stop_vboxms stop_module ;; status) status_module ;; vfsstart) start_vboxfs ;; vfsstop) stop_vboxfs ;; vmsstart) start_vboxms ;; vmsstop) stop_vboxms ;; *) echo "Usage: $0 {start|stop|restart|status}" exit 1 esac exit 0
<table> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th> <th>Column 5</th> </tr> <tr> <td> <?php echo mt_rand(); ?> </td> <td> <?php echo mt_rand(); ?> </td> <td> <?php echo mt_rand(); ?> </td> <td> <?php echo mt_rand(); ?> </td> <td> <?php echo mt_rand(); ?> </td> </tr> <!-- Add 7 more rows here with the same format as above--> </table>
const _ = require('underscore'); const DrawCard = require('../../../drawcard.js'); class HouseManderlyKnight extends DrawCard { setupCardAbilities(ability) { this.persistentEffect({ condition: () => _.any(this.game.getPlayers(), player => player.activePlot && player.activePlot.hasTrait('Winter')), match: this, effect: ability.effects.modifyStrength(2) }); } } HouseManderlyKnight.code = '04101'; module.exports = HouseManderlyKnight;
# Copyright (c) 2020 - for information on the respective copyright owner # see the NOTICE file and/or the repository https://github.com/boschresearch/blackboxopt # # SPDX-License-Identifier: Apache-2.0 # # This source code is derived from HpBandSter 0.7.4 # https://github.com/automl/HpBandSter # Copyright (c) 2017-2018, ML4AAD, licensed under the BSD-3 license, # cf. 3rd-party-licenses.txt file in the root directory of this source tree. # Changes include: # - integration into the blackboxopt API # - docstrings and type hints import logging from parameterspace.base import SearchSpace from blackboxopt import Objective try: from blackboxopt.optimizers.staged.bohb import Sampler as BOHBSampler from blackboxopt.optimizers.staged.hyperband import create_hyperband_iteration from blackboxopt.optimizers.staged.optimizer import StagedIterationOptimizer except ImportError as e: raise ImportError( "Unable to import BOHB optimizer specific dependencies. " + "Make sure to install blackboxopt[bohb]" ) from e class BOHB(StagedIterationOptimizer): def __init__( self, search_space: SearchSpace, objective: Objective, min_fidelity: float, max_fidelity: float, num_iterations: int, eta: float = 3.0, top_n_percent: int = 15, min_samples_in_model: int = None, num_samples: int = 64, random_fraction: float = 1 / 3, bandwidth_factor: float = 3.0, min_bandwidth: float = 1e-3, seed: int = None, logger: logging.Logger = None, ): """BOHB Optimizer. BOHB performs robust and efficient hyperparameter optimization at scale by combining the speed of Hyperband searches with the guidance and guarantees of convergence of Bayesian Optimization. Instead of sampling new configurations at random, BOHB uses kernel density estimators to select promising candidates. For reference: ``` @InProceedings{falkner-icml-18, title = {{BOHB}: Robust and Efficient Hyperparameter Optimization at Scale}, author = {<NAME> and <NAME> and <NAME>}, booktitle = {Proceedings of the 35th International Conference on Machine Learning}, pages = {1436--1445}, year = {2018}, } ``` Args: search_space: [description] objective: [description] min_fidelity: The smallest fidelity value that is still meaningful. Must be strictly greater than zero! max_fidelity: The largest fidelity value used during the optimization. Must not be smaller than `min_fidelity`. num_iterations: The number of iterations that the optimizer will run. eta: Scaling parameter to control the aggressiveness of Hyperband's racing. top_n_percent: Determines the percentile of configurations that will be used as training data for the kernel density estimator of the good configuration, e.g if set to 10 the best 10% configurations will be considered for training. min_samples_in_model: Minimum number of datapoints needed to fit a model. num_samples: Number of samples drawn to optimize EI via sampling. random_fraction: Fraction of random configurations returned. bandwidth_factor: Widens the bandwidth for contiuous parameters for proposed points to optimize EI min_bandwidth: to keep diversity, even when all (good) samples have the same value for one of the parameters, a minimum bandwidth (reasonable default: 1e-3) is used instead of zero. seed: [description] logger: [description] """ if min_samples_in_model is None: min_samples_in_model = 3 * len(search_space) self.min_fidelity = min_fidelity self.max_fidelity = max_fidelity self.eta = eta self.config_sampler = BOHBSampler( search_space=search_space, objective=objective, min_samples_in_model=min_samples_in_model, top_n_percent=top_n_percent, num_samples=num_samples, random_fraction=random_fraction, bandwidth_factor=bandwidth_factor, min_bandwidth=min_bandwidth, ) super().__init__( search_space=search_space, objective=objective, num_iterations=num_iterations, seed=seed, logger=logger, ) def _create_new_iteration(self, iteration_index): """Optimizer specific way to create a new `blackboxopt.optimizer.utils.staged_iteration.StagedIteration` object """ return create_hyperband_iteration( iteration_index, self.min_fidelity, self.max_fidelity, self.eta, self.config_sampler, self.objective, self.logger, )
<reponame>danilovalente/mashery-toolbelt-1<filename>examples/api.js const MasheryClient = require('../src/lib/client') const credentials = { username: `YOUR USERNAME`, password: `<PASSWORD>`, key: `APP KEY`, secret: `APP SECRET`, scope: `AREA UUID`, } // Authenticate on demenad const client = new MasheryClient() client.authenticate(credentials) .then(() => { client.fetchAllServices() .then(data => console.log('done: ', data)) .catch(error => console.error('request error: ', error.message)) }) .catch(error => console.error('auth error: ', error.message)) // Authenticate automatically on first request const client2 = new MasheryClient({ credentials, onAuthenticationError: error => console.error('auth error: ', error.message) }) client2.fetchAllServices() .then(data => console.log('done: ', data)) .catch(error => console.error('error: ', error))
<reponame>undecaf/vue-boilerplate<filename>tests/unit/03-event-bus.spec.js import Vue from 'vue' import options from '@/config' import { emitEventBus, onEventBus } from '@/services/event-bus' const config = options(Vue) /** * TODO Tests the event bus */ describe('Event bus', () => { })
#!/bin/bash # create multiresolution windows icon #mainnet ICON_SRC=../../src/qt/res/icons/zeon.png ICON_DST=../../src/qt/res/icons/zeon.ico convert ${ICON_SRC} -resize 16x16 zeon-16.png convert ${ICON_SRC} -resize 32x32 zeon-32.png convert ${ICON_SRC} -resize 48x48 zeon-48.png convert zeon-16.png zeon-32.png zeon-48.png ${ICON_DST} #testnet ICON_SRC=../../src/qt/res/icons/zeon_testnet.png ICON_DST=../../src/qt/res/icons/zeon_testnet.ico convert ${ICON_SRC} -resize 16x16 zeon-16.png convert ${ICON_SRC} -resize 32x32 zeon-32.png convert ${ICON_SRC} -resize 48x48 zeon-48.png convert zeon-16.png zeon-32.png zeon-48.png ${ICON_DST} rm zeon-16.png zeon-32.png zeon-48.png
#!/bin/bash set -e if [[ $# -eq 0 ]] ; then echo "Enter project name" exit 0 fi cd {{ home }}/$1 {% if is_prod -%} git pull {%- endif %} yarn install yarn build source /opt/$1/env/bin/activate pip install -r requirements.txt --exists-action s cd /opt/$1/project/src ./manage.py migrate ./manage.py collectstatic --noinput {% if is_prod -%} systemctl restart $1-wsgi service nginx restart {%- endif %}
/* * * Created on: 2020年10月1日 * Author: Lzy */ #include "usermainwid.h" #include "ui_usermainwid.h" UserMainWid::UserMainWid(QWidget *parent) : QWidget(parent), ui(new Ui::UserMainWid) { ui->setupUi(this); LandingUser::get(); mBtnBar = new UserBtnBar; mDbTable = new SqlTableWid(ui->groupBox); mDbTable->initWid(DbUser::bulid(), mBtnBar); } UserMainWid::~UserMainWid() { delete ui; }
<gh_stars>0 import { Mutation, Resolver, Args, Query } from '@nestjs/graphql' import { UrlEntity } from './url.entity' import { UrlService } from './url.service' import { UseGuards } from '@nestjs/common' import { AuthGuard } from '../user/auth.guard' @Resolver((of) => UrlEntity) export class UrlResolver { constructor(private readonly urlService: UrlService) {} @Mutation((returns) => UrlEntity) @UseGuards(new AuthGuard()) async shorten(@Args('original') original: string) { return this.urlService.create(original) } @Query((returns) => [UrlEntity]) @UseGuards(new AuthGuard()) urls() { return this.urlService.findAll() } @Query((returns) => UrlEntity) url(@Args('shortcut') shortcut: string) { return this.urlService.find(shortcut) } }
<gh_stars>0 import { Injectable } from '@nestjs/common'; import { User } from '../../../entities/user.entity'; import { getConnection, getRepository } from 'typeorm'; const bcrypt = require('bcryptjs'); @Injectable() export class UserService { async createUser(body) { try { const query = await getConnection() .createQueryBuilder() .insert() .into(User) .values(body) .execute(); if (query.raw.affectedRows > 0) { return true; } } catch (error) { return false; } } async getUserByEmail(email) { const query = await getRepository(User) .createQueryBuilder('user') .select('user.password') .addSelect('user.id') .where('user.email = :email', { email: email }) .getOne(); return query; } async getUserById(id) { const data = await getRepository(User) .createQueryBuilder('user') .select('user.fullName') .addSelect('user.email') .addSelect('user.address') .where('user.id = :id', { id: id }) .getOne(); return data; } async updateUser(body, id) { if (body.password) { const saltRounds = 10; const hash = await bcrypt.hash(body.password, saltRounds); body.password = hash; } const query = await getConnection() .createQueryBuilder() .update(User) .set(body) .where('id = :id', { id: id }) .execute(); if (query.raw.affectedRows > 0) { return true; } else { return false; } } }
#!/bin/bash /home/jizong/.conda/envs/pingao/bin/python train.py exp0008_seizurev16_11_server2.yaml /home/jizong/.conda/envs/pingao/bin/python train.py exp0008_seizurev16_12_server2.yaml /home/jizong/.conda/envs/pingao/bin/python train.py exp0008_seizurev16_13_server2.yaml
#!/bin/bash cd "$(dirname "$BASH_SOURCE")" \ && source '../utils.sh' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - set_preferences() { execute 'defaults write com.apple.terminal FocusFollowsMouse -string true' \ 'Make the focus automatically follow the mouse' execute 'defaults write com.apple.terminal StringEncodings -array 4' \ 'Only use UTF-8' osascript <<EOD tell application "Terminal" local allOpenedWindows local initialOpenedWindows local windowID set themeName to "Solarized Dark" (* Store the IDs of all the open terminal windows *) set initialOpenedWindows to id of every window (* Open the custom theme so that it gets added to the list of available terminal themes (note: this will open two additional terminal windows) *) do shell script "open '" & themeName & ".terminal'" (* Wait a little bit to ensure that the custom theme is added *) delay 1 (* Set the custom theme as the default terminal theme *) set default settings to settings set themeName (* Get the IDs of all the currently opened terminal windows *) set allOpenedWindows to id of every window repeat with windowID in allOpenedWindows (* Close the additional windows that were opened in order to add the custom theme to the list of terminal themes *) if initialOpenedWindows does not contain windowID then close (every window whose id is windowID) (* Change the theme for the initial opened terminal windows to remove the need to close them in order for the custom theme to be applied *) else set current settings of tabs of (every window whose id is windowID) to settings set themeName end if end repeat end tell EOD print_result $? 'Set custom terminal theme' } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - main() { print_in_purple '\n Terminal\n\n' set_preferences } main
import React from "react" const GalleryCard = props => { return ( <> <div className="gallery-item double-column"> <div className="gallery-image"></div> <div className="gallery-header"> <h1> </h1> <div className="gallery-header-sub"></div> </div> </div> </> ) } export default GalleryCard
<reponame>Ashindustry007/competitive-programming // https://www.codechef.com/AUG17/problems/RAINBOWA #include <iostream> #include <vector> using namespace std; typedef vector<int> vi; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int n; cin >> n; vi xs(n); for (int j = 0; j < n; j++) { cin >> xs[j]; }; bool ok = true; int current = 0; int j = 0; int k = n - 1; while (j < k) { if (xs[j] != xs[k]) { ok = false; break; } if (xs[j] < 1 || xs[j] > 7) { ok = false; break; } if (xs[j] != current && xs[j] != current + 1) { ok = false; break; } current = xs[j]; j++; k--; } if (xs[n/2] != 7) ok = false; cout << (ok ? "yes" : "no") << endl; } }
userProfile.controller('activityController', function($scope,$http) { // create a message to display in our view $scope.invalid_login = true; $scope.unexpected_error = true; console.log("inside user activity controller"); init(); function init() { $scope.disableBuyActivity= true; $scope.disableSellActivity= true; $scope.disableBidActivity= true; $scope.disableAuctionWonActivity= true; $http({ method: "POST", url: '/getAllUserDirectBuyingActivities', data: {} }).success(function (data) { console.log("inside success"); console.log("data is ::"); console.log(data); $scope.allItemsInActivity = data.results[0].PurchasedProducts; if(data.statusCode!=401) { $scope.disableBuyActivity= false; } //set all variables. }).error(function (error) { console.log("inside error"); console.log(error); $scope.unexpected_error = false; $scope.invalid_login = true; $window.alert("unexpected_error"); $scope.disableBuyActivity= true; }); $http({ method: "POST", url: '/getAllSoldProducts', data: {} }).success(function (data1) { console.log("inside success"); console.log("data is ::"); console.log(data1); $scope.allSoldProducts = data1.results[0].SoldProducts; if(data1.statusCode!=401) { $scope.disableSellActivity= false; } //set all variables. }).error(function (error) { console.log("inside error"); console.log(error); $scope.unexpected_error = false; $scope.invalid_login = true; $window.alert("unexpected_error"); $scope.disableSellActivity= true; }); $http({ method: "POST", url: '/getAllUserBiddingActivity', data: {} }).success(function (data1) { console.log("inside success"); console.log("data is ::"); console.log(data1); $scope.AllUserBiddingActivity = data1.results[0].BidPlacedOnProducts; if(data1.statusCode!=401) { $scope.disableBidActivity= false; } //set all variables. }).error(function (error) { console.log("inside error"); console.log(error); $scope.unexpected_error = false; $scope.invalid_login = true; $window.alert("unexpected_error"); $scope.disableBidActivity= true; }); $http({ method: "POST", url: '/getAllAuctionProductHistory', data: {} }).success(function (data2) { console.log("inside success"); console.log("data is ::"); console.log(data2); $scope.AllUserAuctionsWonActivity = data2.results[0].AuctionsWonOnProducts; if(data2.statusCode!=401) { $scope.disableAuctionWonActivity= false; } }).error(function (error) { console.log("inside error"); console.log(error); $scope.unexpected_error = false; $scope.invalid_login = true; $window.alert("unexpected_error"); $scope.disableAuctionWonActivity= true; }); } });
<reponame>liuyeming1997/Magnus<filename>Magnus/src/Magnus/ImGui/imGuiBuild.cpp #include "mgpch.h" #define IMGUI_IMPL_OPENGL_LOADER_GLAD #include "examples/imgui_impl_opengl3.cpp" #include "examples/imgui_impl_glfw.cpp"
/* Copyright 2009-2015 <NAME> * * This file is part of the MOEA Framework. * * The MOEA Framework is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * The MOEA Framework is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>. */ package org.moeaframework.analysis.sensitivity; import java.io.File; import java.io.IOException; import java.io.PrintStream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.math3.stat.StatUtils; import org.moeaframework.core.PRNG; import org.moeaframework.util.CommandLineUtility; /** * Global sensitivity analysis of blackbox model output using Saltelli's * improved Sobol' global variance decomposition procedure. * <p> * The following code was derived and translated from the C code used in the * study cited below. Refer to this article for a description of the procedure. * <p> * References: * <ol> * <li><NAME>., <NAME>., <NAME>., and <NAME>., "Comparing * Sensitivity Analysis Methods to Advance Lumped Watershed Model Identification * and Evaluation," Hydrology and Earth System Sciences, vol. 11, no. 2, pp. * 793-817, 2007. * <li><NAME>., et al. "Global Sensitivity Analysis: The Primer." John * Wiley & Sons Ltd, 2008. * </ol> */ public class SobolAnalysis extends CommandLineUtility { /** * Number of resamples used to bootstrap the 50% confidence intervals. */ private int resamples = 1000; /** * Parameters being analyzed. */ private ParameterFile parameterFile; /** * Number of parameters. */ private int P; /** * Number of samples. */ private int N; /** * Index of the metric being evaluated. */ private int index; /** * Output from the original parameters. */ private double[] A; /** * Output from the resampled parameters. */ private double[] B; /** * Output from the original samples where the j-th parameter is replaced by * the corresponding resampled parameter. */ private double[][] C_A; /** * Output from the resampled samples where the j-th parameter is replaced by * the corresponding original parameter. */ private double[][] C_B; /** * Constructs the command line utility for global sensitivity analysis * using Sobol's global variance decomposition based on Saltelli's work. */ public SobolAnalysis() { super(); } /** * Loads the outputs from the file. Each line in the file must contain the * output produced using the parameters generated by SobolSequence. * * @param file the model output file * @throws IOException if an I/O error occurred */ private void load(File file) throws IOException { MatrixReader reader = null; try { reader = new MatrixReader(file); A = new double[N]; B = new double[N]; C_A = new double[N][P]; C_B = new double[N][P]; for (int i = 0; i < N; i++) { A[i] = reader.next()[index]; for (int j = 0; j < P; j++) { C_A[i][j] = reader.next()[index]; } for (int j = 0; j < P; j++) { C_B[i][j] = reader.next()[index]; } B[i] = reader.next()[index]; } } finally { if (reader != null) { reader.close(); } } } /** * Computes and displays the first-, total-, and second- order Sobol' * sensitivities and 50% bootstrap confidence intervals. * * @param output the output stream */ private void display(PrintStream output) { output.println("Parameter Sensitivity [Confidence]"); output.println("First-Order Effects"); for (int j = 0; j < P; j++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_A[i][j]; a2[i] = B[i]; } output.print(" "); output.print(parameterFile.get(j).getName()); output.print(' '); output.print(computeFirstOrder(a0, a1, a2, N)); output.print(" ["); output.print(computeFirstOrderConfidence(a0, a1, a2, N, resamples)); output.println(']'); } output.println("Total-Order Effects"); for (int j = 0; j < P; j++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_A[i][j]; a2[i] = B[i]; } output.print(" "); output.print(parameterFile.get(j).getName()); output.print(' '); output.print(computeTotalOrder(a0, a1, a2, N)); output.print(" ["); output.print(computeTotalOrderConfidence(a0, a1, a2, N, resamples)); output.println(']'); } output.println("Second-Order Effects"); for (int j = 0; j < P; j++) { for (int k = j + 1; k < P; k++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; double[] a3 = new double[N]; double[] a4 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_B[i][j]; a2[i] = C_A[i][k]; a3[i] = C_A[i][j]; a4[i] = B[i]; } output.print(" "); output.print(parameterFile.get(j).getName()); output.print(" * "); output.print(parameterFile.get(k).getName()); output.print(' '); output.print(computeSecondOrder(a0, a1, a2, a3, a4, N)); output.print(" ["); output.print(computeSecondOrderConfidence(a0, a1, a2, a3, a4, N, resamples)); output.println(']'); } } } /** * Computes and displays the first- and total-order Sobol' sensitivites and * 50% bootstrap confidence intervals. * * @param output the output stream */ private void displaySimple(PrintStream output) { output.println("First-Order Effects"); for (int j = 0; j < P; j++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_A[i][j]; a2[i] = B[i]; } double value = computeFirstOrder(a0, a1, a2, N); output.print(value < 0 ? 0.0 : value); if (j < P - 1) { output.print('\t'); } } output.println(); output.println("Total-Order Effects"); for (int j = 0; j < P; j++) { double[] a0 = new double[N]; double[] a1 = new double[N]; double[] a2 = new double[N]; for (int i = 0; i < N; i++) { a0[i] = A[i]; a1[i] = C_A[i][j]; a2[i] = B[i]; } double value = computeTotalOrder(a0, a1, a2, N); output.print(value < 0 ? 0.0 : value); if (j < P - 1) { output.print('\t'); } } output.println(); } /** * Returns the first-order confidence interval of the i-th parameter. The * arguments to this method mirror the arguments to * {@link #computeFirstOrder}. * * @param a0 the output from the first independent samples * @param a1 the output from the samples produced by swapping the i-th * parameter in the first independent samples with the i-th parameter * from the second independent samples * @param a2 the output from the second independent samples * @param nsample the number of samples * @param nresample the number of resamples used when calculating the * confidence interval * @return the first-order confidence interval of the i-th parameter */ private static double computeFirstOrderConfidence(double[] a0, double[] a1, double[] a2, int nsample, int nresample) { double[] b0 = new double[nsample]; double[] b1 = new double[nsample]; double[] b2 = new double[nsample]; double[] s = new double[nresample]; for (int i = 0; i < nresample; i++) { for (int j = 0; j < nsample; j++) { int index = PRNG.nextInt(nsample); b0[j] = a0[index]; b1[j] = a1[index]; b2[j] = a2[index]; } s[i] = computeFirstOrder(b0, b1, b2, nsample); } double ss = StatUtils.sum(s) / nresample; double sss = 0.0; for (int i = 0; i < nresample; i++) { sss += Math.pow(s[i] - ss, 2.0); } return 1.96 * Math.sqrt(sss / (nresample - 1)); } /** * Returns the first-order sensitivity of the i-th parameter. Note how * the contents of the array {@code a1} specify the parameter being * analyzed. * * @param a0 the output from the first independent samples * @param a1 the output from the samples produced by swapping the i-th * parameter in the first independent samples with the i-th parameter * from the second independent samples * @param a2 the output from the second independent samples * @param nsample the number of samples * @return the first-order sensitivity of the i-th parameter */ private static double computeFirstOrder(double[] a0, double[] a1, double[] a2, int nsample) { double c = 0.0; for (int i = 0; i < nsample; i++) { c += a0[i]; } c /= nsample; double tmp1 = 0.0; double tmp2 = 0.0; double tmp3 = 0.0; double EY2 = 0.0; for (int i = 0; i < nsample; i++) { EY2 += (a0[i] - c) * (a2[i] - c); tmp1 += (a2[i] - c) * (a2[i] - c); tmp2 += (a2[i] - c); tmp3 += (a1[i] - c) * (a2[i] - c); } EY2 /= nsample; double V = (tmp1 / (nsample - 1)) - Math.pow(tmp2 / nsample, 2.0); double U = tmp3 / (nsample - 1); return (U - EY2) / V; } /** * Returns the total-order sensitivity of the i-th parameter. Note how * the contents of the array {@code a1} specify the parameter being * analyzed. * * @param a0 the output from the first independent samples * @param a1 the output from the samples produced by swapping the i-th * parameter in the first independent samples with the i-th parameter * from the second independent samples * @param a2 the output from the second independent samples * @param nsample the number of samples * @return the total-order sensitivity of the i-th parameter */ private static double computeTotalOrder(double[] a0, double[] a1, double[] a2, int nsample) { double c = 0.0; for (int i = 0; i < nsample; i++) { c += a0[i]; } c /= nsample; double tmp1 = 0.0; double tmp2 = 0.0; double tmp3 = 0.0; for (int i = 0; i < nsample; i++) { tmp1 += (a0[i] - c) * (a0[i] - c); tmp2 += (a0[i] - c) * (a1[i] - c); tmp3 += (a0[i] - c); } double EY2 = Math.pow(tmp3 / nsample, 2.0); double V = (tmp1 / (nsample - 1)) - EY2; double U = tmp2 / (nsample - 1); return 1.0 - ((U - EY2) / V); } /** * Returns the total-order confidence interval of the i-th parameter. The * arguments to this method mirror the arguments to * {@link #computeTotalOrder}. * * @param a0 the output from the first independent samples * @param a1 the output from the samples produced by swapping the i-th * parameter in the first independent samples with the i-th parameter * from the second independent samples * @param a2 the output from the second independent samples * @param nsample the number of samples * @param nresample the number of resamples used when calculating the * confidence interval * @return the total-order confidence interval of the i-th parameter */ private static double computeTotalOrderConfidence(double[] a0, double[] a1, double[] a2, int nsample, int nresample) { double[] b0 = new double[nsample]; double[] b1 = new double[nsample]; double[] b2 = new double[nsample]; double[] s = new double[nresample]; for (int i = 0; i < nresample; i++) { for (int j = 0; j < nsample; j++) { int index = PRNG.nextInt(nsample); b0[j] = a0[index]; b1[j] = a1[index]; b2[j] = a2[index]; } s[i] = computeTotalOrder(b0, b1, b2, nsample); } double ss = StatUtils.sum(s) / nresample; double sss = 0.0; for (int i = 0; i < nresample; i++) { sss += Math.pow(s[i] - ss, 2.0); } return 1.96 * Math.sqrt(sss / (nresample - 1)); } /** * Returns the second-order sensitivity of the i-th and j-th parameters. * Note how the contents of the arrays {@code a1}, {@code a2}, and * {@code a3} specify the two parameters being analyzed. * * @param a0 the output from the first independent samples * @param a1 the output from the samples produced by swapping the i-th * parameter in the second independent samples with the i-th * parameter from the first independent samples * @param a2 the output from the samples produced by swapping the j-th * parameter in the first independent samples with the j-th parameter * from the second independent samples * @param a3 the output from the samples produced by swapping the i-th * parameter in the first independent samples with the i-th parameter * from the second independent samples * @param a4 the output from the second independent samples * @param nsample the number of samples * @param nresample the number of resamples used when calculating the * confidence interval * @return the second-order sensitivity of the i-th and j-th parameters */ private static double computeSecondOrder(double[] a0, double[] a1, double[] a2, double[] a3, double[] a4, int nsample) { double c = 0.0; for (int i = 0; i < nsample; i++) { c += a0[i]; } c /= nsample; double EY = 0.0; double EY2 = 0.0; double tmp1 = 0.0; double tmp2 = 0.0; double tmp3 = 0.0; double tmp4 = 0.0; double tmp5 = 0.0; for (int i = 0; i < nsample; i++) { EY += (a0[i] - c) * (a4[i] - c); EY2 += (a1[i] - c) * (a3[i] - c); tmp1 += (a1[i] - c) * (a1[i] - c); tmp2 += (a1[i] - c); tmp3 += (a1[i] - c) * (a2[i] - c); tmp4 += (a2[i] - c) * (a4[i] - c); tmp5 += (a3[i] - c) * (a4[i] - c); } EY /= nsample; EY2 /= nsample; double V = (tmp1 / (nsample - 1)) - Math.pow(tmp2 / nsample, 2.0); double Vij = (tmp3 / (nsample - 1)) - EY2; double Vi = (tmp4 / (nsample - 1)) - EY; double Vj = (tmp5 / (nsample - 1)) - EY2; return (Vij - Vi - Vj) / V; } /** * Returns the second-order confidence interval of the i-th and j-th * parameters. The arguments to this method mirror the arguments to * {@link #computeSecondOrder}. * * @param a0 the output from the first independent samples * @param a1 the output from the samples produced by swapping the i-th * parameter in the second independent samples with the i-th * parameter from the first independent samples * @param a2 the output from the samples produced by swapping the j-th * parameter in the first independent samples with the j-th parameter * from the second independent samples * @param a3 the output from the samples produced by swapping the i-th * parameter in the first independent samples with the i-th parameter * from the second independent samples * @param a4 the output from the second independent samples * @param nsample the number of samples * @return the second-order confidence interval of the i-th and j-th * parameters */ private static double computeSecondOrderConfidence(double[] a0, double[] a1, double[] a2, double[] a3, double[] a4, int nsample, int nresample) { double[] b0 = new double[nsample]; double[] b1 = new double[nsample]; double[] b2 = new double[nsample]; double[] b3 = new double[nsample]; double[] b4 = new double[nsample]; double[] s = new double[nresample]; for (int i = 0; i < nresample; i++) { for (int j = 0; j < nsample; j++) { int index = PRNG.nextInt(nsample); b0[j] = a0[index]; b1[j] = a1[index]; b2[j] = a2[index]; b3[j] = a3[index]; b4[j] = a4[index]; } s[i] = computeSecondOrder(b0, b1, b2, b3, b4, nsample); } double ss = StatUtils.sum(s) / nresample; double sss = 0.0; for (int i = 0; i < nresample; i++) { sss += Math.pow(s[i] - ss, 2.0); } return 1.96 * Math.sqrt(sss / (nresample - 1)); } /** * Ensures the model output file contains N*(2P+2) lines and returns N, the * number of samples. * * @param file the model output file being validated * @return the number of samples * @throws IOException */ private int validate(File file) throws IOException { MatrixReader reader = null; try { reader = new MatrixReader(file); int count = 0; while (reader.hasNext()) { if (reader.next().length > index) { count++; } else { break; } } if (count % (2 * P + 2) != 0) { System.err.println(file + " is incomplete"); } return count / (2 * P + 2); } finally { if (reader != null) { reader.close(); } } } @SuppressWarnings("static-access") @Override public Options getOptions() { Options options = super.getOptions(); options.addOption(OptionBuilder .withLongOpt("parameterFile") .hasArg() .withArgName("file") .isRequired() .create('p')); options.addOption(OptionBuilder .withLongOpt("input") .hasArg() .withArgName("file") .isRequired() .create('i')); options.addOption(OptionBuilder .withLongOpt("metric") .hasArg() .withArgName("value") .isRequired() .create('m')); options.addOption(OptionBuilder .withLongOpt("simple") .create('s')); options.addOption(OptionBuilder .withLongOpt("output") .hasArg() .withArgName("file") .create('o')); options.addOption(OptionBuilder .withLongOpt("resamples") .hasArg() .withArgName("number") .create('r')); return options; } @Override public void run(CommandLine commandLine) throws Exception { PrintStream output = null; //setup the parameters parameterFile = new ParameterFile(new File( commandLine.getOptionValue("parameterFile"))); index = Integer.parseInt(commandLine.getOptionValue("metric")); P = parameterFile.size(); if (commandLine.hasOption("resamples")) { resamples = Integer.parseInt(commandLine.getOptionValue( "resamples")); } //load and validate the model output file File input = new File(commandLine.getOptionValue("input")); N = validate(input); load(input); try { //setup the output stream if (commandLine.hasOption("output")) { output = new PrintStream(new File( commandLine.getOptionValue("output"))); } else { output = System.out; } //perform the Sobol analysis and display the results if (commandLine.hasOption("simple")) { displaySimple(output); } else { display(output); } } finally { if ((output != null) && (output != System.out)) { output.close(); } } } /** * Command line utility for global sensitivity analysis using Sobol's global * variance decomposition based on Saltelli's work. * * @param args the command line arguments * @throws Exception if an error occurred */ public static void main(String[] args) throws Exception { new SobolAnalysis().start(args); } }
#!/bin/bash # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Creates an interop worker on GCE. # IMPORTANT: After this script finishes, there are still some manual # steps needed there are hard to automatize. # See go/grpc-jenkins-setup for followup instructions. set -ex cd $(dirname $0) CLOUD_PROJECT=grpc-testing ZONE=us-east1-a # canary gateway is reachable from this zone INSTANCE_NAME="${1:-grpc-canary-interop2}" gcloud compute instances create $INSTANCE_NAME \ --project="$CLOUD_PROJECT" \ --zone "$ZONE" \ --machine-type n1-standard-16 \ --image ubuntu-15-10 \ --boot-disk-size 1000 \ --scopes https://www.googleapis.com/auth/xapi.zoo echo 'Created GCE instance, waiting 60 seconds for it to come online.' sleep 60 gcloud compute copy-files \ --project="$CLOUD_PROJECT" \ --zone "$ZONE" \ jenkins_master.pub linux_worker_init.sh ${INSTANCE_NAME}:~ gcloud compute ssh \ --project="$CLOUD_PROJECT" \ --zone "$ZONE" \ $INSTANCE_NAME --command "./linux_worker_init.sh"
from torch.utils.data import Dataset, DataLoader from tqdm.autonotebook import tqdm import torch from PIL import Image import numpy as np from torch.nn.utils.rnn import pad_sequence """ Write your own dataset here. The __getitem__ method must return a dict with the following key, value pairs: 'ques': tensor of ints, representing the index of words in the vocab 'ans': tensor of int, representing the index of word answer 'img': tensor representing the image Get Images for the dataset: ! wget http://datasets.d2.mpi-inf.mpg.de/mateusz14visual-turing/nyu_depth_images.tar Get Train question & ans: ! wget https://raw.githubusercontent.com/jayantk/lsp/master/data/daquar/reduced/qa.37.raw.train.txt DAQAR dataset: https://github.com/jayantk/lsp/tree/master/data/daquar """ class VQADataset(Dataset): def __init__(self, ques_file, image_dir, tokenizer, max_len=30): super(Dataset, self).__init__() self.ques_file = ques_file self.img_dir = image_dir self.tokenizer = tokenizer self.max_sentence_len = max_len self.data = [] self.load_data() def load_data(self): with open(self.ques_file, 'r') as f: data = f.readlines() for index, line in tqdm(enumerate(data[::2]), desc='Iterating over questions'): img = line.replace('?', '').strip(' ').split()[-1] + '.png' ques = [x for x in self.tokenizer.encode(line)] ques = [torch.tensor(min(x, vocab_size-1)) for x in ques] ans = self.tokenizer.convert_tokens_to_ids([data[2*index+1].strip()]) ans = [torch.tensor(min(vocab_size-1, ans[0]))] dct = { 'ques': ques, 'ques_str': line, 'ans_str': data[2*index+1], 'ans': ans, 'img_file_name': img } if len(dct['ans']) == 1: self.data.append(dct) def __len__(self): return len(self.data) #// 10 def __getitem__(self, idx): dct = self.data[idx] # Crop to given size, as input to vgg is fixed. img = Image.open(self.img_dir + dct['img_file_name']).crop((0, 0, 448, 448)) # Normalize image pixels img = np.array(img, dtype=np.uint8) / 255 # (H, W, C) -> (C, H, W) img = np.moveaxis(img, -1, 0) dct['img'] = torch.from_numpy(img) return dct def pad_collate(batch): """Padds the sentences to given length ensuring all sentences are of same length. Args: batch (Dict): Dictionary containing the data. See load_data method from VQADataset class Returns: batch (dict): Pads the sentences and returns the dict """ ques = [torch.tensor(x['ques']) for x in batch] ques = pad_sequence(ques, batch_first=True) for idx, x in enumerate(ques): batch[idx]['ques'] = x return batch if __name__ == '__main__': dl = DataLoader(VQADataset(ques_file='/content/qa.37.raw.train.txt', image_dir='/content/nyu_depth_images/', tokenizer=tokenizer), batch_size=2, collate_fn=pad_collate)
<reponame>gdnwxf/netty_stu package org.xtwy.thriftrpc; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TSimpleServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.core.Ordered; import com.hzins.thrift.demo.HelloWorldService; import com.hzins.thrift.demo.HelloWorldService.Processor; public class TThreadThriftServer { public static void startServer(int port) throws Exception{ TProcessor processor = new Processor<HelloWorldService.Iface>(new HelloServiceImpl()); TServerSocket transport = new TServerSocket(port); TThreadPoolServer.Args args = new TThreadPoolServer.Args(transport); args.processor(processor); args.protocolFactory(new TBinaryProtocol.Factory()); TServer server = new TThreadPoolServer(args); server.serve(); } public static void main(String[] args) throws Exception { startServer(8080); } }
<reponame>ecmwf/ecflow #ifndef USER_HPP_ #define USER_HPP_ /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // Name : // Author : Avi // Revision : $Revision: #5 $ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 #include <string> namespace ecf { class User { public: enum Action { FOB, FAIL, ADOPT, REMOVE, BLOCK, KILL }; static bool valid_user_action( const std::string& ); static Action user_action( const std::string& ); static std::string to_string(Action); // return login name: will throw if there are any errors static std::string login_name(); private: User(const User&) = delete; const User& operator=(const User&) = delete; User() = delete; }; } #endif
#!/usr/bin/env bash # Base16 Edge Light - Gnome Terminal color scheme install script # cjayross (https://github.com/cjayross) [[ -z "$PROFILE_NAME" ]] && PROFILE_NAME="Base 16 Edge Light" [[ -z "$PROFILE_SLUG" ]] && PROFILE_SLUG="base-16-edge-light" [[ -z "$DCONF" ]] && DCONF=dconf [[ -z "$UUIDGEN" ]] && UUIDGEN=uuidgen dset() { local key="$1"; shift local val="$1"; shift if [[ "$type" == "string" ]]; then val="'$val'" fi "$DCONF" write "$PROFILE_KEY/$key" "$val" } # Because dconf still doesn't have "append" dlist_append() { local key="$1"; shift local val="$1"; shift local entries="$( { "$DCONF" read "$key" | tr -d '[]' | tr , "\n" | fgrep -v "$val" echo "'$val'" } | head -c-1 | tr "\n" , )" "$DCONF" write "$key" "[$entries]" } # Newest versions of gnome-terminal use dconf if which "$DCONF" > /dev/null 2>&1; then # Check that uuidgen is available type $UUIDGEN >/dev/null 2>&1 || { echo >&2 "Requires uuidgen but it's not installed. Aborting!"; exit 1; } [[ -z "$BASE_KEY_NEW" ]] && BASE_KEY_NEW=/org/gnome/terminal/legacy/profiles: if [[ -n "`$DCONF list $BASE_KEY_NEW/`" ]]; then if which "$UUIDGEN" > /dev/null 2>&1; then PROFILE_SLUG=`uuidgen` fi if [[ -n "`$DCONF read $BASE_KEY_NEW/default`" ]]; then DEFAULT_SLUG=`$DCONF read $BASE_KEY_NEW/default | tr -d \'` else DEFAULT_SLUG=`$DCONF list $BASE_KEY_NEW/ | grep '^:' | head -n1 | tr -d :/` fi DEFAULT_KEY="$BASE_KEY_NEW/:$DEFAULT_SLUG" PROFILE_KEY="$BASE_KEY_NEW/:$PROFILE_SLUG" # Copy existing settings from default profile $DCONF dump "$DEFAULT_KEY/" | $DCONF load "$PROFILE_KEY/" # Add new copy to list of profiles dlist_append $BASE_KEY_NEW/list "$PROFILE_SLUG" # Update profile values with theme options dset visible-name "'$PROFILE_NAME'" dset palette "['#fafafa', '#db7070', '#7c9f4b', '#d69822', '#6587bf', '#b870ce', '#509c93', '#5e646f', '#5e646f', '#db7070', '#7c9f4b', '#d69822', '#6587bf', '#b870ce', '#509c93', '#5e646f']" dset background-color "'#fafafa'" dset foreground-color "'#5e646f'" dset bold-color "'#5e646f'" dset bold-color-same-as-fg "true" dset cursor-colors-set "true" dset cursor-background-color "'#5e646f'" dset cursor-foreground-color "'#fafafa'" dset use-theme-colors "false" dset use-theme-background "false" unset PROFILE_NAME unset PROFILE_SLUG unset DCONF unset UUIDGEN exit 0 fi fi # Fallback for Gnome 2 and early Gnome 3 [[ -z "$GCONFTOOL" ]] && GCONFTOOL=gconftool [[ -z "$BASE_KEY" ]] && BASE_KEY=/apps/gnome-terminal/profiles PROFILE_KEY="$BASE_KEY/$PROFILE_SLUG" gset() { local type="$1"; shift local key="$1"; shift local val="$1"; shift "$GCONFTOOL" --set --type "$type" "$PROFILE_KEY/$key" -- "$val" } # Because gconftool doesn't have "append" glist_append() { local type="$1"; shift local key="$1"; shift local val="$1"; shift local entries="$( { "$GCONFTOOL" --get "$key" | tr -d '[]' | tr , "\n" | fgrep -v "$val" echo "$val" } | head -c-1 | tr "\n" , )" "$GCONFTOOL" --set --type list --list-type $type "$key" "[$entries]" } # Append the Base16 profile to the profile list glist_append string /apps/gnome-terminal/global/profile_list "$PROFILE_SLUG" gset string visible_name "$PROFILE_NAME" gset string palette "#fafafa:#db7070:#7c9f4b:#d69822:#6587bf:#b870ce:#509c93:#5e646f:#5e646f:#db7070:#7c9f4b:#d69822:#6587bf:#b870ce:#509c93:#5e646f" gset string palette "['#fafafa', '#db7070', '#7c9f4b', '#d69822', '#6587bf', '#b870ce', '#509c93', '#5e646f', '#5e646f', '#db7070', '#7c9f4b', '#d69822', '#6587bf', '#b870ce', '#509c93', '#5e646f']" gset string background_color "#fafafa" gset string foreground_color "#5e646f" gset string bold_color "#5e646f" gset bool bold_color_same_as_fg "true" gset bool cursor-colors-set "true" gset string cursor-background-color "'#5e646f'" gset string cursor-foreground-color "'#fafafa'" gset bool use_theme_colors "false" gset bool use_theme_background "false" unset PROFILE_NAME unset PROFILE_SLUG unset DCONF unset UUIDGEN
from django import http from functools import wraps def my_decorator(func): '''自定义的装饰器:判断是否登录,如果登录,执行func ,未登录,返回json''' @wraps(func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: # If the user is authenticated, execute the view function return func(request, *args, **kwargs) else: # If the user is not authenticated, return a JSON response with a 400 status code return http.JsonResponse({'code': 400, 'errmsg': '请登录后重试'}) return wrapper
package yimei.jss.algorithm.featureweighted; import java.util.ArrayList; import ec.EvolutionState; import ec.Individual; import ec.gp.GPNode; import ec.util.Checkpoint; import ec.util.Parameter; import ec.util.RandomChoice; import yimei.jss.feature.FeatureIgnorable; import yimei.jss.feature.FeatureUtil; import yimei.jss.feature.ignore.Ignorer; import yimei.jss.gp.GPRuleEvolutionState; import yimei.jss.gp.TerminalsChangable; import yimei.jss.ruleoptimisation.RuleOptimizationProblem; /** * Created by fzhang on 22.5.2019. * 1. set the weights of featurs according to the frequency of features (based on top-k individuals) * 2. replace the bad individuals by generating new individuals with weihhted features */ public class FreBadGPRuleEvolutionState extends GPRuleEvolutionState implements TerminalsChangable, FeatureIgnorable { public static final String P_IGNORER = "ignorer"; public static final String P_PRE_GENERATIONS = "pre-generations"; public static final String P_POP_ADAPT_FRAC_ELITES = "pop-adapt-frac-elites"; public static final String P_POP_ADAPT_FRAC_ADAPTED = "pop-adapt-frac-adapted"; public static final String P_DO_ADAPT = "feature-selection-adapt-population"; /*public static final String P_NUM_TOP_INDS = "num-topinds";*/ private Ignorer ignorer; private int preGenerations; private double fracElites; private double fracAdapted; private boolean doAdapt; /*private int topInds; */ @Override public Ignorer getIgnorer() { return ignorer; } @Override public void setIgnorer(Ignorer ignorer) { this.ignorer = ignorer; } @Override public void setup(EvolutionState state, Parameter base) { super.setup(state, base); ignorer = (Ignorer) (state.parameters.getInstanceForParameter( new Parameter(P_IGNORER), null, Ignorer.class)); //ignorer = yimei.jss.feature.ignore.SimpleIgnorer preGenerations = state.parameters.getIntWithDefault( new Parameter(P_PRE_GENERATIONS), null, -1); //50 fracElites = state.parameters.getDoubleWithDefault( new Parameter(P_POP_ADAPT_FRAC_ELITES), null, 0.0); //0.0 fracAdapted = state.parameters.getDoubleWithDefault( new Parameter(P_POP_ADAPT_FRAC_ADAPTED), null, 1.0); //0.1 doAdapt = state.parameters.getBoolean(new Parameter(P_DO_ADAPT), null, true); /*topInds = state.parameters.getInt(new Parameter(P_NUM_TOP_INDS), null);*/ } private ArrayList<Individual> lastGenEliteIndividual = new ArrayList<>(); @Override public GPNode pickTerminalRandom(int subPopNum) { int index = -1; //random[0].nextInt(terminals[subPopNum].lenth) //1. if no weights is set for features, then we will choose features uniformly. if (weights == null || weights[subPopNum] == null) { //output.warning("weights are null"); index = random[0].nextInt(terminals[subPopNum].length); } else //2. otherwise, choose features based on their weighting power { //System.out.println(subPopNum); index = RandomChoice.pickFromDistribution(weights[subPopNum], random[0].nextDouble()); } //System.out.println("The index of chosen features: " + index); return terminals[subPopNum][index]; } @Override public int evolve() { output.message("Generation " + generation); // EVALUATION statistics.preEvaluationStatistics(this); evaluator.evaluatePopulation(this); //Feature selection, firstly, evaluate population as usual; then clear population //clearing, niching MultiPopCoevolutionaryEvaluator statistics.postEvaluationStatistics(this); // SHOULD WE QUIT? if (evaluator.runComplete(this) && quitOnRunComplete) { output.message("Found Ideal Individual"); return R_SUCCESS; } // SHOULD WE QUIT? if (generation == numGenerations - 1) { generation++; return R_FAILURE; } // PRE-BREEDING EXCHANGING statistics.prePreBreedingExchangeStatistics(this); population = exchanger.preBreedingExchangePopulation(this); statistics.postPreBreedingExchangeStatistics(this); String exchangerWantsToShutdown = exchanger.runComplete(this); if (exchangerWantsToShutdown != null) { output.message(exchangerWantsToShutdown); /* * Don't really know what to return here. The only place I could * find where runComplete ever returns non-null is * IslandExchange. However, that can return non-null whether or * not the ideal individual was found (for example, if there was * a communication error with the server). * * Since the original version of this code didn't care, and the * result was initialized to R_SUCCESS before the while loop, I'm * just going to return R_SUCCESS here. */ return R_SUCCESS; } // BREEDING statistics.preBreedingStatistics(this); population = breeder.breedPopulation(this); //2019.6.1 only applied at interval generation weights = null; // POST-BREEDING EXCHANGING statistics.postBreedingStatistics(this); // POST-BREEDING EXCHANGING statistics.prePostBreedingExchangeStatistics(this); population = exchanger.postBreedingExchangePopulation(this); statistics.postPostBreedingExchangeStatistics(this); // Generate new instances if needed RuleOptimizationProblem problem = (RuleOptimizationProblem) evaluator.p_problem; if (problem.getEvaluationModel().isRotatable()) { problem.rotateEvaluationModel(); } // INCREMENT GENERATION AND CHECKPOINT generation++; if (checkpoint && generation % checkpointModulo == 0) { output.message("Checkpointing"); statistics.preCheckpointStatistics(this); Checkpoint.setCheckpoint(this); statistics.postCheckpointStatistics(this); } return R_NOTDONE; } @Override public void adaptPopulation(int subPopNum) { FeatureUtil.adaptPopulationThreeParts(this, fracElites, fracAdapted, subPopNum); } }
<gh_stars>0 var structarmnn_1_1_space_to_depth_descriptor = [ [ "SpaceToDepthDescriptor", "structarmnn_1_1_space_to_depth_descriptor.xhtml#af295348553622bb3baadff6ea5124414", null ], [ "SpaceToDepthDescriptor", "structarmnn_1_1_space_to_depth_descriptor.xhtml#a700f6dc2a7a912cd37ee7dbfcc9220b9", null ], [ "operator==", "structarmnn_1_1_space_to_depth_descriptor.xhtml#a2b4d1e836dadf7f093ac47a42bb875de", null ], [ "m_BlockSize", "structarmnn_1_1_space_to_depth_descriptor.xhtml#a6c6b8957f1e176867e5fb05b1a1a1486", null ], [ "m_DataLayout", "structarmnn_1_1_space_to_depth_descriptor.xhtml#a6089e1ca91914015777ea780a513131a", null ] ];
package com.yoga.admin.duty.dto; import com.yoga.core.base.BaseDto; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Getter @Setter @NoArgsConstructor public class DutyListDto extends BaseDto { @ApiModelProperty(value = "查询关键字,比如名称") private String filter; }
func fibonacci(_ n: Int) -> Int { guard n > 0 else { return 0 } if n == 1 || n == 2 { return 1 } return fibonacci(n - 1) + fibonacci(n - 2) } for i in 1...10 { print(fibonacci(i)) }
<gh_stars>1-10 require "git/open/version" module Git module Open class CLI def self.execute require "slop" options = Slop.parse do |option| option.on "-h".freeze, "--help".freeze, "Show this help".freeze option.on "-v".freeze, "--version".freeze, "print the version".freeze do puts_and_exit "git-open version #{Git::Open::VERSION}" end end show_help(options) if options[:h] || options[:help] || ARGV.include?("help".freeze) abort("Not a git repo".freeze) if `git rev-parse --is-inside-work-tree`.chomp! != "true".freeze remotes = `git remote`.split("\n".freeze) abort("No remote found".freeze) if remotes.empty? url = if remotes.find { |remote| remote == "origin".freeze } `git config --get remote.origin.url`.chomp! else `git config --get remote.#{remotes.first}.url`.chomp! end require "git/remote/parser"; require "launchy" Launchy.open(open_url = Git::Remote::Parser.new.parse(url).html_url) do |exception| puts "Attempted to open `#{open_url.to_s}' and failed because #{exception}" end end def self.show_help(options) puts_and_exit(options) end def self.puts_and_exit(message) puts(message) exit end end end end
<filename>apps/ospTestSuite/test_light.cpp // Copyright 2020-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #include "test_light.h" #include "ospray_testing.h" namespace OSPRayTestScenes { LightTest::LightTest() { samplesPerPixel = 16; // due to the way c0 in SpotLight is calculated we must rotate around X axis // to get the same result with SciVis and ring light (because its // approximation in SciVis is not rotation invariant) xfm = affine3f::translate(vec3f(1.f, 2.f, 3.f)) * affine3f::rotate(vec3f(1.f, 0.f, 0.f), pi); } void LightTest::SetUp() { Base::SetUp(); // set common renderer parameter if (rendererType == "pathtracer") renderer.setParam("maxPathLength", 1); if (rendererType == "scivis") { renderer.setParam("shadows", true); renderer.setParam("visibleLights", true); } // build cornell box scene auto builder = ospray::testing::newBuilder("cornell_box"); ospray::testing::setParam(builder, "rendererType", rendererType); ospray::testing::commit(builder); auto group = ospray::testing::buildGroup(builder); AddInstance(cpp::Instance(group)); ospray::testing::release(builder); // position camera camera.setParam("position", vec3f(0, 0, -2.4641)); } void LightTest::AddInstancedLightWithMB( cpp::Light light, const affine3f &xfm1, const affine3f &xfm2) { light.commit(); cpp::Group group; group.setParam("light", cpp::CopiedData(light)); group.commit(); cpp::Instance instance(group); const affine3f xfmR = rcp(xfm); if (motionBlur) { std::vector<affine3f> xfms; xfms.push_back(xfmR * xfm1); xfms.push_back(xfmR * xfm2); instance.setParam("motion.transform", cpp::CopiedData(xfms)); camera.setParam("shutter", range1f(0, 1)); } else instance.setParam("transform", xfmR); AddInstance(instance); } AmbientLight::AmbientLight() { rendererType = GetParam(); } void AmbientLight::SetUp() { LightTest::SetUp(); cpp::Light ambient = ospNewLight("ambient"); ambient.setParam("intensity", 0.5f); AddLight(ambient); if (rendererType == "scivis") renderer.setParam("aoSamples", 1); } DistantLight::DistantLight() { auto params = GetParam(); direction = std::get<0>(params); rendererType = std::get<1>(params); motionBlur = std::get<2>(params); } void DistantLight::SetUp() { LightTest::SetUp(); cpp::Light distant("distant"); distant.setParam("direction", xfmVector(xfm, direction)); distant.setParam("color", vec3f(1.0f, 0.75f, 0.25f)); distant.setParam("angularDiameter", 1.0f); AddInstancedLightWithRotateMB(distant); } GeometricLight::GeometricLight() { rendererType = "pathtracer"; auto params = GetParam(); size = std::get<0>(params); useMaterialList = std::get<1>(params); motionBlur = std::get<2>(params); } void GeometricLight::SetUp() { LightTest::SetUp(); const float area = size * size; const float halfSize = 0.5f * size; std::vector<vec3f> lightVertices = {{-halfSize, 0.98f, -halfSize}, {halfSize, 0.98f, -halfSize}, {halfSize, 0.98f, halfSize}, {-halfSize, 0.98f, halfSize}}; std::vector<vec4ui> lightIndices = {{0, 1, 2, 3}}; cpp::Geometry lightMesh("mesh"); lightMesh.setParam("vertex.position", cpp::CopiedData(lightVertices)); lightMesh.setParam("index", cpp::CopiedData(lightIndices)); lightMesh.commit(); cpp::GeometricModel lightModel(lightMesh); cpp::Material lightMaterial(rendererType, "luminous"); lightMaterial.setParam("color", vec3f(0.78f, 0.551f, 0.183f)); lightMaterial.setParam("intensity", 10.f / area); lightMaterial.commit(); if (useMaterialList) { std::vector<cpp::Material> materials{lightMaterial}; renderer.setParam("material", cpp::CopiedData(materials)); uint32_t materialIndex = 0; lightModel.setParam("material", materialIndex); } else { lightModel.setParam("material", lightMaterial); } if (motionBlur) { lightModel.commit(); cpp::Group group; group.setParam("geometry", cpp::CopiedData(lightModel)); group.commit(); cpp::Instance instance(group); std::vector<affine3f> xfms; xfms.push_back(affine3f::translate(vec3f(-0.5, 0, 0))); xfms.push_back(affine3f::translate(vec3f(0.5, 0, 0))); instance.setParam("motion.transform", cpp::CopiedData(xfms)); AddInstance(instance); camera.setParam("shutter", range1f(0, 1)); } else AddModel(lightModel); } PhotometricLight::PhotometricLight() { auto params = GetParam(); radius = std::get<0>(params); rendererType = std::get<1>(params); } void PhotometricLight::SetUp() { LightTest::SetUp(); cpp::Light light1d("spot"); light1d.setParam("intensity", 5.f); light1d.setParam("position", xfmPoint(xfm, vec3f(-0.6f, 0.8f, -0.5f))); light1d.setParam("direction", xfmVector(xfm, vec3f(0.0f, -1.0f, 0.0f))); light1d.setParam("openingAngle", 360.f); light1d.setParam("penumbraAngle", 0.f); light1d.setParam("radius", radius); float lid1d[] = {2.5f, 0.4f, 0.2f, 0.1f, 0.03f, 0.01f, 0.01f}; light1d.setParam("intensityDistribution", cpp::CopiedData(lid1d, 7)); light1d.commit(); cpp::Light light2d("spot"); light2d.setParam("intensity", 1.f); light2d.setParam("position", xfmPoint(xfm, vec3f(0.3f, 0.6f, 0.f))); light2d.setParam("direction", xfmVector(xfm, vec3f(0.0f, -1.0f, 0.0f))); light2d.setParam("openingAngle", 270.f); light2d.setParam("penumbraAngle", 10.f); light2d.setParam("radius", radius); float lid2d[60] = { 1.5f, 5.0f, 6.0f, 0.3f, 0.01f, 0.15f, 0.5f, 1.6f, 0.1f, 0.01f}; light2d.setParam( "intensityDistribution", cpp::CopiedData(lid2d, vec2ul(5, 12))); light2d.setParam("c0", xfmVector(xfm, vec3f(1.0f, 0.0f, 0.0f))); light2d.commit(); cpp::Group group; std::vector<cpp::Light> lights{light1d, light2d}; group.setParam("light", cpp::CopiedData(lights)); group.commit(); cpp::Instance instance(group); instance.setParam("transform", rcp(xfm)); AddInstance(instance); } QuadLight::QuadLight() { auto params = GetParam(); size = std::get<0>(params); rendererType = std::get<1>(params); intensityQuantity = std::get<2>(params); motionBlur = std::get<3>(params); } void QuadLight::SetUp() { LightTest::SetUp(); cpp::Light light("quad"); light.setParam("color", vec3f(0.78f, 0.551f, 0.183f)); light.setParam("intensity", 10.f); light.setParam("intensityQuantity", intensityQuantity); light.setParam( "position", xfmPoint(xfm, vec3f(size / -2.0f, 0.98f, size / -2.0f))); light.setParam("edge1", xfmVector(xfm, vec3f(size, 0.0f, 0.0f))); light.setParam("edge2", xfmVector(xfm, vec3f(0.0f, 0.0f, size))); AddInstancedLightWithTranslateMB(light); } CylinderLight::CylinderLight() { auto params = GetParam(); size = std::get<0>(params); rendererType = std::get<1>(params); intensityQuantity = std::get<2>(params); motionBlur = std::get<3>(params); } void CylinderLight::SetUp() { LightTest::SetUp(); cpp::Light light("cylinder"); light.setParam("color", vec3f(0.78f, 0.551f, 0.183f)); light.setParam("intensity", 5.0f); light.setParam("intensityQuantity", intensityQuantity); light.setParam( "position0", xfmPoint(xfm, vec3f(-0.2f - 2.0 * size, 0.65f, 0.0f))); light.setParam( "position1", xfmPoint(xfm, vec3f(0.2f + 2.0 * size, 0.65f, 0.0f))); light.setParam("radius", size); AddInstancedLightWithTranslateMB(light); } SphereLight::SphereLight() { auto params = GetParam(); radius = std::get<0>(params); rendererType = std::get<1>(params); intensityQuantity = std::get<2>(params); motionBlur = std::get<3>(params); } void SphereLight::SetUp() { LightTest::SetUp(); cpp::Light light("sphere"); light.setParam("color", vec3f(0.78f, 0.551f, 0.183f)); light.setParam("intensity", 2.5f); light.setParam("intensityQuantity", intensityQuantity); light.setParam("position", xfmPoint(xfm, vec3f(0.0f, 0.48f, 0.0f))); light.setParam("radius", radius); AddInstancedLightWithTranslateMB(light); } SpotLight::SpotLight() { auto params = GetParam(); innerOuterRadius = std::get<0>(params); rendererType = std::get<1>(params); intensityQuantity = std::get<2>(params); motionBlur = std::get<3>(params); } void SpotLight::SetUp() { LightTest::SetUp(); cpp::Light light("spot"); light.setParam("color", vec3f(0.78f, 0.551f, 0.183f)); light.setParam("intensity", 10.f); light.setParam("intensityQuantity", intensityQuantity); light.setParam("position", xfmPoint(xfm, vec3f(0.0f, 0.98f, 0.0f))); light.setParam("direction", xfmVector(xfm, vec3f(0.0f, -1.0f, 0.0f))); light.setParam("radius", innerOuterRadius[1]); light.setParam("innerRadius", innerOuterRadius[0]); AddInstancedLightWithTranslateMB(light); } HDRILight::HDRILight() { auto params = GetParam(); rendererType = std::get<0>(params); motionBlur = std::get<1>(params); } void HDRILight::SetUp() { Base::SetUp(); // set common renderer parameter if (rendererType == "pathtracer") renderer.setParam("maxPathLength", 1); if (rendererType == "scivis") { renderer.setParam("shadows", true); renderer.setParam("visibleLights", true); } // create sphere cpp::Group group; { cpp::Geometry sphere("sphere"); sphere.setParam("sphere.position", cpp::CopiedData(vec3f(0.f))); sphere.setParam("radius", 1.f); sphere.commit(); cpp::GeometricModel model(sphere); cpp::Material material(rendererType, "obj"); material.commit(); model.setParam("material", material); model.commit(); group.setParam("geometry", cpp::CopiedData(model)); group.commit(); } AddInstance(cpp::Instance(group)); // position camera camera.setParam("position", vec3f(0.f, 0.f, -3.f)); // prepare environment texture cpp::Texture envTex("texture2d"); { std::array<vec3f, 8> data = {vec3f(0.f, 1.f, 1.f), vec3f(1.f, 0.f, 1.f), vec3f(1.f, 1.f, 0.f), vec3f(1.f, 1.f, 1.f), vec3f(1.f, 0.f, 0.f), vec3f(0.f, 1.f, 0.f), vec3f(0.f, 0.f, 1.f), vec3f(0.f, 0.f, 0.f)}; cpp::CopiedData texData(data.data(), vec2ul(4, 2)); envTex.setParam("format", OSP_TEXTURE_RGB32F); envTex.setParam("filter", OSP_TEXTURE_FILTER_NEAREST); envTex.setParam("data", texData); envTex.commit(); } // prepare light cpp::Light light("hdri"); light.setParam("color", vec3f(0.78f, 0.551f, 0.183f)); light.setParam("up", xfmVector(xfm, vec3f(0.f, 1.f, 0.f))); light.setParam("direction", xfmVector(xfm, vec3f(0.f, 0.f, 1.f))); light.setParam("map", envTex); AddInstancedLightWithRotateMB(light); renderer.setParam("backgroundColor", vec4f(0.f, 0.f, 0.f, 1.0f)); } SunSky::SunSky() { rendererType = "pathtracer"; samplesPerPixel = 1; auto params = GetParam(); motionBlur = std::get<5>(params); } void SunSky::SetUp() { Base::SetUp(); auto params = GetParam(); cpp::Light light("sunSky"); float turb = std::get<2>(params); light.setParam("up", xfmVector(xfm, std::get<0>(params))); light.setParam("direction", xfmVector(xfm, std::get<1>(params))); light.setParam("turbidity", turb); light.setParam("albedo", std::get<3>(params)); // lower brightness with high turbidity light.setParam("intensityQuantity", OSP_INTENSITY_QUANTITY_SCALE); light.setParam("intensity", 0.025f / turb); light.setParam("horizonExtension", std::get<4>(params)); AddInstancedLightWithRotateMB(light); renderer.setParam("backgroundColor", vec4f(0.f, 0.f, 0.f, 1.0f)); } // Test Instantiations ////////////////////////////////////////////////////// // Ambient Light TEST_P(AmbientLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P( Light, AmbientLight, ::testing::Values("scivis", "pathtracer")); // Distant Light TEST_P(DistantLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, DistantLight, ::testing::Combine( ::testing::Values(vec3f(0.0f, 0.0f, 1.0f), vec3f(-0.5f, 1.0f, 3.0f)), ::testing::Values("scivis", "pathtracer"), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, DistantLight, ::testing::Values( std::make_tuple(vec3f(-0.5f, 1.0f, 3.0f), "pathtracer", true))); // Geometric Light TEST_P(GeometricLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, GeometricLight, ::testing::Combine(::testing::Values(0.2f, 0.4f), ::testing::Bool(), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, GeometricLight, ::testing::Values(std::make_tuple(0.2f, false, true))); // Quad Light TEST_P(QuadLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, QuadLight, ::testing::Combine(::testing::Values(0.2f, 0.4f), ::testing::Values("scivis", "pathtracer"), ::testing::Values(OSP_INTENSITY_QUANTITY_INTENSITY), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightIntensityQuantity, QuadLight, ::testing::Combine(::testing::Values(0.2f, 0.4f), ::testing::Values("pathtracer"), ::testing::Values( OSP_INTENSITY_QUANTITY_RADIANCE, OSP_INTENSITY_QUANTITY_POWER), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, QuadLight, ::testing::Values(std::make_tuple( 0.2f, "pathtracer", OSP_INTENSITY_QUANTITY_INTENSITY, true))); // Cylinder Light TEST_P(CylinderLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, CylinderLight, ::testing::Combine(::testing::Values(0.02f, 0.15f), ::testing::Values("scivis", "pathtracer"), ::testing::Values(OSP_INTENSITY_QUANTITY_INTENSITY), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightIntensityQuantity, CylinderLight, ::testing::Combine(::testing::Values(0.02f, 0.15), ::testing::Values("pathtracer"), ::testing::Values( OSP_INTENSITY_QUANTITY_RADIANCE, OSP_INTENSITY_QUANTITY_POWER), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, CylinderLight, ::testing::Values(std::make_tuple( 0.02f, "pathtracer", OSP_INTENSITY_QUANTITY_INTENSITY, true))); // Sphere Light TEST_P(SphereLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, SphereLight, ::testing::Combine(::testing::Values(0.0f, 0.2f, 0.3f), ::testing::Values("scivis", "pathtracer"), ::testing::Values(OSP_INTENSITY_QUANTITY_INTENSITY), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightIntensityQuantity, SphereLight, ::testing::Combine(::testing::Values(0.0f, 0.2f, 0.3f), ::testing::Values("pathtracer"), ::testing::Values( OSP_INTENSITY_QUANTITY_RADIANCE, OSP_INTENSITY_QUANTITY_POWER), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, SphereLight, ::testing::Values(std::make_tuple( 0.3f, "pathtracer", OSP_INTENSITY_QUANTITY_RADIANCE, true))); // Spot Light TEST_P(SpotLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, SpotLight, ::testing::Combine(::testing::Values(vec2f(0.0f, 0.0f), vec2f(0.0f, 0.2f), vec2f(0.0f, 0.4f), vec2f(0.2f, 0.4f), vec2f(0.7f, 0.8f)), ::testing::Values("scivis", "pathtracer"), ::testing::Values(OSP_INTENSITY_QUANTITY_INTENSITY), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightIntensityQuantity, SpotLight, ::testing::Combine( ::testing::Values( vec2f(0.0f, 0.0f), vec2f(0.0f, 0.2f), vec2f(0.0f, 0.4f)), ::testing::Values("pathtracer"), ::testing::Values( OSP_INTENSITY_QUANTITY_RADIANCE, OSP_INTENSITY_QUANTITY_POWER), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, SpotLight, ::testing::Values(std::make_tuple(vec2f(0.0f, 0.4f), "pathtracer", OSP_INTENSITY_QUANTITY_RADIANCE, true))); // Photometric (Spot) Light TEST_P(PhotometricLight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, PhotometricLight, ::testing::Combine(::testing::Values(0.0f, 0.1f), ::testing::Values("scivis", "pathtracer"))); // HDRI Light TEST_P(HDRILight, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, HDRILight, ::testing::Combine( ::testing::Values("scivis", "pathtracer"), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, HDRILight, ::testing::Values(std::make_tuple("pathtracer", true))); // SunSky Light TEST_P(SunSky, parameter) { PerformRenderTest(); } INSTANTIATE_TEST_SUITE_P(Light, SunSky, ::testing::Combine(::testing::Values(vec3f(0.f, 0.8f, 0.4f)), ::testing::Values(vec3f(0.f, 0.7f, -1.f), vec3f(0.f, 0.4f, -1.f), vec3f(0.f, 0.1f, -1.f), vec3f(0.f, -0.3f, -1.f), vec3f(0.f, -0.8f, 0.4f)), ::testing::Values(1.0f, 3.0f, 10.0f), ::testing::Values(0.0f), ::testing::Values(0.01f), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(Light2, SunSky, ::testing::Combine(::testing::Values(vec3f(0.2f, -0.5f, 0.f)), ::testing::Values(vec3f(0.2f, 0.4f, -1.f), vec3f(0.f, 0.f, -1.f)), ::testing::Values(2.0f), ::testing::Values(0.0f, 1.0f), ::testing::Values(0.1f), ::testing::Values(false))); INSTANTIATE_TEST_SUITE_P(LightMotionBlur, SunSky, ::testing::Values(std::make_tuple(vec3f(0.2f, -0.5f, 0.f), vec3f(0.2f, 0.4f, -1.f), 2.0f, 0.0f, 0.1f, true))); } // namespace OSPRayTestScenes
public class Tree { Node root; // Recursive Function to calculate the number of nodes public int numberOfNodes(Node node) { if (node == null) return 0; else { int count = 1; count += numberOfNodes(node.left); count += numberOfNodes(node.right); return count; } } // Create a Binary Tree public Tree createTree() { Tree tree = new Tree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); return tree; } public static void main(String[] args) { Tree tree = new Tree(); tree = tree.createTree(); // Calculate number of nodes int numberOfNodes = tree.numberOfNodes(tree.root); System.out.println("Number of Nodes: " + numberOfNodes); } }
import Vue from 'vue' import moxios from 'moxios' import * as sinon from 'sinon' import ProteinView from '@/components/App/Protein/registration_system_ext/View' import VueRouter from 'vue-router' import { HTTP } from '@/utils/http-common' const sandbox = sinon.sandbox.create() const router = new VueRouter() describe('Protein/registration_system_ext/View.vue', () => { let vm = null const DATA = { projectSlugOrId: 'project-1', protein: { id: 1, slug: 'protein-label', label: 'Protein label', purificationId: '333', tubeLabel: 'T333', concentration: { isDilutedOrConcentrated: false, concentrationType: 'Concentration', dilutionFactor: null, concentrationFactor: null } } } const PROJECTS = [ {id: 1, label: 'Project 1', proteins: [DATA.protein]}, {id: 2, label: 'Project 2'}, {id: 3, label: 'Project 3'} ] beforeEach(() => { sandbox.stub(router, 'push') const Constructor = Vue.extend(ProteinView) vm = new Constructor({router}) moxios.install(HTTP) moxios.stubRequest(process.env.API_URL + 'protein/' + DATA.protein.slug, { status: 200, response: DATA.protein }) moxios.stubRequest(process.env.API_URL + 'protein/' + DATA.protein.slug + '/projects', { status: 200, response: PROJECTS }) moxios.stubRequest(process.env.API_URL + 'project/', { status: 200, response: PROJECTS }) moxios.stubRequest(process.env.API_URL + 'protein/', { status: 200, response: DATA.protein }) vm.id = DATA.protein.slug vm.projectId = DATA.projectSlugOrId vm = vm.$mount() }) afterEach(() => { moxios.uninstall() sandbox.restore() vm.$destroy() vm = null }) it('should download and show protein aliquot', done => { new Promise((resolve, reject) => moxios.wait(resolve)).then(() => { expect(vm.protein).to.be.eql(DATA.protein) expect(vm.$el.querySelector('.view-header__content__title').innerHTML).to.be.eql(DATA.protein.label) expect(vm.$el.querySelector('a#purificationId').textContent).to.be.eql(DATA.protein.purificationId) expect(vm.$el.querySelector('#protein-tube-labeling').innerHTML.trim().split(' ')[0]).to.be.eql(DATA.protein.tubeLabel) expect(vm.$el.querySelector('#concentration-factor-fallback').innerHTML.trim().split(' ')[0]).to.be.eql('1') }).then(done, done) }) it('should display the edit button', () => { expect(vm.$el.querySelector('#action-buttons__edit').title).to.be.eql('Edit') }) it('should edit button switch to edit form', done => { Vue.nextTick().then(() => { vm.$el.querySelector('#action-buttons__edit').click() const expectedPush = { name: 'protein-edit', params: { id: DATA.protein.slug, projectId: DATA.projectSlugOrId } } expect(router.push).to.have.been.calledOnce expect(router.push).to.have.been.calledWith(expectedPush) }).then(done, done) }) })
import { Puzzle202011, parseInput } from './11'; let day: Puzzle202011; describe('202011', () => { beforeEach(() => { day = new Puzzle202011('202011'); }); test('parseInput', () => { const input = `L.LL. LLLLL`; const result = parseInput(input); expect(result).toEqual([ [ { occupied: false, seat: true }, { occupied: false, seat: false }, { occupied: false, seat: true }, { occupied: false, seat: true }, { occupied: false, seat: false }, ], [ { occupied: false, seat: true }, { occupied: false, seat: true }, { occupied: false, seat: true }, { occupied: false, seat: true }, { occupied: false, seat: true }, ], ]); }); test('Part 1 example 1', () => { day.loadData(`L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL`); const result = day.part1(); expect(result).toBe('37'); }); test('Part 2 example 1', () => { day.loadData(`L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL`); const result = day.part2(); expect(result).toBe('26'); }); });
def replace_greater_than_n(arr, n): new_arr = [] for row in arr: new_row = [] for item in row: if item > n: new_row.append(n) else: new_row.append(item) new_arr.append(new_row) return new_arr print(replace_greater_than_n(arr, n))
#!/usr/bin/env bash NEW_RELIC_LICENSE_KEY=$1 SERVICE_BUS=$2 echo "NEW_RELIC_LICENSE_KEY=$NEW_RELIC_LICENSE_KEY" echo "SERVICE_BUS=$SERVICE_BUS" dotnet publish docker build -t dotnet-backend:latest . docker run -e NEW_RELIC_LICENSE_KEY="$NEW_RELIC_LICENSE_KEY" -e SERVICE_BUS="$SERVICE_BUS" -p 5000:80 dotnet-backend:latest
/* * Copyright 2018 Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * <NAME>, <EMAIL> */ #include <new> #include <stdio.h> #include <string.h> #include <bus/PCI.h> #include <PCI_x86.h> #include <KernelExport.h> #include "sdhci_pci.h" #define TRACE_SDHCI #ifdef TRACE_SDHCI # define TRACE(x...) dprintf("\33[33msdhci_pci:\33[0m " x) #else # define TRACE(x...) ; #endif #define TRACE_ALWAYS(x...) dprintf("\33[33msdhci_pci:\33[0m " x) #define ERROR(x...) dprintf("\33[33msdhci_pci:\33[0m " x) #define CALLED(x...) TRACE("CALLED %s\n", __PRETTY_FUNCTION__) #define SDHCI_PCI_DEVICE_MODULE_NAME "busses/mmc/sdhci_pci/driver_v1" #define SDHCI_PCI_MMC_BUS_MODULE_NAME "busses/mmc/sdhci_pci/device/v1" #define SDHCI_PCI_CONTROLLER_TYPE_NAME "sdhci pci controller" #define SLOTS_COUNT "device/slots_count" #define SLOT_NUMBER "device/slot" #define BAR_INDEX "device/bar" typedef struct { pci_device_module_info* pci; pci_device* device; addr_t base_addr; uint8 irq; sdhci_mmc_bus mmc_bus; area_id regs_area; device_node* node; pci_info info; struct registers* _regs; } sdhci_pci_mmc_bus_info; device_manager_info* gDeviceManager; device_module_info* gSDHCIDeviceController; static pci_x86_module_info* sPCIx86Module; static void sdhci_register_dump(uint8_t slot, struct registers* regs) { TRACE("Register values for slot: %d\n", slot); TRACE("system_address: %d\n", regs->system_address); TRACE("block_size: %d\n", regs->block_size); TRACE("block_count: %d\n", regs->block_count); TRACE("argument: %d\n", regs->argument); TRACE("transfer_mode: %d\n", regs->transfer_mode); TRACE("command: %d\n", regs->command); TRACE("response0: %d\n", regs->response0); TRACE("response2: %d\n", regs->response2); TRACE("response4: %d\n", regs->response4); TRACE("response6: %d\n", regs->response6); TRACE("buffer_data_port: %d\n", regs->buffer_data_port); TRACE("present_state: %d\n", regs->present_state); TRACE("power_control: %d\n", regs->power_control); TRACE("host_control: %d\n", regs->host_control); TRACE("wakeup_control: %d\n", regs->wakeup_control); TRACE("block_gap_control: %d\n", regs->block_gap_control); TRACE("clock_control: %d\n", regs->clock_control); TRACE("software_reset: %d\n", regs->software_reset); TRACE("timeout_control: %d\n", regs->timeout_control); TRACE("interrupt_status: %d\n", regs->interrupt_status); TRACE("interrupt_status_enable: %d\n", regs->interrupt_status_enable); TRACE("interrupt_signal_enable: %d\n", regs->interrupt_signal_enable); TRACE("auto_cmd12_error_status: %d\n", regs->auto_cmd12_error_status); TRACE("capabilities: %d\n", regs->capabilities); TRACE("capabilities_rsvd: %d\n", regs->capabilities_rsvd); TRACE("max_current_capabilities: %d\n", regs->max_current_capabilities); TRACE("max_current_capabilities_rsvd: %d\n", regs->max_current_capabilities_rsvd); TRACE("slot_interrupt_status: %d\n", regs->slot_interrupt_status); TRACE("host_control_version %d\n", regs->host_control_version); } static void sdhci_reset(struct registers* regs) { // if card is not present then no point of reseting the registers if (!(regs->present_state & SDHCI_CARD_DETECT)) return; // enabling software reset all regs->software_reset |= SDHCI_SOFTWARE_RESET_ALL; // waiting for clock and power to get off while (regs->clock_control != 0 && regs->power_control != 0); } static void sdhci_set_clock(struct registers* regs, uint16_t base_clock_div) { uint32_t clock_control = regs->clock_control; int base_clock = SDHCI_BASE_CLOCK_FREQ(regs->capabilities); TRACE("SDCLK frequency: %dMHz\n", base_clock); // clearing previous frequency clock_control &= SDHCI_CLR_FREQ_SEL; clock_control |= base_clock_div; // enabling internal clock clock_control |= SDHCI_INTERNAL_CLOCK_ENABLE; regs->clock_control = clock_control; // waiting till internal clock gets stable while (!(regs->clock_control & SDHCI_INTERNAL_CLOCK_STABLE)); regs->clock_control |= SDHCI_SD_CLOCK_ENABLE; // enabling the SD clock } static void sdhci_stop_clock(struct registers* regs) { regs->clock_control &= SDHCI_SD_CLOCK_DISABLE; } static void sdhci_set_power(struct registers* _regs) { uint16_t command = _regs->command; if (SDHCI_VOLTAGE_SUPPORTED(_regs->capabilities)) if (SDHCI_VOLTAGE_SUPPORTED_33(_regs->capabilities)) _regs->power_control |= SDHCI_VOLTAGE_SUPPORT_33; else if (SDHCI_VOLTAGE_SUPPORTED_30(_regs->capabilities)) _regs->power_control |= SDHCI_VOLTAGE_SUPPORT_30; else _regs->power_control |= SDHCI_VOLTAGE_SUPPORT_18; else TRACE("No voltage is supported\n"); if (SDHCI_CARD_INSERTED(_regs->present_state) == 0) { TRACE("Card not inserted\n"); return; } _regs->power_control |= SDHCI_BUS_POWER_ON; TRACE("Executed CMD0\n"); command = SDHCI_RESPONSE_R1 | SDHCI_CMD_CRC_EN | SDHCI_CMD_INDEX_EN | SDHCI_CMD_0; _regs->command |= command; DELAY(1000); } static status_t init_bus(device_node* node, void** bus_cookie) { CALLED(); status_t status = B_OK; area_id regs_area; volatile uint32_t* regs; uint8_t bar, slot; sdhci_pci_mmc_bus_info* bus = new(std::nothrow) sdhci_pci_mmc_bus_info; if (bus == NULL) return B_NO_MEMORY; pci_info* pciInfo = &bus->info; pci_device_module_info* pci; pci_device* device; device_node* parent = gDeviceManager->get_parent_node(node); device_node* pciParent = gDeviceManager->get_parent_node(parent); gDeviceManager->get_driver(pciParent, (driver_module_info**)&pci, (void**)&device); gDeviceManager->put_node(pciParent); gDeviceManager->put_node(parent); if (get_module(B_PCI_X86_MODULE_NAME, (module_info**)&sPCIx86Module) != B_OK) { sPCIx86Module = NULL; TRACE("PCIx86Module not loaded\n"); } int msiCount = sPCIx86Module->get_msi_count(pciInfo->bus, pciInfo->device, pciInfo->function); TRACE("interrupts count: %d\n",msiCount); if (gDeviceManager->get_attr_uint8(node, SLOT_NUMBER, &slot, false) < B_OK || gDeviceManager->get_attr_uint8(node, BAR_INDEX, &bar, false) < B_OK) return -1; bus->node = node; bus->pci = pci; bus->device = device; pci->get_pci_info(device, pciInfo); // legacy interrupt bus->base_addr = pciInfo->u.h0.base_registers[bar]; // enable bus master and io uint16 pcicmd = pci->read_pci_config(device, PCI_command, 2); pcicmd &= ~(PCI_command_int_disable | PCI_command_io); pcicmd |= PCI_command_master | PCI_command_memory; pci->write_pci_config(device, PCI_command, 2, pcicmd); TRACE("init_bus() %p node %p pci %p device %p\n", bus, node, bus->pci, bus->device); // mapping the registers by MMUIO method int bar_size = pciInfo->u.h0.base_register_sizes[bar]; regs_area = map_physical_memory("sdhc_regs_map", pciInfo->u.h0.base_registers[bar], pciInfo->u.h0.base_register_sizes[bar], B_ANY_KERNEL_BLOCK_ADDRESS, B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, (void**)&regs); if (regs_area < B_OK) { TRACE("mapping failed"); return B_BAD_VALUE; } bus->regs_area = regs_area; struct registers* _regs = (struct registers*)regs; bus->_regs = _regs; sdhci_reset(_regs); bus->irq = pciInfo->u.h0.interrupt_line; TRACE("irq interrupt line: %d\n",bus->irq); if (bus->irq == 0 || bus->irq == 0xff) { TRACE("PCI IRQ not assigned\n"); if (sPCIx86Module != NULL) { put_module(B_PCI_X86_MODULE_NAME); sPCIx86Module = NULL; } delete bus; return B_ERROR; } status = install_io_interrupt_handler(bus->irq, sdhci_generic_interrupt, bus, 0); if (status != B_OK) { TRACE("can't install interrupt handler\n"); return status; } TRACE("interrupt handler installed\n"); _regs->interrupt_status_enable = SDHCI_INT_CMD_CMP | SDHCI_INT_TRANS_CMP | SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM | SDHCI_INT_TIMEOUT | SDHCI_INT_CRC | SDHCI_INT_INDEX | SDHCI_INT_BUS_POWER | SDHCI_INT_END_BIT; _regs->interrupt_signal_enable = SDHCI_INT_CMD_CMP | SDHCI_INT_TRANS_CMP | SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM | SDHCI_INT_TIMEOUT | SDHCI_INT_CRC | SDHCI_INT_INDEX | SDHCI_INT_BUS_POWER | SDHCI_INT_END_BIT; sdhci_register_dump(slot, _regs); sdhci_set_clock(_regs, SDHCI_BASE_CLOCK_DIV_128); sdhci_set_power(_regs); sdhci_register_dump(slot, _regs); *bus_cookie = bus; return status; } void sdhci_error_interrupt_recovery(struct registers* _regs) { _regs->interrupt_signal_enable &= ~(SDHCI_INT_CMD_CMP | SDHCI_INT_TRANS_CMP | SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM); if (_regs->interrupt_status & 7) { _regs->software_reset |= 1 << 1; while (_regs->command); } int16_t erorr_status = _regs->interrupt_status; _regs->interrupt_status &= ~(erorr_status); } int32 sdhci_generic_interrupt(void* data) { TRACE("interrupt function called\n"); sdhci_pci_mmc_bus_info* bus = (sdhci_pci_mmc_bus_info*)data; uint16_t intmask, card_present; intmask = bus->_regs->slot_interrupt_status; if (intmask == 0 || intmask == 0xffffffff) { TRACE("invalid command interrupt\n"); return B_UNHANDLED_INTERRUPT; } // handling card presence interrupt if (intmask & (SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM)) { card_present = ((intmask & SDHCI_INT_CARD_INS) != 0); bus->_regs->interrupt_status_enable &= ~(SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM); bus->_regs->interrupt_signal_enable &= ~(SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM); bus->_regs->interrupt_status_enable |= card_present ? SDHCI_INT_CARD_REM : SDHCI_INT_CARD_INS; bus->_regs->interrupt_signal_enable |= card_present ? SDHCI_INT_CARD_REM : SDHCI_INT_CARD_INS; bus->_regs->interrupt_status |= (intmask & (SDHCI_INT_CARD_INS | SDHCI_INT_CARD_REM)); TRACE("Card presence interrupt handled\n"); return B_HANDLED_INTERRUPT; } // handling command interrupt if (intmask & SDHCI_INT_CMD_MASK) { TRACE("interrupt status error: %d\n", bus->_regs->interrupt_status); bus->_regs->interrupt_status |= (intmask & SDHCI_INT_CMD_MASK); TRACE("Command interrupt handled\n"); return B_HANDLED_INTERRUPT; } // handling bus power interrupt if (intmask & SDHCI_INT_BUS_POWER) { bus->_regs->interrupt_status |= SDHCI_INT_BUS_POWER; TRACE("card is consuming too much power\n"); return B_HANDLED_INTERRUPT; } intmask &= ~(SDHCI_INT_BUS_POWER | SDHCI_INT_CARD_INS |SDHCI_INT_CARD_REM | SDHCI_INT_CMD_MASK); } static void uninit_bus(void* bus_cookie) { sdhci_pci_mmc_bus_info* bus = (sdhci_pci_mmc_bus_info*)bus_cookie; delete bus; } static void bus_removed(void* bus_cookie) { return; } static status_t register_child_devices(void* cookie) { CALLED(); device_node* node = (device_node*)cookie; device_node* parent = gDeviceManager->get_parent_node(node); pci_device_module_info* pci; pci_device* device; uint8 slots_count, bar, slotsInfo; gDeviceManager->get_driver(parent, (driver_module_info**)&pci, (void**)&device); uint16 pciSubDeviceId = pci->read_pci_config(device, PCI_subsystem_id, 2); slotsInfo = pci->read_pci_config(device, SDHCI_PCI_SLOT_INFO, 1); bar = SDHCI_PCI_SLOT_INFO_FIRST_BASE_INDEX(slotsInfo); slots_count = SDHCI_PCI_SLOTS(slotsInfo); char prettyName[25]; if (slots_count > 6 || bar > 5) { TRACE("Invalid slots count: %d or BAR count: %d \n", slots_count, bar); return B_BAD_VALUE; } for (uint8_t slot = 0; slot <= slots_count; slot++) { bar = bar + slot; sprintf(prettyName, "SDHC bus %" B_PRIu16 " slot %" B_PRIu8, pciSubDeviceId, slot); device_attr attrs[] = { // properties of this controller for SDHCI bus manager { B_DEVICE_PRETTY_NAME, B_STRING_TYPE, { string: prettyName }}, { B_DEVICE_FIXED_CHILD, B_STRING_TYPE, {string: SDHCI_BUS_CONTROLLER_MODULE_NAME}}, {SDHCI_DEVICE_TYPE_ITEM, B_UINT16_TYPE, { ui16: pciSubDeviceId}}, {B_DEVICE_BUS, B_STRING_TYPE,{string: "mmc"}}, {SLOT_NUMBER, B_UINT8_TYPE, { ui8: slot}}, {BAR_INDEX, B_UINT8_TYPE, { ui8: bar}}, { NULL } }; if (gDeviceManager->register_node(node, SDHCI_PCI_MMC_BUS_MODULE_NAME, attrs, NULL, &node) != B_OK) return B_BAD_VALUE; } return B_OK; } static status_t init_device(device_node* node, void** device_cookie) { CALLED(); *device_cookie = node; return B_OK; } static status_t register_device(device_node* parent) { device_attr attrs[] = { {B_DEVICE_PRETTY_NAME, B_STRING_TYPE, {string: "SDHC PCI controller"}}, {} }; return gDeviceManager->register_node(parent, SDHCI_PCI_DEVICE_MODULE_NAME, attrs, NULL, NULL); } static float supports_device(device_node* parent) { CALLED(); const char* bus; uint16 type, subType; uint8 pciSubDeviceId; // make sure parent is a PCI SDHCI device node if (gDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false) != B_OK || gDeviceManager->get_attr_uint16(parent, B_DEVICE_SUB_TYPE, &subType, false) < B_OK || gDeviceManager->get_attr_uint16(parent, B_DEVICE_TYPE, &type, false) < B_OK) return -1; if (strcmp(bus, "pci") != 0) return 0.0f; if (type == PCI_base_peripheral) { if (subType != PCI_sd_host) return 0.0f; pci_device_module_info* pci; pci_device* device; gDeviceManager->get_driver(parent, (driver_module_info**)&pci, (void**)&device); pciSubDeviceId = pci->read_pci_config(device, PCI_revision, 1); TRACE("SDHCI Device found! Subtype: 0x%04x, type: 0x%04x\n", subType, type); return 0.8f; } return 0.0f; } module_dependency module_dependencies[] = { { SDHCI_BUS_CONTROLLER_MODULE_NAME, (module_info**)&gSDHCIDeviceController}, { B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&gDeviceManager }, {} }; static sdhci_mmc_bus_interface gSDHCIPCIDeviceModule = { { { SDHCI_PCI_MMC_BUS_MODULE_NAME, 0, NULL }, NULL, // supports device NULL, // register device init_bus, uninit_bus, NULL, // register child devices NULL, // rescan bus_removed, } }; static driver_module_info sSDHCIDevice = { { SDHCI_PCI_DEVICE_MODULE_NAME, 0, NULL }, supports_device, register_device, init_device, NULL, // uninit register_child_devices, NULL, // rescan NULL, // device removed }; module_info* modules[] = { (module_info* )&sSDHCIDevice, (module_info* )&gSDHCIPCIDeviceModule, NULL };
#!/bin/bash -e if [[ -e ./src/lab2_fb ]] ; then binStr="./src/lab2_fb" else echo "Couldn't find program to execute." exit 1 fi $binStr --audio_file p018k7.1.dat --graph_file p018k7.1.fsm --iters 1 \ --in_gmm p018k7.22.2.gmm --out_gmm /dev/null --chart_file p3a_chart.dat
import random def generate_list(): list = [] for i in range(10): list.append(random.randint(0, 10)) return list
#!/bin/bash -e OPTION="$1" shift # Check if an option is specified. if [[ -z $OPTION ]]; then echo "Usage: $0 <init|backend|frontend>" exit 0 fi # This script must be run in the project root folder. if [ ! -d "photod-backend" ]; then echo "The source directory is not mounted." exit 1 fi # Parse option and execute action. case $OPTION in init) (cd photod-backend && python3 -m venv env && source env/bin/activate && pip install -r requirements.txt) (cd photod-frontend && yarn) ;; backend) (cd photod-backend && source env/bin/activate && ./manage.py $@) ;; frontend) (cd photod-frontend && yarn $@) ;; *) echo "Unknown option: $OPTION" exit 1 ;; esac
/** * */ package coca.api.co; import coca.api.CocaConst; import coca.co.ins.CoIns; import coca.co.ins.CoIns.Ins; import coca.co.ins.CoInsFactory; /** * * @author dzh * @date Oct 13, 2017 11:12:56 AM * @since 0.0.1 */ public class CocaInsFactory extends CoInsFactory { protected CoIns<?> customIns(Ins ins) { if (CocaConst.EVICT.equals(ins)) { return new StackCoIns(ins); } return null; } }
#!/bin/bash quick=false while getopts ":HG:M:D:R:F:S:Q" opt; do case $opt in H) echo "Bash script to evaluate released models on tempoTL:" echo "" echo " Flag 'R' (required): path with RGB model " echo "" echo " Flag 'F' (required): path with flow model " echo "" echo " Flag 'D' (required): indicate dataset tempoTL, tempoHL, or didemo" echo "" echo " Flag 'M' (required): indicate which model to evaluate" echo " Options:" echo " mcn, mcn-tall-loss, tall-noTEF, tall, mllc-global, mllc-ba, mllc-ws, mllc-ws-conTEF, mlls-ss, mllc" echo "" echo " Flag 'S' (optional): indicate which folder models saved to; default 'snapshots'. Released models are in 'released_models'" echo "" echo " Flag 'G' (optional): indicate which GPU to run on" echo "" echo " Flag 'Q' (optional): if you have run evaluation before, intermediate values will be cached. Adding -Q will speed up computation" exit 1 ;; R) rgb="$OPTARG" ;; F) flow="$OPTARG" ;; G) gpu="$OPTARG" ;; M) model="$OPTARG" ;; D) dataset="$OPTARG" ;; S) snapshot_folder="$OPTARG" ;; Q) quick=true ;; \?) echo "Invalid option -$OPTARG" >&2 ;; esac done if [[ -z $gpu ]] ; then echo 'Did not indicate GPU: using default GPU (0)' gpu=0 fi if [[ -z $snapshot_folder ]] ; then echo 'Did not indicate snapshot folder: using default GPU ("snapshots")' snapshot_folder=snapshots fi echo "GPU: " $gpu echo "Evaluating model: " $model echo "Dataset: " $dataset #Parameters shared across all models DROPOUT_VISUAL=0.3 DROPOUT_LANGUAGE=0.3 LANGUAGE_LAYERS=lstm_no_embed FEATURE_PROCESS_LANGUAGE=recurrent_embedding MAX_ITER=45000 SNAPSHOT=45000 STEPSIZE=15000 BASE_LR=0.05 RANDOM_SEED=1701 LW_INTER=0.2 BATCH_SIZE=120 loc_flag=loc test_set='val+test' loss='ranking' if [ "$dataset" == tempoTL ]; then TRAIN_JSON=data/tempoTL+didemo_train.json VAL_JSON=data/tempoTL+didemo_val.json TEST_JSON=data/tempoTL+didemo_test.json elif [ "$dataset" == tempoHL ]; then TRAIN_JSON=data/tempoHL+didemo_train.json VAL_JSON=data/tempoHL+didemo_val.json TEST_JSON=data/tempoHL+didemo_test.json elif [ "$dataset" == didemo ]; then TRAIN_JSON=data/didemo_train.json VAL_JSON=data/didemo_val.json TEST_JSON=data/didemo_test.json test_set='val' else echo "-D (dataset) must be 'tempoTL', 'tempoHL' or 'didemo'" exit 1 fi #Defining parameters for specific models if [ "$model" == mllc ]; then INPUT_VISUAL_DATA="relational" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_norm LOSS_TYPE=triplet DISTANCE_FUNCTION=early_combine_mult LW_INTER=0.2 VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 elif [ "$model" == mllc-ws ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_before_after LOSS_TYPE=triplet DISTANCE_FUNCTION=early_combine_mult LW_INTER=0.2 VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 elif [ "$model" == mllc-ws-conTEF ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_before_after LOSS_TYPE=triplet DISTANCE_FUNCTION=early_combine_mult LW_INTER=0.2 VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 elif [ "$model" == mllc-ss ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_before_after LOSS_TYPE=triplet DISTANCE_FUNCTION=early_combine_mult LW_INTER=0.2 VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 elif [ "$model" == mllc-ba ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_before_after LOSS_TYPE=triplet DISTANCE_FUNCTION=early_combine_mult LW_INTER=0.2 VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 elif [ "$model" == mllc-global ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_context LOSS_TYPE=triplet DISTANCE_FUNCTION=early_combine_mult LW_INTER=0.2 VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 elif [ "$model" == tall ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_before_after LOSS_TYPE=intra DISTANCE_FUNCTION=tall_distance VISUAL_EMBEDDING_DIM_1=100 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=100 loss=tall elif [ "$model" == tall-noTEF ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_before_after LOSS_TYPE=intra DISTANCE_FUNCTION=tall_distance VISUAL_EMBEDDING_DIM_1=100 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=100 MAX_ITER=45000 loc_flag="no-loc" elif [ "$model" == mcn ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=2 FEATURE_PROCESS_VISUAL=feature_process_context DISTANCE_FUNCTION=euclidean_distance LW_INTER=0.2 LOSS_TYPE=triplet VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2=100 LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=100 elif [ "$model" == mcn-tall-loss ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=2 FEATURE_PROCESS_VISUAL=feature_process_context DISTANCE_FUNCTION=euclidean_distance LW_INTER=0.2 LOSS_TYPE=triplet VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2=100 LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=100 loss=tall elif [ "$model" == mcn-tall-sim ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_context DISTANCE_FUNCTION=early_combine_mult_tall LW_INTER=0.2 LOSS_TYPE=triplet VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 elif [ "$model" == mcn-mult-no-norm ]; then INPUT_VISUAL_DATA="clip" VISION_LAYERS=1 FEATURE_PROCESS_VISUAL=feature_process_context DISTANCE_FUNCTION=early_combine_mult_no_norm LW_INTER=0.2 LOSS_TYPE=triplet VISUAL_EMBEDDING_DIM_1=500 VISUAL_EMBEDDING_DIM_2='' LANGUAGE_EMBEDDING_DIM_1=1000 LANGUAGE_EMBEDDING_DIM_2=500 else echo "-M (model) must be 'mcn', 'mcn-tall-loss', 'tall-noTEF', 'tall', 'mllc-global', 'mllc-ba', 'mllc-ws', 'mllc-ws-conTEF', 'mllc-ss', 'mllc'" exit 1 fi if [ $quick == false ] ; then ##rgb rgb_data=data/average_rgb_feats.h5 TRAIN_H5=$rgb_data TEST_H5=$rgb_data #test on val python utils/build_net.py --feature_process_visual $FEATURE_PROCESS_VISUAL \ --$loc_flag \ --vision_layers $VISION_LAYERS \ --dropout_visual $DROPOUT_VISUAL \ --dropout_language $DROPOUT_LANGUAGE \ --language_layers $LANGUAGE_LAYERS \ --feature_process_language $FEATURE_PROCESS_LANGUAGE \ --visual_embedding_dim $VISUAL_EMBEDDING_DIM_1 $VISUAL_EMBEDDING_DIM_2 \ --language_embedding_dim $LANGUAGE_EMBEDDING_DIM_1 $LANGUAGE_EMBEDDING_DIM_2 \ --gpu $gpu \ --max_iter $MAX_ITER \ --snapshot $SNAPSHOT \ --stepsize $MAX_ITER \ --base_lr $BASE_LR \ --train_json $TRAIN_JSON \ --test_json $VAL_JSON \ --train_h5 $TRAIN_H5 \ --test_h5 $TEST_H5 \ --random_seed $RANDOM_SEED \ --loss_type $LOSS_TYPE \ --lw_inter $LW_INTER \ --batch_size $BATCH_SIZE \ --distance_function $DISTANCE_FUNCTION \ --pool_type max \ --strong_supervise \ --input_visual_data $INPUT_VISUAL_DATA \ --snapshot_folder $snapshot_folder \ --tag $rgb #test on test python utils/build_net.py --feature_process_visual $FEATURE_PROCESS_VISUAL \ --$loc_flag \ --vision_layers $VISION_LAYERS \ --dropout_visual $DROPOUT_VISUAL \ --dropout_language $DROPOUT_LANGUAGE \ --language_layers $LANGUAGE_LAYERS \ --feature_process_language $FEATURE_PROCESS_LANGUAGE \ --visual_embedding_dim $VISUAL_EMBEDDING_DIM_1 $VISUAL_EMBEDDING_DIM_2 \ --language_embedding_dim $LANGUAGE_EMBEDDING_DIM_1 $LANGUAGE_EMBEDDING_DIM_2 \ --gpu $gpu \ --max_iter $MAX_ITER \ --snapshot $SNAPSHOT \ --stepsize $MAX_ITER \ --base_lr $BASE_LR \ --train_json $TRAIN_JSON \ --test_json $TEST_JSON \ --train_h5 $TRAIN_H5 \ --test_h5 $TEST_H5 \ --random_seed $RANDOM_SEED \ --loss_type $LOSS_TYPE \ --lw_inter $LW_INTER \ --batch_size $BATCH_SIZE \ --distance_function $DISTANCE_FUNCTION \ --pool_type max \ --strong_supervise \ --snapshot_folder $snapshot_folder \ --input_visual_data $INPUT_VISUAL_DATA \ --tag $rgb #flow on test flow_data=data/average_flow_feats.h5 TRAIN_H5=$flow_data TEST_H5=$flow_data #test on val python utils/build_net.py --feature_process_visual $FEATURE_PROCESS_VISUAL \ --$loc_flag \ --vision_layers $VISION_LAYERS \ --dropout_visual $DROPOUT_VISUAL \ --dropout_language $DROPOUT_LANGUAGE \ --language_layers $LANGUAGE_LAYERS \ --feature_process_language $FEATURE_PROCESS_LANGUAGE \ --visual_embedding_dim $VISUAL_EMBEDDING_DIM_1 $VISUAL_EMBEDDING_DIM_2 \ --language_embedding_dim $LANGUAGE_EMBEDDING_DIM_1 $LANGUAGE_EMBEDDING_DIM_2 \ --gpu $gpu \ --max_iter $MAX_ITER \ --snapshot $SNAPSHOT \ --stepsize $MAX_ITER \ --base_lr $BASE_LR \ --train_json $TRAIN_JSON \ --test_json $VAL_JSON \ --train_h5 $TRAIN_H5 \ --test_h5 $TEST_H5 \ --random_seed $RANDOM_SEED \ --loss_type $LOSS_TYPE \ --lw_inter $LW_INTER \ --batch_size $BATCH_SIZE \ --distance_function $DISTANCE_FUNCTION \ --pool_type max \ --strong_supervise \ --snapshot_folder $snapshot_folder \ --input_visual_data $INPUT_VISUAL_DATA \ --tag $flow #test on test python utils/build_net.py --feature_process_visual $FEATURE_PROCESS_VISUAL \ --$loc_flag \ --vision_layers $VISION_LAYERS \ --dropout_visual $DROPOUT_VISUAL \ --dropout_language $DROPOUT_LANGUAGE \ --language_layers $LANGUAGE_LAYERS \ --feature_process_language $FEATURE_PROCESS_LANGUAGE \ --visual_embedding_dim $VISUAL_EMBEDDING_DIM_1 $VISUAL_EMBEDDING_DIM_2 \ --language_embedding_dim $LANGUAGE_EMBEDDING_DIM_1 $LANGUAGE_EMBEDDING_DIM_2 \ --gpu $gpu \ --max_iter $MAX_ITER \ --snapshot $SNAPSHOT \ --stepsize $MAX_ITER \ --base_lr $BASE_LR \ --train_json $TRAIN_JSON \ --test_json $TEST_JSON \ --train_h5 $TRAIN_H5 \ --test_h5 $TEST_H5 \ --random_seed $RANDOM_SEED \ --loss_type $LOSS_TYPE \ --lw_inter $LW_INTER \ --batch_size $BATCH_SIZE \ --distance_function $DISTANCE_FUNCTION \ --pool_type max \ --snapshot_folder $snapshot_folder \ --strong_supervise \ --input_visual_data $INPUT_VISUAL_DATA \ --snapshot_folder=$snapshot_folder \ --tag $flow fi if [ "$loss" == tall ] ; then python utils/fusion.py --rgb_tag $rgb \ --flow_tag $flow \ --iter $MAX_ITER \ --dataset $dataset \ --set $test_set \ --tall else python utils/fusion.py --rgb_tag $rgb \ --flow_tag $flow \ --iter $MAX_ITER \ --set $test_set \ --dataset $dataset fi echo "Evaluated model: " $model echo "On dataset: " $dataset
<reponame>chino-os/chino-os<filename>src/hal/src/chip/wm/w600/uart.cpp // MIT License // // Copyright (c) 2020 SunnyCase // // 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. #include <chino/chip/wm/w600/uart.h> using namespace chino; using namespace chino::chip; typedef struct { uint32_t uart_line_ctrl; uint32_t auto_flow_ctrl; uint32_t dma_ctrl; uint32_t uart_fifo_ctrl; uint32_t baud_rate_ctrl; uint32_t int_mask; uint32_t int_src; uint32_t fifo_status; uint32_t tx_data; uint32_t reserved0[3]; uint32_t rx_data; } uart_t; static volatile uart_t &uart_r(uintptr_t base) noexcept { return *reinterpret_cast<volatile uart_t *>(base); } void uart::set_baud_rate(uintptr_t base, uint32_t apb_clk, uint32_t baudrate) noexcept { uart_r(base).uart_line_ctrl = 0xC3; uart_r(base).auto_flow_ctrl = 0x14; uart_r(base).dma_ctrl = 0x0; uart_r(base).baud_rate_ctrl = 0x81; //auto ubdiv = apb_clk / (16 * baudrate) - 1; //auto ubdiv_frac = (apb_clk % (baudrate * 16)) / baudrate; //uart_r(base).baud_rate_ctrl = (ubdiv_frac << 16) | ubdiv; } bool uart::is_tx_fifo_full(uintptr_t base) noexcept { return (uart_r(base).fifo_status & 0x3F) == 0x3F; } void uart::write(uintptr_t base, uint8_t data) noexcept { uart_r(base).tx_data = data; }
import numpy as np class Object3D: def __init__(self): # define the object points self.vertices = np.array([(0., 0., 0.), (1., 0., 0.), (1., 1., 0.), (0., 1., 0.), (0., 0., 1.), (1., 0., 1.), (1., 1., 1.), (0., 1., 1.)]) # define the faces (defined by indices of the points) self.faces = np.array([(0, 1, 2, 3), (4, 5, 6, 7), (0, 1, 5, 4), (2, 3, 7, 6)]) # define the object colors self.colors = np.array([(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1)]) # define the object edges self.edges = np.array([(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)])
<gh_stars>1-10 package com.studentsteam.sonic.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.studentsteam.sonic.Main; import com.studentsteam.sonic.screens.assets.ScrollingBackground; import com.studentsteam.sonic.screens.assets.SonicLogo; import com.studentsteam.sonic.screens.assets.TextureActor; import org.apache.log4j.Logger; public class StartScreen implements Screen { //Logs private final Logger log = Logger.getLogger(this.getClass()); private Main game; private Music music; private TextureActor sega; //Stage and viewport private Stage stage; private Viewport viewport; public StartScreen(Main game){ log.info("Запуск начального экрана"); this.game = game; //Texture this.sega = new TextureActor("start/sega.png"); sega.setPosition(Gdx.graphics.getWidth()-sega.getWidth(),5); //Music this.music = Gdx.audio.newMusic(Gdx.files.internal("start/background.mp3")); music.setLooping(false); music.setVolume(0.1f); music.play(); //Creating stage and viewport viewport = new FitViewport(Gdx.graphics.getWidth(),Gdx.graphics.getHeight(),new OrthographicCamera()); stage = new Stage(viewport,game.batch); //Creating scrolling background ScrollingBackground background = new ScrollingBackground("start/BG.png",1.0f); //Creating logo SonicLogo logo = new SonicLogo(); //Adding actors stage.addActor(background); stage.addActor(logo); stage.addActor(sega); } @Override public void show() { } private void handleInput(float delta){ if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){ log.info("Переход к экрану сохранения"); game.setScreen(new SaveScreen(game)); dispose(); } } private void update(float delta){ handleInput(delta); stage.act(delta); } @Override public void render(float delta) { //Update update(delta); //Clears the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); //Draw stage stage.draw(); } @Override public void resize(int width, int height){ } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { music.dispose(); stage.dispose(); } }
<reponame>eMedin4/indice $( document ).ready(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); /************************************************************************************************ RESPONSIVE MENU ************************************************************************************************/ $('.toggle-icon').on('click', function() { $('body').toggleClass('menu-visible'); }); $('.darken-overlay, .info-close').on('click', function() { $('body').removeClass('menu-visible'); }) /************************************************************************************************ SEARCH ************************************************************************************************/ /************************************************************************************************ MODAL GENERIC ************************************************************************************************/ /************************************************************************************************ FILTER ************************************************************************************************/ /* $('.icon-filter').on('click', function() { $('.filter-wrap').addClass('display'); }); var starsSlider = document.getElementById('js-stars-slider'); noUiSlider.create(starsSlider, { start: [ 0, 6], connect: [false, true, false], range: { 'min': 0, 'max': 6 }, step: 1, margin: 1, pips: { mode: 'steps', density: 12 }, format: { to: function ( value ) { return value; }, from: function ( value ) { return value.replace(',-', ''); } } }); starsSlider.noUiSlider.on('change', function() { $('#from-stars').val(starsSlider.noUiSlider.get()[0]); $('#to-stars').val(starsSlider.noUiSlider.get()[1]); }); $('.to-year').on('change', function() { var to = $(this).val(); var from = $('.from-year').val(); if (from > to) { $('.from-year').val(to); } }); $('.from-year').on('change', function() { var to = $('.to-year').val(); var from = $(this).val(); if (from > to) { $('.to-year').val(from); } }); $('#select-all').change(function() { var checkboxes = $('.channel-group').find(':checkbox'); if($(this).is(':checked')) { checkboxes.prop('checked', true); } else { checkboxes.prop('checked', false); } }); $('.btn-channel-dropdown').on('click', function() { $('.channel-group').toggle(); }); //cerrar el modal $('.filter-wrap').on('click', function() { $(this).removeClass('display'); }); //clickando en inner no se cerrará, excepto todo lo que tenga .propagation que si se cerrará $('.filter .inner').on('click', function (e) { if(!$(e.target).is('.propagation')){ e.stopPropagation(); } }); */ /************************************************************************************************ MODAL LOGIN ************************************************************************************************/ $('.js-launch-login').on('click', function() { var facebook = $('.single-wrap').data('facebook'); var google = $('.single-wrap').data('google'); var info = $(this).parent().parent().data('info'); var html = `<div class="login-modal panel-modal"> <h3>Entra</h3> <h4>en Indicecine</h4> <a class="social-btn facebook" href="{{route('authsocial', ['provider' => 'facebook'])}}"> <i class="fa fa-facebook-fa" aria-hidden="true"></i> <span>Entra con Facebook</span> </a> <a class="social-btn google" href="{{route('authsocial', ['provider' => 'google'])}}"> <i class="fa fa-google" aria-hidden="true"></i> <span>Entra con Google</span> </a> <div class="oval-shape"></div> <p>` + info + `</p> </div>`; $('.modal .inner').html(html); $('.modal-wrap').fadeIn(500).css('display','table'); $('.modal input').focus(); }); /************************************************************************************************ MODAL NEW LIST ************************************************************************************************/ $('.js-new-list').on('click', function(){ var t = $(this); var csrf = t.data('csrf'); var movie = t.data('movie'); var url = t.data('url'); var html = `<form method="POST" action="` + url + `" class="modal-new-list" data-movie="` + movie + `"> <input type="hidden" name="_token" value="` + csrf + `"> <h3>Nueva lista</h3> <div class="errors"></div> <input type="text" name="name" maxlength="48" placeholder="Nombre"> <textarea name="description" rows="3" maxlength="500" placeholder="Descripción"></textarea> <div class="btn-group"> <button type="submit" class="btn">Crear</button> <button type="button" class="btn btn-cancel propagation">Cancelar</button> </div> <div class="checkbox"> <input id="check-description" type="checkbox" name="check-description"> <label class="lbl-check" for="check-description">Añadir descripción</label> </div> <div class="checkbox"> <input id="check-ordered" type="checkbox" name="check-ordered"> <label class="lbl-check" for="check-ordered">Lista numerada</label> </div> </form>`; $('.modal .inner').html(html); $('.modal-wrap').fadeIn(500).css('display','table'); $('.modal input').focus(); }); /************************************************************************************************ CREATE NEW LIST ************************************************************************************************/ $('.modal').on('submit', '.modal-new-list', function(e){ e.preventDefault(e); var t = $(this); var url = t.attr('action'); var movie = t.data('movie'); var name = t.find('input[type="text"]').val(); var description = t.find('textarea').val(); var ordered = t.find('#check-ordered').is(":checked") ? 1 : 0; $.ajax({ url: url, type: 'POST', data: { 'name': name, 'movie': movie, 'description': description, 'ordered': ordered } }) .done(function(data) { if (!data.state) { t.find('.errors').text(data.message); } else { $('.modal-wrap').fadeOut(500); if (movie) { /*Si estamos añadiendo desde single movie será el id de la película, si añadimos desde user-lists movie será 0*/ var html = '<li><span class="disable-add-list recent-list">' + data.name + '<i class="icon-check-list fa fa-check"></i></span></li>'; //para que funcione el efecto lo cargamos previamente var new_item = $(html).hide(); $('.my-lists').append(new_item); new_item.show('slow'); } else { //que hacer cuando añadimos desde user-lists var html= ` <article class="new-grid"> <a class="list" href="` + $('.js-new-list').data('path') + `lista/` + data.slugname + `/` + data.id + `"> <div class="list-image relative"> <div class="loop-no-image"></div> </div> <div class="meta"> <span> <span>No hay nada </span> <i class="separator">·</i> <span class="no-wrap"> ahora</span> </span> </div> <div class="loop-title"> <h3>` + data.name + `</h3> </div> </a> </article>`; $('.loop').prepend(html); } } }) .fail(function(data) { var parsed = $.parseJSON(data.responseText).name; t.find('.errors').text(parsed); }); }); if($('body').is('.list222-page')){ /************************************************************************************************ SETTINGS RUBAXA SORTABLE ************************************************************************************************/ var rubitems = document.getElementById('js-loop'); var sortable = Sortable.create(rubitems, { disabled: true, animation: 150, handle: ".medium-image", chosenClass: "js-chosen", // Clase mientras arrastramos filter: ".js-ignore-edit", onUpdate: function () { //reordenamos en la etiqueta order var i = 1; $('.order').each(function (index) { var t = $(this); var old = t.data('current'); if (old > i) { t.html(i + '<i class="icon-order-up fa fa-arrow-up-fi"></i>'); } else if (old < i) { t.html(i + '<i class="icon-order-down fa fa-arrow-down"></i>'); } else { t.html(i); } i++; }); }, }); /************************************************************************************************ ACTIVAR MODO EDICIÓN ************************************************************************************************/ $('.js-on-edit').on('click', function() { sortable.option('disabled', false); $('.info-default').fadeOut(300).promise().done(function(){ $('.info-edit').fadeIn(300); }); $('.loop article').addClass('article-edit'); $('.medium-image').append('<i class="delete-movie fa fa-times"></i>') $('.movie').on('click', function(e) { //la película no es clickable en modo edit e.preventDefault(); }) }); /************************************************************************************************ SALIR MODO EDICIÓN ************************************************************************************************/ var offedit = function() { sortable.option('disabled', true); $('.info-edit').fadeOut(300).promise().done(function(){ $('.info-default').fadeIn(300); }); $('.loop article').removeClass('article-edit'); $('.delete-movie').remove(); $('.movie').unbind('click'); /*Recupera su acción por defecto (inhabilita preventdefault)*/ } $('.js-off-edit').on('click', function() { offedit(); }); /************************************************************************************************ EDITAR INFO ************************************************************************************************/ $('.js-edit-list').on('click', function(){ var t = $(this); var name = $('.info-edit .name').text(); var description = $('.info-edit .description').text(); var order = t.data('order'); var html = `<form class="modal-edit-list"> <h3>Editar lista</h3> <div class="errors"></div> <input type="text" name="name" maxlength="48" value="` + name + `"> <textarea name="description" rows="3" maxlength="500" placeholder="Descripción" ` + (description ? "style='display:block;'" : "") + `>` + description + `</textarea> <div class="btn-group"> <button type="submit" class="btn">Actualizar</button> <button type="button" class="btn btn-cancel propagation">Cancelar</button> </div> <div class="checkbox"> <input id="check-description" type="checkbox" name="check-description" ` + (description ? "checked" : "") + `> <label class="lbl-check" for="check-description">Añadir descripción</label> </div> <div class="checkbox"> <input id="check-ordered" type="checkbox" name="check-ordered" ` + (order == 1 ? "checked" : "") + `> <label class="lbl-check" for="check-ordered">Lista numerada</label> </div> </form>`; $('.modal .inner').html(html); $('.modal-wrap').fadeIn(500).css('display','table'); $('.modal input').focus(); }); $('.modal').on('submit', '.modal-edit-list', function(e){ e.preventDefault(e); var name = $('input[name=name]').val(); if ($('#check-description').is(":checked")) var description = $('textarea[name=description]').val(); else var description = ""; $('.info-edit .name').text(name); $('.info-edit .description').text(description); $('.modal-wrap').fadeOut(500); }); /************************************************************************************************ VALIDAR EDICIÓN ************************************************************************************************/ $('.edit-submit').on('click', function() { var t = $(this); var url = t.data('url'); var list = t.data('id'); var title = $('.info-edit .name').text(); var description = $('.info-edit .description').text(); var movies = []; $('.movie').each(function (index) { var id = $(this).data('id'); movies[index] = id; }); $.ajax({ url: url, type: 'POST', data: { 'list': list, 'movies': movies, 'title': title, 'description': description } }) .done(function(data) { offedit(); $('.original-name').text(title); //existia <h2>description</h2>? SI if ($('.original-description').length) { //existe ahora description? if (description) { $('.original-description').text(description); } else { $('.original-description').remove(); } //existia <h2>description</h2>? NO } else { //existe ahora description? if (description) { $('.original-name').after('<h2 class="original-description">' + description + '</h2>'); } } $('.time').text('Actualizada ahora'); }) .fail(function(data) { console.log('error'); }); }); /************************************************************************************************ BORRAR LISTA ************************************************************************************************/ $('.edit-delete').on('click', function() { var name = $(this).data('name'); var html=`<div>Vas a borrar la lista</div> <h3>`+ name + `</h3> <div class="btn-group-alt"> <span class="btn btn-cancel propagation">Cancelar</span> <span class="btn btn-alert edit-delete-confirm propagation">Borrar definitivamente</span> </div>`; $('.modal .inner').html(html); $('.modal-wrap').fadeIn(500).css('display','table'); }); $('.modal').on('click', '.edit-delete-confirm', function() { var id = $('.edit-delete').data('id'); var url = $('.edit-delete').data('url'); var redirect_url = $('.edit-delete').data('redirect'); $.ajax({ url: url, type: 'POST', data: { 'id': id } }) .done(function(data) { console.log(data); window.location.href = redirect_url; }) .fail(function(data) { console.log('error'); }); }); /************************************************************************************************ GUARDAR LISTA EN MIS LISTAS ************************************************************************************************/ $('.info').on('click', '.js-add-to-mylists', function(){ var t = $(this); var list = t.data('id'); var url = t.data('url'); $.ajax({ url: url, type: 'POST', data: { 'list': list } }) .done(function(data) { t.removeClass('js-add-to-mylists').addClass('btn-success btn-single').html('¡Guardada en mis listas!'); }) .fail(function(data) { console.log('error'); }); }); /************************************************************************************************ BORRAR LISTA DE MIS LISTAS ************************************************************************************************/ $('.info').on('click', '.js-del-from-mylists', function(){ var t = $(this); var list = t.data('id'); var url = t.data('url'); $.ajax({ url: url, type: 'POST', data: { 'list': list } }) .done(function(data) { t.siblings('.btn-success').remove(); t.removeClass('js-del-from-mylists btn-double').addClass('btn-success btn-single').text('¡Borrada de mis listas!'); }) .fail(function(data) { console.log('error'); }); }); }/*endif is .list-page*/ /************************************************************************************************ SUMMARY ************************************************************************************************/ /*OCULTAR LISTAS DE REPARTO DEMASIADO LARGAS*/ /*$('.js-characters a:lt(10)').show(); $('.more').on('click', function() { $('.js-characters a').fadeIn(); $(this).fadeOut(); });*/ /*MENU SUMMARY MOBILE*/ $('.summary-menu').on('click', '.launch-menu', function() { var t = $(this); var selector = '.' + t.data('launch'); $('.summary-part').fadeOut(200); $(selector).fadeIn(200); $('.summary-menu .active').removeClass('active').addClass('launch-menu'); t.removeClass('launch.menu').addClass('active'); }); /************************************************************************************************ new SHOW TEXTAREA DESCRIPTION ************************************************************************************************/ $('.modal').on('change', '#check-description', function() { if($('#check-description').is(":checked")) $(".modal textarea").fadeIn(300); else $(".modal textarea").hide(); }); /************************************************************************************************ new MODALS GENERIC ************************************************************************************************/ $('.modal-wrap').on('click', function () { $(this).removeClass('display'); }); $('.modal-inner').on('click', function (e) { //hacemos que con el boton modal-close si se cierre el modal if(!$(e.target).is('.propagation')){ e.stopPropagation(); } }); $('.btn-launch-lists').on('click', function() { $('.modal-wrap-add-to-list').addClass('display'); }); $('.btn-new-list').on('click', function() { //¿donde estamos?: info, add-to-list o edit-list var position = $(this).data('position'); $('.position').val(position); //si viene de add-to-list lo ocultamos $('.modal-wrap-add-to-list').removeClass('display'); //si viene de edit list rellenamos los campos if (position == 'edit-list') { var title = $('h1').text(); var description = $('.list-description').text(); $('input[name=name]').val(title); if (description) { $('textarea[name=description]').val(description); $(".modal textarea").show(); $('#check-description').prop('checked', true); } $('.modal-wrap-new-list h3').text('Editar lista'); $('.modal-wrap-new-list button[type="submit"]').text('Editar'); } else { //si no los vaciamos por si previamente se han rellenado $('input[name=name]').val(''); $(".modal textarea").hide(); $('textarea[name=description]').val(''); $('#check-description').prop('checked', false); $('#check-ordered').prop('checked', false); $('.modal-wrap-new-list h3').text('Crear nueva lista'); $('.modal-wrap-new-list button[type="submit"]').text('Crear'); } //y mostramos $('.modal-wrap-new-list').addClass('display'); }); $('.btn-launch-filters').on('click', function() { $('.modal-wrap-filters').addClass('display'); }); $('.btn-delete').on('click', function() { var t = $(this); var id = t.data('id'); var type = t.data('type'); var text = t.data('text'); $('.form-delete input[name="id"]').val(id); $('.form-delete input[name="type"]').val(type); $('.modal-wrap-confirm h3').text(text); $('.modal-wrap-confirm').addClass('display'); }); /************************************************************************************************ AÑADIR PELÍCULA A UNA LISTA ************************************************************************************************/ $('.add-to-list').on('click', '.add-to-list-active', function(){ var t = $(this); var addtolist = $('.add-to-list'); var list = t.data('id'); var ordered = t.data('ordered'); var movie = addtolist.data('movie'); var url = addtolist.data('url'); //icono de espera t.append('<div class="wait"><i class="fa fa-circle-o-notch"></i></div>'); $.ajax({ url: url, type: 'POST', data: { 'list': list, 'movie': movie, 'ordered': ordered } }) .done(function(data) { t.find('.wait').remove(); t.removeClass('add-to-list-active').addClass('add-to-list-disable'); var count = parseInt(t.find('.item-count').text()) + 1; t.find('.item-count').text(count); $('.item-list').find('li[data-id=' + list +'] .item-count').text(count); }) .fail(function(data) { t.find('.wait').remove(); }); }); /*BORRAR PELÍCULA DE LISTA*/ $('.add-to-list').on('click', '.add-to-list-disable', function(){ var t = $(this); var addtolist = $('.add-to-list'); var list = t.data('id'); var movie = addtolist.data('movie'); var url = addtolist.data('alturl'); //icono de espera t.append('<div class="wait"><i class="fa fa-circle-o-notch"></i></div>'); $.ajax({ url: url, type: 'POST', data: { 'list': list, 'movie': movie } }) .done(function(data) { t.find('.wait').remove(); t.removeClass('add-to-list-disable').addClass('add-to-list-active'); var count = parseInt(t.find('.item-count').text()) - 1; t.find('.item-count').text(count); $('.item-list').find('li[data-id=' + list +'] .item-count').text(count); }) .fail(function(data) { t.find('.wait').remove(); }); }); /************************************************************************************************ CREAR LISTAS O EDITAR SU INFO ************************************************************************************************/ $('.form-new-list').submit(function(e) { e.preventDefault(e); var t = $(this); var name = t.find('input[name="name"]').val(); var description = t.find('textarea[name="description"]').val(); var ordered = t.find('#check-ordered').is(":checked") ? 1 : 0; var movie = t.data('movie'); var position = $('.position').val(); //SI ESTAMOS CREANDO UNA LISTA DESDE INFO if (position == 'info') { var url = t.data('actionnew'); $.ajax({ url: url, type: 'POST', data: { 'name': name, 'movie': movie, 'description': description, 'ordered': ordered, 'position': position } }) .done(function(data) { $('.modal-wrap-new-list').removeClass('display'); /*var html = `<li data-id="` + id + `"><a href="` + link + `"><span>` + name + `</span><span class="item-count">` + count + `</span></a></li>`; $('.my-likes').append(html).hide().fadeIn(300);*/ }) .fail(function(data) { console.log(data); }); //SI ESTAMOS CREANDO UNA LISTA DESDE ADD-TO-LIST } else if (position == 'add-to-list') { var url = t.data('actionnew'); $.ajax({ url: url, type: 'POST', data: { 'name': name, 'movie': movie, 'description': description, 'ordered': ordered, 'position': position } }) .done(function(data) { $('.modal-wrap-new-list').removeClass('display'); $('.modal-wrap-add-to-list').addClass('display'); var html = `<li><div class="add-to-list-disable lbl-check">` + data.name + `<span class="item-count">1</span>`; $('.add-to-list li:first').before(html); }) .fail(function(data) { console.log(data); }); //SI LA ESTAMOS EDITANDO } else if (position == 'edit-list') { var url = t.data('actionedit'); var id = $('h1').data('id'); $.ajax({ url: url, type: 'POST', data: { 'name': name, 'description': description, 'ordered': ordered, 'id': id } }) .done(function(data) { $('h1').hide().text(name).fadeIn(); $('.list-description').hide().text(description).fadeIn(); $('.modal-wrap-new-list').removeClass('display'); }) .fail(function(data) { console.log(data); }); } }); /************************************************************************************************ BORRAR PELICULAS O LISTAS DESDE EL MODAL DE CONFIRMACIÓN (EN EDITLIST) ************************************************************************************************/ $('.form-delete').on('submit', function(e) { e.preventDefault(e); var type = $('.form-delete input[name="type"]').val(); var movieId = $('.form-delete input[name="id"]').val(); var listId = $('h1').data('id'); //SI ES UNA PELÍCULA if (type == 'delete-movie') { var url = $(this).data('actionmovie'); $.ajax({ url: url, type: 'POST', data: { 'list': listId, 'movie': movieId } }) .done(function(data) { $('.modal-wrap').removeClass('display'); var selector = "article[data-id=" + movieId + "]"; $(selector).remove(); }) .fail(function(data) { console.log(data); }); //SI ES UNA LISTA } else if (type == 'delete-list') { var url = $(this).data('actionlist'); var redirect = $(this).data('redirect'); $.ajax({ url: url, type: 'POST', data: { 'listid': listId } }) .done(function(data) { $('.modal-wrap').removeClass('display'); console.log(data); window.location.href = redirect; }) .fail(function(data) { console.log(data); }); } }); /************************************************************************************************ ME GUSTA A LISTA ************************************************************************************************/ $('.list-info').on('click', '.btn-launch-like', function() { var h1 = $('h1'); var t = $(this); var id = h1.data('id'); var url = t.data('url'); var alturl = $(this).data('alturl'); console.log(url); $.ajax({ url: url, type: 'POST', data: { 'id': id } }) .done(function(data) { //transformamos boton de like a dislike t.removeClass('launch-like btn-launch-like').addClass('launch-dislike btn-launch-dislike'); t.find('i').removeClass('fa-heart-full-outline').addClass('fa-check'); t.data('url', alturl).data('alturl', url); //creamos la lista en info-lista var link = h1.data('link'); var name = h1.text(); var count = h1.data('counter'); var html = `<li data-id="` + id + `"><a href="` + link + `"><span>` + name + `</span><span class="item-count">` + count + `</span></a></li>`; $('.my-likes').append(html).hide().fadeIn(300); }) .fail(function(data) { }); }); /*YA NO ME GUSTA*/ $('.list-info').on('click', '.btn-launch-dislike', function() { var t = $(this); var id = $('h1').data('id'); var url = t.data('url'); var alturl = $(this).data('alturl'); console.log(url); $.ajax({ url: url, type: 'POST', data: { 'id': id } }) .done(function(data) { //transformamos boton de dislike a like t.removeClass('launch-dislike btn-launch-dislike').addClass('launch-like btn-launch-like'); t.find('i').removeClass('fa-check').addClass('fa-heart-full-outline'); t.data('url', alturl).data('alturl', url); //borramos de la info-lista $('.my-likes').find('li[data-id=' + id + ']').fadeOut(300, function() { $(this).remove(); }); }) .fail(function(data) { }); }); /************************************************************************************************ new BUSCAR ************************************************************************************************/ /*$('.search-launch').on('click', function() { $('.search').addClass('visible'); $('.input-search').focus(); }); $('.search .close').on('click', function() { $('.search').removeClass('visible'); }); $('.input-search').focusout(function() { $('.search-results, .search-results-wrap').fadeOut(300); }); $('.input-search').focusin(function() { //para que solo aparezcan si hay resultados if ($('.search-item').length && $(this).length) { $('.search-results, .search-results-wrap').fadeIn(300); } });*/ $('.input-search').bind('paste keyup', function() { var t = $(this); var string = t.val(); var ilength = string.length; var url = t.data('url'); var path = t.data('path'); if (ilength > 2) { $.ajax({ url: url, type: 'POST', data: { 'string': string } }).done(function(data) { if (data.response == true) { /*si hay resultados*/ $('.search-results').html('<div class="inner"></div>'); /*$('.loop').html('');*/ $.each(data.result, function(key,val) { if (val.check_poster) { var fullImgPath = path + `assets/movieimages/posters/sml/` + val.slug + `.jpg`; } else { var fullImgPath = path + `assets/images/no-poster-small.png`; } var html = `<div class="search-item"> <a href="` + path + val.slug + `"> <img src="` + fullImgPath + `" width="30" height="45"> </a> <div class="search-item-data"> <a class="title" href="` + path + val.slug + `">` + val.title + `</a> <div class="loop-features">` + val.year + `<div class="country country-` + val.country + `" title="` + val.country + `"></div> <div class="stars stars-` + val.avg + `"></div> </div> </div> </div>`; $('.search-results .inner').append(html); }); } else { $('.search-results').html(''); } }).fail(function() { console.log('no se envia'); }); } else { //si tiene menos de 3 carácteres $('.search-results').html(''); } }); /************************************************************************************************ new DESPLEGAR ACTORES ************************************************************************************************/ $('.more').on('click', function() { $('.actors .hide').addClass('show-inline'); $(this).addClass('hide'); }); });
# ********************************************************** # Copyright (c) 2007 VMware, Inc. All rights reserved. # ********************************************************** # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of VMware, Inc. nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH # DAMAGE. # FIXME: use a real tag in CVS when this is done for real # -kv doesn't handle properly binary files mkdir dynamorio cd dynamorio #export CO=checkout -D 2007-09-28 # note a date in the future should work fine # thanksgiving_cvs_snapshot is last CVS checkin # look for the code at its new home at perforce-tiger://depot/dynamorio/... # all modules in both repositories should be tagged with cvs rtag thanksgiving_cvs_snapshot export TAG=thanksgiving_cvs_snapshot # -D 2007-11-21 export CO="export -r $TAG -kv" #rename src -> core cvs -d /repo/cvseast $CO -d core src cvs -d /repo/cvseast $CO tools #rename share -> libutil cvs -d /repo/cvs $CO -d libutil share #rename liveshield-update -> liveshield cvs -d /repo/cvs $CO -d liveshield liveshield-update cvs -d /repo/cvseast $CO suite cvs -d /repo/cvseast $CO api cvs -d /repo/cvseast $CO clients cvs -d /repo/cvseast $CO win32lore cvs -d /repo/cvseast $CO docs cvs -d /repo/cvseast $CO papers #remove some old stuff rm -rf docs/status cvs -d /repo/cvs $CO nightly cvs -d /repo/cvs $CO nodemgr cvs -d /repo/cvs $CO threatinfo # these take a little more time, comment out if testing # EAST coast repository cvs -d /repo/cvseast $CO exploits cvs -d /repo/cvs $CO -d exploits exploits # merge from west coast repository exploits/antihips cvs -d /repo/cvseast $CO benchmarks cvs -d /repo/cvseast $CO spec2kdata # adding config temporarily cvs -d /repo/cvs $CO config ### below the line # detertray # do we want the exploits from the west coast repository?? cd .. tar czvf dynamorio-main.tgz dynamorio
#!/bin/bash # remember to update the compiled train: # NB: directory where program is run (PATH_TO/fbcode) matters # buck build @mode/opt -c fbcode.platform=gcc-4.9-glibc-2.20 experimental/commai/env/src:train # cp ~/fbsource/fbcode/buck-out/gen/experimental/commai/env/src/train.par /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/ # NB: paths might have to be updated to the flash/non-flash directory!!! # also, the relevant config files must be copied to the directory above # COMPOSITIONAL echo compositional 1 exp_name="3bit_up_to_3_eight_1_compositional" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_1_compositional.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo compositional 2 exp_name="3bit_up_to_3_eight_2_compositional" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_2_compositional.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo compositional 3 exp_name="3bit_up_to_3_eight_3_compositional" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_3_compositional.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo compositional 4 exp_name="3bit_up_to_3_eight_4_compositional" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_4_compositional.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo compositional 5 exp_name="3bit_up_to_3_eight_5_compositional" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_5_compositional.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - # CONTROL echo control 1 exp_name="3bit_up_to_3_eight_1_control" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_1_control.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo control 2 exp_name="3bit_up_to_3_eight_2_control" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_2_control.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo control 3 exp_name="3bit_up_to_3_eight_3_control" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_3_control.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo control 4 exp_name="3bit_up_to_3_eight_4_control" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_4_control.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo control 5 exp_name="3bit_up_to_3_eight_5_control" temp_dir="/tmp/$exp_name" config_file="tasks_config.3bit_up_to_3_eight_5_control.json" my_processes="mkdir $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/train.par $temp_dir; cp /mnt/vol/gfsai-flash-east/ai-group/users/mbaroni/lookup_experiments/$config_file $temp_dir; OMP_NUM_THREADS=1 $temp_dir/train.par $temp_dir/$config_file --learner experimental.learner.BlockControlGraphLearner -s core.serializer.IdentitySerializer --max-reward-per-task 50000000000 --err_debug True --ponder_env True --view experimental.view.View --nhid 150 --sparcity 0 --dropout 0 --nreplay 1 --entropy_reg 0.1 --lr 1e-3 --gamma 0.99 --Cblock 10 --rnntype LSTM --log_interval 1000 --exp_name ${exp_name}_ --log_dir $temp_dir --num_processes 10 --output $temp_dir/${exp_name}_outfile --vis_interval 100; cp -r $temp_dir /mnt/vol/gfsai-east/ai-group/users/mbaroni/lookup_experiments;" echo "$my_processes" | crun -G 0 -C 10 -M 40 --retries 3 --hostgroup fblearner_ash_cpuram_default - echo done launching jobs
/*ckwg +29 * Copyright 2017-2019 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither name of Kitware, Inc. nor the names of any contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * \file * \brief Core feature_descriptor_io interface */ #ifndef KWIVER_ARROWS_CORE_FEATURE_DESCRIPTOR_IO_H_ #define KWIVER_ARROWS_CORE_FEATURE_DESCRIPTOR_IO_H_ #include <arrows/core/kwiver_algo_core_export.h> #include <vital/algo/feature_descriptor_io.h> namespace kwiver { namespace arrows { namespace core { /// A class for reading and writing feature and desriptor sets class KWIVER_ALGO_CORE_EXPORT feature_descriptor_io : public vital::algorithm_impl<feature_descriptor_io, vital::algo::feature_descriptor_io> { public: PLUGIN_INFO( "core", "Read and write features and descriptor" " to binary files using Cereal serialization." ) /// Constructor feature_descriptor_io(); /// Destructor virtual ~feature_descriptor_io(); /// Get this algorithm's \link vital::config_block configuration block \endlink virtual vital::config_block_sptr get_configuration() const; /// Set this algorithm's properties via a config block virtual void set_configuration(vital::config_block_sptr config); /// Check that the algorithm's currently configuration is valid virtual bool check_configuration(vital::config_block_sptr config) const; private: /// Implementation specific load functionality. /** * Concrete implementations of feature_descriptor_io class must provide an * implementation for this method. * * \param filename the path to the file the load * \param feat the set of features to load from the file * \param desc the set of descriptors to load from the file */ virtual void load_(std::string const& filename, vital::feature_set_sptr& feat, vital::descriptor_set_sptr& desc) const; /// Implementation specific save functionality. /** * Concrete implementations of feature_descriptor_io class must provide an * implementation for this method. * * \param filename the path to the file to save * \param feat the set of features to write to the file * \param desc the set of descriptors to write to the file */ virtual void save_(std::string const& filename, vital::feature_set_sptr feat, vital::descriptor_set_sptr desc) const; /// private implementation class class priv; const std::unique_ptr<priv> d_; }; } // end namespace core } // end namespace arrows } // end namespace kwiver #endif
import * as React from 'react'; import {Route} from 'react-router-dom'; import { NavLink } from 'react-router-dom'; import Account from './account'; import Password from './Password'; import AddProfile from './AddProfile'; class Settings extends React.Component<any, any>{ render(){ return ( <div className="container p-5"> <div className="row"> <div className="col-2 bg-white p-0 shadow border"> {/* <nav className="navbar"> */} <ul className="nav nav-pills"> <li className="nav-item w-100"> <NavLink to="/settings/account" className="nav-link">Account</NavLink> </li> <li className="nav-item w-100"> <NavLink to="/settings/password" className="nav-link">Password</NavLink> </li> <li className="nav-item w-100"> <NavLink to="/settings/profile" className="nav-link">Profile</NavLink> </li> {/* <li className="nav-item w-100"> <NavLink to="/settings/contacts" className="nav-link">Contacts</NavLink> </li> */} </ul> {/* </nav> */} </div> <div className="col-10"> <Route exact path="/settings/account" component={(props) => <Account {...props} user={this.props.user}/>}/> <Route exact path="/settings/password" component={(props) => <Password {...props} user={this.props.user}/>}/> <Route exact path="/settings/profile" component={(props) => <AddProfile {...props} user={this.props.user}/>}/> {/* <Route exact path="/settings/contacts" component={(props) => <Account {...props} user={this.props.user}/>}/> */} </div> </div> </div> ); } } export default Settings;
<reponame>ourcade/phaser3-typescript-examples<gh_stars>10-100 import Phaser from 'phaser' export default class Muybridge extends Phaser.Scene { preload() { this.load.spritesheet('muybridge','/assets/animations/muybridge01.png', { frameWidth: 119, frameHeight: 228 }) } create() { var config: Phaser.Types.Animations.Animation = { key: 'run', frames: this.anims.generateFrameNumbers('muybridge', {}), frameRate: 15, repeat: -1 }; this.anims.create(config) // Each frame is 119px wide const group = this.add.group() group.createMultiple({ key: 'muybridge', frame: 0, repeat: 8 }) Phaser.Actions.GridAlign(group.getChildren(), { width: 9, height: 1, cellWidth: 119, y: 170 }) this.anims.staggerPlay('run', group.getChildren(), -100) } }
# Copyright 2020 Cloudbase Solutions Srl # Copyright 2019 <EMAIL> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import base64 import gzip import io import os from oslo_log import log as oslo_logging from cloudbaseinit import conf as cloudbaseinit_conf from cloudbaseinit import exception from cloudbaseinit.metadata.services import base from cloudbaseinit.osutils import factory as osutils_factory from cloudbaseinit.utils import serialization from cloudbaseinit.metadata.services import nocloudservice CONF = cloudbaseinit_conf.CONF LOG = oslo_logging.getLogger(__name__) class VMwareGuestInfoService(base.BaseMetadataService): def __init__(self): super(VMwareGuestInfoService, self).__init__() self._rpc_tool_path = None self._osutils = osutils_factory.get_os_utils() self._meta_data = {} self._user_data = None @staticmethod def _decode_data(raw_data, is_base64, is_gzip): """Decode raw_data from base64 / ungzip""" if not raw_data: return if is_base64: raw_data = base64.b64decode(raw_data) if is_gzip: with gzip.GzipFile(fileobj=io.BytesIO(raw_data), mode='rb') as dt: raw_data = dt.read() return raw_data def _get_guestinfo_value(self, key): rpc_command = 'info-get guestinfo.%s' % key data, stderr, exit_code = self._osutils.execute_process([ self._rpc_tool_path, rpc_command ]) if exit_code: LOG.debug( 'Failed to execute "%(rpctool_path)s \'%(rpc_command)s\'" ' 'with exit code: %(exit_code)s\nstdout: ' '%(stdout)s\nstderr: %(stderr)s' % { 'rpctool_path': self._rpc_tool_path, 'rpc_command': rpc_command, 'exit_code': exit_code, 'stdout': data, 'stderr': stderr}) return return data def _get_guest_data(self, key): is_base64 = False is_gzip = False encoding_plain_text = 'plaintext' raw_data = self._get_guestinfo_value(key) raw_encoding = self._get_guestinfo_value("%s.encoding" % key) if not raw_encoding or not raw_encoding.strip(): raw_encoding = encoding_plain_text encoding = raw_encoding.strip() if isinstance(encoding, bytes): encoding = encoding.decode("utf-8") if encoding in ('gzip+base64', 'gz+b64'): is_gzip = True is_base64 = True elif encoding in ('base64', 'b64'): is_base64 = True elif encoding != encoding_plain_text: raise exception.CloudbaseInitException( "Encoding %s not supported" % encoding) LOG.debug("Decoding key %s: encoding %s", key, encoding) return self._decode_data(raw_data, is_base64, is_gzip) def load(self): super(VMwareGuestInfoService, self).load() if not CONF.vmwareguestinfo.vmware_rpctool_path: LOG.info("rpctool_path is empty. " "Please provide a value for VMware rpctool path.") return False self._rpc_tool_path = os.path.abspath( os.path.expandvars(CONF.vmwareguestinfo.vmware_rpctool_path)) if not os.path.exists(self._rpc_tool_path): LOG.info("%s does not exist. " "Please provide a valid value for VMware rpctool path." % self._rpc_tool_path) return False self._meta_data = serialization.parse_json_yaml( self._get_guest_data('metadata')) if not isinstance(self._meta_data, dict): LOG.warning("Instance metadata is not a dictionary.") self._meta_data = {} self._user_data = self._get_guest_data('userdata') if self._meta_data or self._user_data: return True def _get_data(self, path): pass def get_instance_id(self): return self._meta_data.get('instance-id') def get_user_data(self): return self._user_data def get_host_name(self): return self._meta_data.get('local-hostname') def get_public_keys(self): public_keys = [] public_keys_data = self._meta_data.get('public-keys-data') if public_keys_data: public_keys = public_keys_data.splitlines() return list(set((key.strip() for key in public_keys))) def get_admin_username(self): return self._meta_data.get('admin-username') def get_admin_password(self): return self._meta_data.get('admin-password') def get_network_details_v2(self): network_data = self._meta_data.get('network') if not network_data: LOG.info("No network configuration found in metadata") return network_data_version = network_data.get("version") if network_data_version != 1: LOG.error("Network data version '%s' is not supported", network_data_version) return network_config_parser = nocloudservice.NoCloudNetworkConfigV1Parser() return network_config_parser.parse(network_data.get("config"))
/* * Copyright 2019 Wultra s.r.o. * * 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 io.getlime.security.powerauth.lib.webflow.authentication.method.form.encryption; import com.google.common.io.BaseEncoding; import io.getlime.security.powerauth.lib.webflow.authentication.encryption.AesEncryptionPasswordProtection; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.*; /** * Test class for the AES password encryptor. * * @author <NAME>, <EMAIL> */ class AesEncryptionPasswordProtectionTest { @BeforeAll static void setUp() { Security.addProvider(new BouncyCastleProvider()); } @org.junit.jupiter.api.Test void protect() throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchProviderException { final String secretKeyBase64 = "<KEY>; final String cipherTransformation = "AES/CBC/PKCS7Padding"; final String originalPassword = "<PASSWORD>"; System.out.println("Encrypting Password: '" + originalPassword + "' with key '" + secretKeyBase64 + "' using '" + cipherTransformation + "' mode." ); String decryptedPassword; // Decrypt previously known password String encryptedPassword = "<PASSWORD>==:<PASSWORD>=="; decryptedPassword = decryptPassword(secretKeyBase64, cipherTransformation, encryptedPassword); System.out.println("Encrypted Password - static: " + encryptedPassword); System.out.println("Decrypted Password - static: " + decryptedPassword); Assertions.assertEquals(decryptedPassword, originalPassword); // Perform repeated encryption and decryption of passwords AesEncryptionPasswordProtection inst = new AesEncryptionPasswordProtection(cipherTransformation, secretKeyBase64); for (int i = 0; i < 10; i++){ encryptedPassword = inst.protect(originalPassword); System.out.println("Encrypted Password " + i + ": " + encryptedPassword); decryptedPassword = decryptPassword(secretKeyBase64, cipherTransformation, encryptedPassword); System.out.println("Decrypted Password " + i + ": " + decryptedPassword); Assertions.assertEquals(decryptedPassword, originalPassword); } } private String decryptPassword(String secretKeyBase64, String cipherTransformation, String encryptedPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException { // Read secret key from configuration byte[] secretKeyBytes = BaseEncoding.base64().decode(secretKeyBase64); SecretKey secretKey = new SecretKeySpec(secretKeyBytes, "AES"); // Extract IV and encrypted password and convert them to bytes String[] parts = encryptedPassword.split(":"); if (parts.length != 2) { throw new IllegalArgumentException("Invalid request"); } String ivBase64 = parts[0]; byte[] ivBytes = BaseEncoding.base64().decode(ivBase64); String encryptedPasswordBase64 = parts[1]; byte[] encryptedPasswordBytes = BaseEncoding.base64().decode(encryptedPasswordBase64); // Decrypt password using specified cipher transformation, extracted IV and encrypted password bytes Cipher cipher = Cipher.getInstance(cipherTransformation, "BC"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(ivBytes)); byte[] decryptedPasswordBytes = cipher.doFinal(encryptedPasswordBytes); return new String(decryptedPasswordBytes, StandardCharsets.UTF_8); } }
#!/bin/sh aclocal -I m4 || exit 1 autoconf || exit 1
import React from 'react' import Link from 'gatsby-link' const Footer = () => ( <footer className="section"> <div className="diviider"></div> <div className="w-container"> <div className="w-row"> <div className="w-col w-col-3"> <Link to="/" className="brand black w-nav-brand"> <div>Logotype</div> </Link> </div> <div className="w-col w-col-3"> <h4>Here is links</h4> <Link to="#" className="footer-links">Career</Link> <Link to="#" className="footer-links">Press</Link> <Link to="#" className="footer-links">Help</Link> <Link to="#" className="footer-links">Polices</Link> </div> <div className="w-col w-col-3"> <h4>About us</h4> <Link to="#" className="footer-links">Contacts</Link> <Link to="#" className="footer-links">Another links</Link> </div> <div className="w-col w-col-3"> <h4>Have a hotel?</h4> <Link to="#" className="footer-links">How add your hotel</Link> </div> </div> <div className="diviider"></div> <div className="copyrights"> <h5> {/* Created by <Link to="http://eric-design.ru">eric-design.ru</Link> */} Created by <Link to="http://ostrumtech.com">Ostrumtech</Link> </h5> </div> </div> </footer> ) export default Footer
from typing import Callable, Iterable, List, Iterator, Tuple, Union, Dict, Any from dataclasses import dataclass import time import tqdm import logging from opentelemetry import trace from datapipe.types import DataDF, IndexDF from datapipe.compute import ComputeStep, PipelineStep, Catalog, DatatableTransformStep from datapipe.datatable import DataStore, DataTable from datapipe.run_config import RunConfig from datapipe.types import ChangeList logger = logging.getLogger('datapipe.core_steps') tracer = trace.get_tracer("datapipe.core_steps") BatchTransformFunc = Callable[..., Union[DataDF, List[DataDF]]] def do_batch_transform( func: BatchTransformFunc, ds: DataStore, input_dts: List[DataTable], output_dts: List[DataTable], idx_gen: Iterable[IndexDF], idx_count: int = None, run_config: RunConfig = None, ) -> Iterator[ChangeList]: ''' Множественная инкрементальная обработка `input_dts' на основе изменяющихся индексов ''' logger.info(f'Items to update {idx_count}') if idx_count is not None and idx_count == 0: # Nothing to process return [ChangeList()] for idx in tqdm.tqdm(idx_gen, total=idx_count): with tracer.start_as_current_span("process batch"): logger.debug(f'Idx to process: {idx.to_records()}') with tracer.start_as_current_span("get input data"): input_dfs = [inp.get_data(idx) for inp in input_dts] changes = ChangeList() if sum(len(j) for j in input_dfs) > 0: with tracer.start_as_current_span("run transform"): try: chunks_df = func(*input_dfs) except Exception as e: logger.error(f"Transform failed ({func.__name__}): {str(e)}") ds.event_logger.log_exception(e, run_config=run_config) continue if isinstance(chunks_df, (list, tuple)): assert len(chunks_df) == len(output_dts) else: assert len(output_dts) == 1 chunks_df = [chunks_df] with tracer.start_as_current_span("store output batch"): for k, res_dt in enumerate(output_dts): # Берем k-ое значение функции для k-ой таблички # Добавляем результат в результирующие чанки change_idx = res_dt.store_chunk( data_df=chunks_df[k], processed_idx=idx, run_config=run_config, ) changes.append(res_dt.name, change_idx) else: with tracer.start_as_current_span("delete missing data from output"): for k, res_dt in enumerate(output_dts): del_idx = res_dt.meta_table.get_existing_idx(idx) res_dt.delete_by_idx(del_idx, run_config=run_config) changes.append(res_dt.name, del_idx) yield changes def do_full_batch_transform( func: BatchTransformFunc, ds: DataStore, input_dts: List[DataTable], output_dts: List[DataTable], chunk_size: int = 1000, run_config: RunConfig = None, ) -> None: with tracer.start_as_current_span("compute ids to process"): idx_count, idx_gen = ds.get_full_process_ids( inputs=input_dts, outputs=output_dts, chunk_size=chunk_size, run_config=run_config ) gen = do_batch_transform( func, ds=ds, idx_count=idx_count, idx_gen=idx_gen, input_dts=input_dts, output_dts=output_dts, run_config=run_config, ) for changes in gen: pass @dataclass class BatchTransform(PipelineStep): func: Callable inputs: List[str] outputs: List[str] chunk_size: int = 1000 def build_compute(self, ds: DataStore, catalog: Catalog) -> List[ComputeStep]: input_dts = [catalog.get_datatable(ds, name) for name in self.inputs] output_dts = [catalog.get_datatable(ds, name) for name in self.outputs] return [ BatchTransformStep( f'{self.func.__name__}', input_dts=input_dts, output_dts=output_dts, func=self.func, chunk_size=self.chunk_size, ) ] class BatchTransformStep(ComputeStep): name: str input_dts: List[DataTable] output_dts: List[DataTable] def __init__( self, name: str, input_dts: List[DataTable], output_dts: List[DataTable], func: BatchTransformFunc, kwargs: Dict[str, Any] = None, chunk_size: int = 1000, ) -> None: self.name = name self.input_dts = input_dts self.output_dts = output_dts self.func = func self.kwargs: Dict[str, Any] = kwargs or {} self.chunk_size = chunk_size def get_name(self) -> str: return self.name def get_input_dts(self) -> List[DataTable]: return self.input_dts def get_output_dts(self) -> List[DataTable]: return self.output_dts def run_full(self, ds: DataStore, run_config: RunConfig = None) -> None: run_config = RunConfig.add_labels(run_config, {'step_name': self.name}) idx_count, idx_gen = ds.get_full_process_ids( inputs=self.input_dts, outputs=self.output_dts, chunk_size=self.chunk_size, run_config=run_config ) gen = do_batch_transform( self.func, ds=ds, idx_count=idx_count, idx_gen=idx_gen, input_dts=self.input_dts, output_dts=self.output_dts, run_config=run_config, ) for changes in gen: pass def run_changelist(self, ds: DataStore, change_list: ChangeList, run_config: RunConfig = None) -> ChangeList: run_config = RunConfig.add_labels(run_config, {'step_name': self.name}) idx_count, idx_gen = ds.get_change_list_process_ids( inputs=self.input_dts, outputs=self.output_dts, change_list=change_list, chunk_size=self.chunk_size, run_config=run_config ) gen = do_batch_transform( self.func, ds=ds, input_dts=self.input_dts, output_dts=self.output_dts, idx_count=idx_count, idx_gen=idx_gen, run_config=run_config, ) res_changelist = ChangeList() for changes in gen: res_changelist.extend(changes) return res_changelist BatchGenerateFunc = Callable[[], Iterator[Tuple[DataDF, ...]]] def do_batch_generate( func: BatchGenerateFunc, ds: DataStore, output_dts: List[DataTable], run_config: RunConfig = None ) -> None: import inspect import pandas as pd ''' Создание новой таблицы из результатов запуска `proc_func`. Функция может быть как обычной, так и генерирующейся ''' now = time.time() empty_generator = True assert inspect.isgeneratorfunction(func), "Starting v0.8.0 proc_func should be a generator" with tracer.start_as_current_span("init generator"): try: iterable = func() except Exception as e: logger.exception(f"Generating failed ({func.__name__}): {str(e)}") ds.event_logger.log_exception(e, run_config=run_config) raise e while True: with tracer.start_as_current_span("get next batch"): try: chunk_dfs = next(iterable) if isinstance(chunk_dfs, pd.DataFrame): chunk_dfs = [chunk_dfs] except StopIteration: if empty_generator: for k, dt_k in enumerate(output_dts): dt_k.event_logger.log_state( dt_k.name, added_count=0, updated_count=0, deleted_count=0, processed_count=0, run_config=run_config, ) break except Exception as e: logger.exception(f"Generating failed ({func}): {str(e)}") ds.event_logger.log_exception(e, run_config=run_config) # raise e return empty_generator = False with tracer.start_as_current_span("store results"): for k, dt_k in enumerate(output_dts): dt_k.store_chunk(chunk_dfs[k], run_config=run_config) with tracer.start_as_current_span("delete stale rows"): for k, dt_k in enumerate(output_dts): dt_k.delete_stale_by_process_ts(now, run_config=run_config) @dataclass class BatchGenerate(PipelineStep): func: BatchGenerateFunc outputs: List[str] def build_compute(self, ds: DataStore, catalog: Catalog) -> List[ComputeStep]: def transform_func(ds, input_dts, output_dts, run_config): return do_batch_generate(self.func, ds, output_dts, run_config) return [ DatatableTransformStep( name=self.func.__name__, func=transform_func, input_dts=[], output_dts=[catalog.get_datatable(ds, name) for name in self.outputs], check_for_changes=False ) ] def update_external_table(ds: DataStore, table: DataTable, run_config: RunConfig = None) -> None: now = time.time() for ps_df in tqdm.tqdm(table.table_store.read_rows_meta_pseudo_df(run_config=run_config)): ( new_df, changed_df, new_meta_df, changed_meta_df ) = table.meta_table.get_changes_for_store_chunk(ps_df, now=now) ds.event_logger.log_state( table.name, added_count=len(new_df), updated_count=len(changed_df), deleted_count=0, processed_count=len(ps_df), run_config=run_config, ) # TODO switch to iterative store_chunk and table.sync_meta_by_process_ts table.meta_table.insert_meta_for_store_chunk(new_meta_df) table.meta_table.update_meta_for_store_chunk(changed_meta_df) for stale_idx in table.meta_table.get_stale_idx(now, run_config=run_config): logger.debug(f'Deleting {len(stale_idx.index)} rows from {table.name} data') table.event_logger.log_state( table.name, added_count=0, updated_count=0, deleted_count=len(stale_idx), processed_count=len(stale_idx), run_config=run_config, ) table.meta_table.mark_rows_deleted(stale_idx, now=now) class UpdateExternalTable(PipelineStep): def __init__(self, output: str) -> None: self.output_table_name = output def build_compute(self, ds: DataStore, catalog: Catalog) -> List[ComputeStep]: def transform_func(ds, input_dts, output_dts, run_config): return update_external_table(ds, output_dts[0], run_config) return [ DatatableTransformStep( name=f'update_{self.output_table_name}', func=transform_func, input_dts=[], output_dts=[catalog.get_datatable(ds, self.output_table_name)], ) ]
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ic_import_contacts = void 0; var ic_import_contacts = { "viewBox": "0 0 24 24", "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "rect", "attribs": { "fill": "none", "height": "24", "width": "24" }, "children": [{ "name": "rect", "attribs": { "fill": "none", "height": "24", "width": "24" }, "children": [] }] }] }, { "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "path", "attribs": { "d": "M17.5,4.5c-1.95,0-4.05,0.4-5.5,1.5c-1.45-1.1-3.55-1.5-5.5-1.5S2.45,4.9,1,6v14.65c0,0.65,0.73,0.45,0.75,0.45 C3.1,20.45,5.05,20,6.5,20c1.95,0,4.05,0.4,5.5,1.5c1.35-0.85,3.8-1.5,5.5-1.5c1.65,0,3.35,0.3,4.75,1.05 C22.66,21.26,23,20.86,23,20.6V6C21.51,4.88,19.37,4.5,17.5,4.5z M21,18.5c-1.1-0.35-2.3-0.5-3.5-0.5c-1.7,0-4.15,0.65-5.5,1.5V8 c1.35-0.85,3.8-1.5,5.5-1.5c1.2,0,2.4,0.15,3.5,0.5V18.5z" }, "children": [{ "name": "path", "attribs": { "d": "M17.5,4.5c-1.95,0-4.05,0.4-5.5,1.5c-1.45-1.1-3.55-1.5-5.5-1.5S2.45,4.9,1,6v14.65c0,0.65,0.73,0.45,0.75,0.45 C3.1,20.45,5.05,20,6.5,20c1.95,0,4.05,0.4,5.5,1.5c1.35-0.85,3.8-1.5,5.5-1.5c1.65,0,3.35,0.3,4.75,1.05 C22.66,21.26,23,20.86,23,20.6V6C21.51,4.88,19.37,4.5,17.5,4.5z M21,18.5c-1.1-0.35-2.3-0.5-3.5-0.5c-1.7,0-4.15,0.65-5.5,1.5V8 c1.35-0.85,3.8-1.5,5.5-1.5c1.2,0,2.4,0.15,3.5,0.5V18.5z" }, "children": [] }] }] }] }] }] }] }] }; exports.ic_import_contacts = ic_import_contacts;
def cipher_alphabet(message): output = "" for letter in message: if(letter == 'z'): output += 'a' else: output += chr(ord(letter) + 1) return output message = input("Enter a message to encrypt: ") encryptedMessage = cipher_alphabet(message) print("Encrypted Message: {}".format(encryptedMessage))
def maxProduct(arr): maxProduct = -(float("inf")) for i in range(len(arr)-1): product = arr[i] * arr[i+1] if product > maxProduct: maxProduct = product return maxProduct
package malte0811.controlengineering.datagen.recipes; import net.minecraft.advancements.CriterionTriggerInstance; import net.minecraft.advancements.critereon.ImpossibleTrigger; import net.minecraft.data.recipes.FinishedRecipe; import net.minecraft.data.recipes.ShapedRecipeBuilder; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.ItemLike; import net.minecraftforge.registries.RegistryObject; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.function.Consumer; public class NoAdvancementShapedBuilder extends ShapedRecipeBuilder { @Nullable private final CompoundTag nbt; public NoAdvancementShapedBuilder(ItemLike pResult, int pCount, @Nullable CompoundTag nbt) { super(pResult, pCount); this.nbt = nbt; } public static NoAdvancementShapedBuilder shaped(ItemStack result) { return new NoAdvancementShapedBuilder(result.getItem(), result.getCount(), result.getTag()); } public static NoAdvancementShapedBuilder shaped(ItemLike result) { return shaped(result, 1); } public static NoAdvancementShapedBuilder shaped(RegistryObject<? extends ItemLike> regObject) { return shaped(regObject.get()); } public static NoAdvancementShapedBuilder shaped(ItemLike result, int pCount) { return new NoAdvancementShapedBuilder(result, pCount, null); } public static NoAdvancementShapedBuilder shaped(RegistryObject<? extends ItemLike> regObject, int count) { return shaped(regObject.get(), count); } public NoAdvancementShapedBuilder define(char symbol, RegistryObject<? extends ItemLike> item) { define(symbol, item.get()); return this; } @Nonnull public NoAdvancementShapedBuilder define(@Nonnull Character symbol, @Nonnull TagKey<Item> tag) { super.define(symbol, tag); return this; } @Nonnull public NoAdvancementShapedBuilder pattern(@Nonnull String pattern) { super.pattern(pattern); return this; } @Nonnull public NoAdvancementShapedBuilder define(@Nonnull Character symbol, @Nonnull ItemLike item) { super.define(symbol, item); return this; } @Nonnull @Override public ShapedRecipeBuilder unlockedBy( @Nonnull String pCriterionName, @Nonnull CriterionTriggerInstance pCriterionTrigger ) { throw new UnsupportedOperationException(); } @Override public void save(@Nonnull Consumer<FinishedRecipe> out, @Nonnull ResourceLocation recipeId) { super.unlockedBy("dummy", new ImpossibleTrigger.TriggerInstance()); super.save( recipe -> out.accept(new NoAdvancementFinishedRecipe(recipe, nbt)), recipeId ); } }
const request = require('request'); const generator = (data, templateName, done) => { const report_data = { template: { name: templateName }, data, options: { reports: { save: true, public: true } } } const options = { headers: { 'Authorization': 'Basic YWRtaW46YWRtaW4xMjM=', 'Content-Type': 'application/json' }, uri: 'http://localhost:8001/api/report', method: 'POST', json: report_data } request(options, (err, res) => { if (err) { console.log("Error : ", err); done(err); } else { done(null,res); } }); } module.exports = generator;
package container import ( "context" "errors" "testing" "github.com/google/go-containerregistry/pkg/name" "github.com/matthogan/zc/cmd/cn/cli/options" ociremote "github.com/matthogan/zc/pkg/oci/remote" ) type RemoteMock struct{} var resolveDigestMock func(ref name.Reference, opts ...ociremote.Option) (*name.Digest, error) func (d *RemoteMock) ResolveDigest(ref name.Reference, opts ...ociremote.Option) (*name.Digest, error) { return resolveDigestMock(ref, opts...) } func TestDigest_GetDigestFromRegistry(t *testing.T) { remote = &RemoteMock{} d, err := name.NewDigest("image@sha256:0cae3cc26f4f6cf6d57d51239545bf46212bfed24a2d9df9a581a6b47ec6f532", name.WithDefaultRegistry("x.io")) if err != nil { t.Errorf("unexpected error %d", err) } resolveDigestMock = func(ref name.Reference, opts ...ociremote.Option) (*name.Digest, error) { return &d, nil } sut := Digest{} imageRef := "image:latest" regOpts := &options.RegistryOptions{} actual, err := sut.GetDigestFromRegistry(context.Background(), regOpts, imageRef) if err != nil { t.Errorf("unexpected error %d", err) } if actual.DigestStr() != d.DigestStr() { t.Fatalf("expected \"%s\" got \"%s\"", d.DigestStr(), actual.DigestStr()) } } func TestDigest_GetDigestFromRegistry_Error(t *testing.T) { remote = &RemoteMock{} resolveDigestMock = func(ref name.Reference, opts ...ociremote.Option) (*name.Digest, error) { return nil, errors.New("error") } sut := Digest{} imageRef := "image:latest" regOpts := &options.RegistryOptions{} if _, err := sut.GetDigestFromRegistry(context.Background(), regOpts, imageRef); err == nil { t.Errorf("expected error %s", "error") } }
#!/bin/sh # # This is an example of a script to run a "secure" TURN UDP client # with short-term credential mechanism. # # Options: # # 1) -t is absent, it means that UDP networking is used. # 5) -n 1000 means 1000 messages per single emulated client. Messages # are sent with interval of 20 milliseconds, to emulate an RTP stream. # 6) -m 10 means that 10 clients are emulated. # 7) -l 170 means that the payload size of the packets is 170 bytes # (like average audio RTP packet). # 8) -e 127.0.0.1 means that the clients will use peer address 127.0.0.1. # 9) -g means "set DONT_FRAGMENT parameter in TURN requests". # 10) -A means that the short-term credentials mechanism is used. # 11) -u ninefingers sets the client user name. # 12) -w youhavetoberealistic sets the password for the user account as "youhavetoberealistic". # 13) -s option means that the client will be using "send" indication for data trasfer. # 14) ::1 (the last parameter) is the TURN Server IP address. We use IPv6 here # to illustrate how the TURN Server convert the traffic from IPv6 to IPv4 and back. # if [ -d examples ] ; then cd examples fi export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/lib/ PATH=examples/bin/:../bin/:./bin/:${PATH} turnutils_uclient -n 1000 -m 10 -l 170 -e 127.0.0.1 -X -g -A -u ninefingers -w youhavetoberealistic -s $@ ::1
/* * Copyright (C) 2020 The Dagger Authors. * * 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 dagger.hilt.android; import android.app.Activity; import android.content.Context; import androidx.fragment.app.Fragment; import android.view.View; import dagger.hilt.EntryPoints; import javax.annotation.Nonnull; /** Static utility methods for dealing with entry points for standard Android components. */ public final class EntryPointAccessors { /** * Returns the entry point interface from an application. The context can be any context derived * from the application context. May only be used with entry point interfaces installed in the * ApplicationComponent. */ @Nonnull public static <T> T fromApplication(Context context, Class<T> entryPoint) { return EntryPoints.get(context.getApplicationContext(), entryPoint); } /** * Returns the entry point interface from an activity. May only be used with entry point * interfaces installed in the ActivityComponent. */ @Nonnull public static <T> T fromActivity(Activity activity, Class<T> entryPoint) { return EntryPoints.get(activity, entryPoint); } /** * Returns the entry point interface from a fragment. May only be used with entry point interfaces * installed in the FragmentComponent. */ @Nonnull public static <T> T fromFragment(Fragment fragment, Class<T> entryPoint) { return EntryPoints.get(fragment, entryPoint); } /** * Returns the entry point interface from a view. May only be used with entry point interfaces * installed in the ViewComponent or ViewNoFragmentComponent. */ @Nonnull public static <T> T fromView(View view, Class<T> entryPoint) { return EntryPoints.get(view, entryPoint); } private EntryPointAccessors() {} }
import { GameObject } from '../../core'; import { GameUpdateArgs, Session } from '../../game'; import { MainHeading, Menu, SpriteText, TextMenuItem } from '../../gameObjects'; import { MenuInputContext } from '../../input'; import { PointsHighscoreManager } from '../../points'; import * as config from '../../config'; import { GameScene } from '../GameScene'; import { GameSceneType } from '../GameSceneType'; const SLIDE_SPEED = 240; enum State { Sliding, Ready, } export class MainMenuScene extends GameScene { private group: GameObject; private heading: MainHeading; private primaryPoints: SpriteText; private secondaryPoints: SpriteText; private commonHighscore: SpriteText; private menu: Menu; private singlePlayerItem: TextMenuItem; private multiPlayerItem: TextMenuItem; private modesItem: TextMenuItem; private editorItem: TextMenuItem; private settingsItem: TextMenuItem; private aboutItem: TextMenuItem; private state: State = State.Ready; private session: Session; private pointsHighscoreManager: PointsHighscoreManager; protected setup({ mapLoader, pointsHighscoreManager, session, }: GameUpdateArgs): void { this.session = session; this.pointsHighscoreManager = pointsHighscoreManager; // Restore source for maps to default mapLoader.restoreDefaultReader(); this.group = new GameObject(); this.group.size.copyFrom(this.root.size); this.primaryPoints = new SpriteText(this.getPrimaryPointsText(), { color: config.COLOR_WHITE, }); this.primaryPoints.position.set(92, 64); this.group.add(this.primaryPoints); this.secondaryPoints = new SpriteText(this.getSecondaryPointsText(), { color: config.COLOR_WHITE, }); this.secondaryPoints.position.set(704, 64); if (session.secondaryPlayer.wasInLastGame()) { this.group.add(this.secondaryPoints); } this.commonHighscore = new SpriteText(this.getCommonHighscoreText(), { color: config.COLOR_WHITE, }); this.commonHighscore.position.set(380, 64); this.group.add(this.commonHighscore); this.heading = new MainHeading(); this.heading.origin.setX(0.5); this.heading.setCenter(this.root.getSelfCenter()); this.heading.position.setY(160); this.group.add(this.heading); this.singlePlayerItem = new TextMenuItem('1 PLAYER'); this.singlePlayerItem.selected.addListener(this.handleSinglePlayerSelected); this.multiPlayerItem = new TextMenuItem('2 PLAYERS'); this.multiPlayerItem.selected.addListener(this.handleMultiPlayerSelected); this.modesItem = new TextMenuItem('MODES'); this.modesItem.selected.addListener(this.handleModesSelected); this.editorItem = new TextMenuItem('CONSTRUCTION'); this.editorItem.selected.addListener(this.handleEditorSelected); this.settingsItem = new TextMenuItem('SETTINGS'); this.settingsItem.selected.addListener(this.handleSettingsSelected); this.aboutItem = new TextMenuItem('ABOUT'); this.aboutItem.selected.addListener(this.handleAboutSelected); const menuItems = [ this.singlePlayerItem, this.multiPlayerItem, this.modesItem, this.editorItem, this.settingsItem, this.aboutItem, ]; this.menu = new Menu(); this.menu.setItems(menuItems); this.menu.setCenter(this.root.getSelfCenter()); this.menu.position.setY(490); this.group.add(this.menu); if (!this.session.haveSeenIntro()) { this.state = State.Sliding; this.group.position.setY(this.root.size.height); this.menu.hideCursor(); } this.root.add(this.group); } protected update(updateArgs: GameUpdateArgs): void { const { deltaTime, inputManager } = updateArgs; const inputMethod = inputManager.getActiveMethod(); if (this.state === State.Sliding) { let nextPosition = this.group.position.y - SLIDE_SPEED * deltaTime; if (nextPosition <= 0) { nextPosition = 0; } const isSkipped = inputMethod.isDownAny(MenuInputContext.Skip); if (isSkipped) { nextPosition = 0; } const hasReachedTop = nextPosition === 0; this.group.dirtyPaintBox(); this.group.position.setY(nextPosition); this.group.updateMatrix(true); if (hasReachedTop) { this.state = State.Ready; this.menu.showCursor(); this.session.setSeenIntro(true); } else { super.update(updateArgs); } return; } super.update(updateArgs); } private getPrimaryPointsText(): string { const points = this.session.primaryPlayer.getLastGamePoints() || 0; const pointsNumberText = points > 0 ? points.toString() : '00'; const pointsText = pointsNumberText.padStart(6, ' '); const text = `Ⅰ-${pointsText}`; return text; } private getSecondaryPointsText(): string { const points = this.session.secondaryPlayer.getLastGamePoints() || 0; const pointsNumberText = points > 0 ? points.toString() : '00'; const pointsText = pointsNumberText.padStart(6, ' '); const text = `Ⅱ-${pointsText}`; return text; } private getCommonHighscoreText(): string { const points = this.pointsHighscoreManager.getOverallMaxPoints(); const pointsText = points.toString().padStart(6, ' '); const text = `HI-${pointsText}`; return text; } private handleSinglePlayerSelected = (): void => { this.navigator.replace(GameSceneType.LevelSelection); }; private handleMultiPlayerSelected = (): void => { this.session.setMultiplayer(); this.navigator.replace(GameSceneType.LevelSelection); }; private handleModesSelected = (): void => { this.navigator.push(GameSceneType.ModesMenu); }; private handleEditorSelected = (): void => { this.navigator.push(GameSceneType.EditorMenu); }; private handleSettingsSelected = (): void => { this.navigator.push(GameSceneType.SettingsMenu); }; private handleAboutSelected = (): void => { this.navigator.push(GameSceneType.MainAbout); }; }
<reponame>Decipher/druxt.js module.exports = { files: [{ path: './packages/**/dist/*.js', maxSize: '50kb', }], ci: { repoBranchBase: process.env.CI_PULL_REQUEST ? 'develop' : 'main', trackBranches: ['main', 'develop'], } }
<filename>App/app/src/main/java/com/crossover/mobiliza/app/data/remote/service/AppServices.java package com.crossover.mobiliza.app.data.remote.service; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import androidx.core.util.Consumer; import com.crossover.mobiliza.app.AppExecutors; import com.crossover.mobiliza.app.R; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class AppServices { private static final String TAG = AppServices.class.getSimpleName(); private static final Object LOCK = new Object(); private static AppServices sInstance; private Retrofit mRetrofit; public static AppServices getInstance(Context context) { if (sInstance == null) { synchronized (LOCK) { Log.d(TAG, "Creating AppServices instance"); sInstance = new AppServices(context.getApplicationContext()); } } return sInstance; } private AppServices(Context context) { mRetrofit = new Retrofit.Builder() .baseUrl(context.getString(R.string.api_base_url)) .addConverterFactory(GsonConverterFactory.create()) .build(); } public <TService> TService createService(Class<TService> serviceClass) { return mRetrofit.create(serviceClass); } public static <T> void runCallAsync(final Call<T> call, final Consumer<T> onSuccess, final Consumer<String> onFailure) { AppExecutors.getInstance().network().execute(() -> { call.enqueue(new Callback<T>() { @Override public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) { if (response.isSuccessful()) { onSuccess.accept(response.body()); } else { try { String resp = response.errorBody().string(); JSONObject json = new JSONObject(resp); String msg = json.getString("message"); Log.e(TAG, msg); onFailure.accept(msg); } catch (IOException | JSONException e) { e.printStackTrace(); onFailure.accept(response.message()); } } } @Override public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) { onFailure.accept(t.getMessage()); } }); }); } }
#!/usr/bin/env bash cd "$(dirname $0)/.." name=$(basename $0) base_name=${name%.*} name="${base_name}" CUDA_VISIBLE_DEVICES=0 python run.py --name $name --dataset cifar10 --arc dcgan\ --generator_adversarial_objective hinge --discriminator_adversarial_objective hinge\ --discriminator_filters 512 --generator_filters 512\ --discriminator_spectral 1\ --generator_block_norm d --generator_block_coloring uconv --generator_last_norm d --generator_last_coloring uconv\ --g_decomposition iter_norm --g_iter_num 5 --g_whitten_m 0 --g_coloring_m 0 --g_instance_norm 0\ --discriminator_norm n --discriminator_coloring n\ --d_decomposition iter_norm --d_iter_num 5 --d_whitten_m 0 --d_coloring_m 0 --d_instance_norm 0\ --gradient_penalty_weight 0\ --lr_decay_schedule linear --generator_lr 2e-4 --discriminator_lr 2e-4 \ --beta1 0 --beta2 0.9\ --number_of_epochs 100 --batch_size 64\ --training_ratio 1 --generator_batch_multiple 1 \
arr_1 = [1, 2, 3] arr_2 = [0, 1, 5] # loop through the two arrays for i in range(len(arr_1)): diff = arr_1[i] - arr_2[i] # print the difference print("Difference between " + str(arr_1[i]) + " and " + str(arr_2[i]) + " is " + str(diff))