text
stringlengths
1
1.05M
class MinHeap: def __init__(self): self.heap = [] def _heapify(self, index): smallest = index left = 2 * index + 1 right = 2 * index + 2 if left < len(self.heap) and self.heap[left] < self.heap[smallest]: smallest = left if right < len(self.heap) and self.heap[right] < self.heap[smallest]: smallest = right if smallest != index: self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index] self._heapify(smallest) def insert(self, value): self.heap.append(value) index = len(self.heap) - 1 while index > 0: parent = (index - 1) // 2 if self.heap[parent] > self.heap[index]: self.heap[parent], self.heap[index] = self.heap[index], self.heap[parent] index = parent else: break # Example usage min_heap = MinHeap() min_heap.insert(5) min_heap.insert(3) min_heap.insert(8) print(min_heap.heap) # Output: [3, 5, 8]
<gh_stars>0 import fs from 'fs'; import {buildComponentTests} from './_auto-render'; const componentsToLoad = ['icon', 'toolbar', 'card', 'panel']; componentsToLoad.forEach(c => { const componentsProps = require(`../../fixtures/${c}`); const files = fs.readdirSync(`${__dirname}/../../../src/app/components/${c}/`).map(f => f.substring(0, f.length - 4)); const components = files.map(f => require(`app/components/${c}/${f}`)); components.forEach(c => buildComponentTests(c, componentsProps)); });
import gulp from 'gulp'; import { join } from 'path'; import loadPlugins from 'gulp-load-plugins'; import { src, dest } from '../config'; const p = loadPlugins(); /** * This task has the function of only copying what doesn't require any treatment */ gulp.task('dist:copy', ['dist:copy:markup'], function() { var copyRootFiles = gulp.src([join(src, 'html', '*.{xml,json,webapp,txt}')], { dot: true }) .pipe(gulp.dest(dest)) .pipe(p.size({ title: 'DIST COPY :' })); return copyRootFiles; }); gulp.task('dist:copy:markup', function() { var copyRootFiles = gulp.src(join(src, 'html', 'index.html'), { dot: true }) .pipe(gulp.dest(join(dest, 'html'))) .pipe(p.size({ title: 'DIST COPY :' })); return copyRootFiles; });
#!/usr/bin/env python3 import algorithms bag = algorithms.NodeBag(89) bag.printBag()
def sum_even_numbers(nums): total = 0 for num in nums: if num % 2 == 0: total += num return total result = sum_even_numbers([3, 9, 12, 5]) print(result)
<gh_stars>0 /* * Copyright [2020-2030] [https://www.stylefeng.cn] * * 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. * * Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点: * * 1.请不要删除和修改根目录下的LICENSE文件。 * 2.请不要删除和修改Guns源码头部的版权声明。 * 3.请保留源码和相关描述文件的项目出处,作者声明等。 * 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns * 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns * 6.若您的项目无法满足以上几点,可申请商业授权 */ package cn.stylefeng.roses.kernel.auth.api.expander; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import cn.stylefeng.roses.kernel.config.api.context.ConfigContext; import java.util.ArrayList; import java.util.List; import static cn.stylefeng.roses.kernel.auth.api.constants.AuthConstants.*; /** * 权限相关配置快速获取 * * @author fengshuonan * @date 2020/10/17 16:10 */ public class AuthConfigExpander { /** * 获取不被权限控制的url * * @author fengshuonan * @date 2020/10/17 16:12 */ public static List<String> getNoneSecurityConfig() { String noneSecurityUrls = ConfigContext.me().getSysConfigValueWithDefault("SYS_NONE_SECURITY_URLS", String.class, ""); if (StrUtil.isEmpty(noneSecurityUrls)) { return new ArrayList<>(); } else { return StrUtil.split(noneSecurityUrls, ','); } } /** * 用于auth校验的jwt的秘钥 * * @author fengshuonan * @date 2021/1/2 18:52 */ public static String getAuthJwtSecret() { String sysJwtSecret = ConfigContext.me().getConfigValueNullable("SYS_AUTH_JWT_SECRET", String.class); // 没配置就返回一个随机密码 if (sysJwtSecret == null) { return RandomUtil.randomString(20); } else { return sysJwtSecret; } } /** * 用于auth模块权限校验的jwt失效时间 * <p> * 这个时间也是“记住我”功能的过期时间,默认为7天 * <p> * 如果登录的时候开启了“记住我”,则用户7天内免登录 * * @author fengshuonan * @date 2021/1/2 18:53 */ public static Long getAuthJwtTimeoutSeconds() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_JWT_TIMEOUT_SECONDS", Long.class, DEFAULT_AUTH_JWT_TIMEOUT_SECONDS); } /** * 获取session过期时间,默认3600秒 * <p> * 在这个时段内不操作,会将用户踢下线,从新登陆 * <p> * 如果开启了记住我功能,在session过期后会从新创建session * * @author fengshuonan * @date 2020/10/20 9:32 */ public static Long getSessionExpiredSeconds() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_SESSION_EXPIRED_SECONDS", Long.class, 3600L); } /** * 获取单账号单端登录的开关 * <p> * 单账号单端登录为限制一个账号多个浏览器登录 * * @return true-开启单端限制,false-关闭单端限制 * @author fengshuonan * @date 2020/10/21 14:31 */ public static boolean getSingleAccountLoginFlag() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_SINGLE_ACCOUNT_LOGIN_FLAG", Boolean.class, false); } /** * 获取携带token的header头的名称 * * @author fengshuonan * @date 2020/10/22 14:11 */ public static String getAuthTokenHeaderName() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_HEADER_NAME", String.class, DEFAULT_AUTH_HEADER_NAME); } /** * 获取携带token的param传参的名称 * * @author fengshuonan * @date 2020/10/22 14:11 */ public static String getAuthTokenParamName() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_PARAM_NAME", String.class, DEFAULT_AUTH_PARAM_NAME); } /** * 会话保存在cookie中时,cooke的name * * @author fengshuonan * @date 2020/12/27 13:18 */ public static String getSessionCookieName() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_SESSION_COOKIE_NAME", String.class, DEFAULT_AUTH_HEADER_NAME); } /** * 默认解析jwt的秘钥(用于解析sso传过来的token) * * @author fengshuonan * @date 2021/5/25 22:39 */ public static String getSsoJwtSecret() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_JWT_SECRET", String.class, SYS_AUTH_SSO_JWT_SECRET); } /** * 默认解析sso加密的数据的秘钥 * * @author fengshuonan * @date 2021/5/25 22:39 */ public static String getSsoDataDecryptSecret() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_DECRYPT_DATA_SECRET", String.class, SYS_AUTH_SSO_DECRYPT_DATA_SECRET); } /** * 获取是否开启sso远程会话校验,当系统对接sso后,如需同时校验sso的会话是否存在则开启此开关 * * @return true-开启远程校验,false-关闭远程校验 * @author fengshuonan * @date 2021/5/25 22:39 */ public static Boolean getSsoSessionValidateSwitch() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_SESSION_VALIDATE_SWITCH", Boolean.class, SYS_AUTH_SSO_SESSION_VALIDATE_SWITCH); } /** * sso会话远程校验,redis的host * * @author fengshuonan * @date 2021/5/25 22:39 */ public static String getSsoSessionValidateRedisHost() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_HOST", String.class, SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_HOST); } /** * sso会话远程校验,redis的端口 * * @author fengshuonan * @date 2021/5/25 22:39 */ public static Integer getSsoSessionValidateRedisPort() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_PORT", Integer.class, SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_PORT); } /** * sso会话远程校验,redis的密码 * * @author fengshuonan * @date 2021/5/25 22:39 */ public static String getSsoSessionValidateRedisPassword() { return ConfigContext.me().getConfigValueNullable("SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_PASSWORD", String.class); } /** * sso会话远程校验,redis的db * * @author fengshuonan * @date 2021/5/25 22:39 */ public static Integer getSsoSessionValidateRedisDbIndex() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_DB_INDEX", Integer.class, SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_DB_INDEX); } /** * sso会话远程校验,redis的缓存前缀 * * @author fengshuonan * @date 2021/5/25 22:39 */ public static String getSsoSessionValidateRedisCachePrefix() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_CACHE_PREFIX", String.class, SYS_AUTH_SSO_SESSION_VALIDATE_REDIS_CACHE_PREFIX); } /** * 获取SSO服务器的地址 * * @author fengshuonan * @date 2021/5/25 22:39 */ public static String getSsoUrl() { return ConfigContext.me().getSysConfigValueWithDefault("SYS_AUTH_SSO_HOST", String.class, SYS_AUTH_SSO_HOST); } }
<filename>MSDaPl_Web_App/WebRoot/js/comparison.js // --------------------------------------------------------------------------------------- // AJAX DEFAULTS // --------------------------------------------------------------------------------------- $.ajaxSetup({ type: 'POST', //timeout: 5000, dataType: 'html', error: function(xhr) { var statusCode = xhr.status; // status code returned if user is not logged in // reloading this page will redirect to the login page if(statusCode == 303) window.location.reload(); // otherwise just display an alert else { alert("Request Failed: "+statusCode+"\n"+xhr.statusText); } } }); $.blockUI.defaults.message = '<b>Loading...</b>'; $.blockUI.defaults.css.padding = 20; $.blockUI.defaults.fadeIn = 0; $.blockUI.defaults.fadeOut = 0; $().ajaxStop($.unblockUI); // --------------------------------------------------------------------------------------- // PAGE RESULTS // --------------------------------------------------------------------------------------- function pageResults(pageNum) { var actionId = $("#actionOptions").val(); if(actionId == 3 || actionId == 4) { alert("Cannot page results if the selected action is GO Analysis"); return false; } $("input#pageNum").val(pageNum); $("input#download").val("false"); //alert("setting to "+pageNum+" value set to: "+$("input#pageNum").val()); $("form[name='proteinSetComparisonForm']").submit(); } //--------------------------------------------------------------------------------------- //NAVIGATE TO RELEVANT PAGE //--------------------------------------------------------------------------------------- function goToHeatMapIndex(index) { var numPerPage = $("input#numPerPage").val(); var newPage = Math.ceil(index / numPerPage); $("input#rowIndex").val(index); pageResults(newPage); } // --------------------------------------------------------------------------------------- // SORT RESULTS // --------------------------------------------------------------------------------------- function sortResults(sortBy, sortOrder) { var actionId = $("#actionOptions").val(); if(actionId == 3 || actionId == 4) { alert("Cannot sort results if the selected action is GO Analysis"); return false; } if(actionId == 2) { alert("Cannot sort results if the selected action is \"Cluster Spectrum Counts\""); return false; } $("input#pageNum").val(1); $("input#download").val("false"); $("input#sortBy").val(sortBy); $("input#sortOrder").val(sortOrder); $("form[name='proteinSetComparisonForm']").attr('target', ''); $("form[name='proteinSetComparisonForm']").submit(); } // --------------------------------------------------------------------------------------- // UPDATE RESULTS // --------------------------------------------------------------------------------------- function updateResults() { $("input#download").val("false"); var actionId = $("#actionOptions").val(); if(actionId == 3) { // GO Analysis submitFormForGoSlimAnalysis(); return false; } else if(actionId == 4) { // GO Enrichment submitFormForGoEnrichmentAnalysis(); return false; } else { //alert("Updating"); $("input#pageNum").val(1); $("input#numPerPage").val($("input#pager_result_count").val()); //alert("setting result count to: "+$("input#numPerPage").val()); $("form[name='proteinSetComparisonForm']").attr('target', ''); $("form[name='proteinSetComparisonForm']").submit(); } } function toggleGoSlimDetails() { fold($("#goslim_fold")); } function hideGoSlimDetails() { foldClose($("#goslim_fold")); } function toggleGoEnrichmentDetails() { fold($("#goenrich_fold")); } function hideGoEnrichmentDetails() { foldClose($("#goenrich_fold")); } // --------------------------------------------------------------------------------------- // DOWNLOAD RESULTS // --------------------------------------------------------------------------------------- function downloadResults() { var actionId = $("#actionOptions").val(); if(actionId == 3 || actionId == 4) { alert("GO Analysis results cannot be downloaded"); return false; } $("input#download").val("true"); $("form[name='proteinSetComparisonForm']").attr('target', '_blank'); $("form[name='proteinSetComparisonForm']").submit(); } // --------------------------------------------------------------------------------------- // TOGGLE AND, OR, NOT FILTERS // --------------------------------------------------------------------------------------- function toggleAndSelect(dsIndex, red, green, blue) { var id = "AND_"+dsIndex+"_select"; var value = $("input#"+id).val(); if(value == "true") { $("input#"+id).val("false"); $("td#AND_"+dsIndex+"_td").css("background-color", "#FFFFFF"); } else { var color = "rgb("+red+","+green+","+blue+")"; $("input#"+id).val("true"); $("td#AND_"+dsIndex+"_td").css("background-color", color); } } function toggleOrSelect(dsIndex, red, green, blue) { var id = "OR_"+dsIndex+"_select"; var value = $("input#"+id).val(); if(value == "true") { $("input#"+id).val("false"); $("td#OR_"+dsIndex+"_td").css("background-color", "#FFFFFF"); } else { var color = "rgb("+red+","+green+","+blue+")"; $("input#"+id).val("true"); $("td#OR_"+dsIndex+"_td").css("background-color", color); } } function toggleNotSelect(dsIndex, red, green, blue) { var id = "NOT_"+dsIndex+"_select"; var value = $("input#"+id).val(); if(value == "true") { $("input#"+id).val("false"); $("td#NOT_"+dsIndex+"_td").css("background-color", "#FFFFFF"); } else { var color = "rgb("+red+","+green+","+blue+")"; $("input#"+id).val("true"); $("td#NOT_"+dsIndex+"_td").css("background-color", color); } } function toggleXorSelect(dsIndex, red, green, blue) { var id = "XOR_"+dsIndex+"_select"; var value = $("input#"+id).val(); if(value == "true") { $("input#"+id).val("false"); $("td#XOR_"+dsIndex+"_td").css("background-color", "#FFFFFF"); } else { var color = "rgb("+red+","+green+","+blue+")"; $("input#"+id).val("true"); $("td#XOR_"+dsIndex+"_td").css("background-color", color); } } // --------------------------------------------------------------------------------------- // TOGGLE FULL PROTEIN NAMES // --------------------------------------------------------------------------------------- function toggleFullNames() { if($("#full_names").text() == "[Full Names]") { $("#full_names").text("[Short Names]"); $(".full_name").show(); $(".short_name").hide(); } else if($("#full_names").text() == "[Short Names]") { $("#full_names").text("[Full Names]"); $(".full_name").hide(); $(".short_name").show(); } } // --------------------------------------------------------------------------------------- // TOGGLE FULL PROTEIN DESCRIPTIONS // --------------------------------------------------------------------------------------- function toggleFullDescriptions() { if($("#full_descriptions").text() == "[Full Descriptions]") { $("#full_descriptions").text("[Short Descriptions]"); $(".full_description").show(); $(".short_description").hide(); } else if($("#full_descriptions").text() == "[Short Descriptions]") { $("#full_descriptions").text("[Full Descriptions]"); $(".full_description").hide(); $(".short_description").show(); } } function showAllDescriptionsForProtein(nrseqId) { $("#short_desc_"+nrseqId).hide(); $("#full_desc_"+nrseqId).show(); } function hideAllDescriptionsForProtein(nrseqId) { $("#short_desc_"+nrseqId).show(); $("#full_desc_"+nrseqId).hide(); } //--------------------------------------------------------------------------------------- //TOGGLE DATASET NAME / ID IN THE COMPARISON TABLE HEADER //--------------------------------------------------------------------------------------- function toggleDatasetNameId() { var text = $("#headerValueChooser").text(); //alert(text); if(text == "[Show Dataset IDs]") { $("#headerValueChooser").text("[Show Dataset Names]"); $("span.dsid").show(); $("span.dsname").hide(); } else { $("#headerValueChooser").text("[Show Dataset IDs]"); $("span.dsname").show(); $("span.dsid").hide(); } }
#include <algorithm> void sortArray(int arr[], int len) { std::sort(arr, arr + len); }
package com.marcus.reactnative.lib.task; import com.marcus.reactnative.lib.base.MMErrorCode; /*! * Copyright(c) 2009-2017 <NAME> * E-mail:<EMAIL> * GitHub : https://github.com/MarcusMa * MIT Licensed */ class CommonTaskResult { private int errorCode; private String errorMessage; private Object data; protected int getErrorCode() { return errorCode; } protected void setErrorCode(int errorCode) { this.errorCode = errorCode; } protected String getErrorMessage() { return errorMessage; } protected void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } protected Object getData() { return data; } protected void setData(Object data) { this.data = data; } /* Build Method For A Successful Result */ protected static final CommonTaskResult build() { CommonTaskResult result = new CommonTaskResult(); result.setErrorCode(MMErrorCode.SUCCESS); result.setErrorMessage(""); return result; } }
#!/usr/bin/bash -e if [ $# -lt 1 ] || ! [ -f "$1" ]; then echo Missing job file exit 1 fi if [ "$2" == "--rm" ]; then CLEAN=true shift fi JOB_FILE="$1.tmp" cp "$1" $JOB_FILE shift for named_arg in $@; do NAME=$(echo $named_arg | cut -d= -f1) ARG=$(echo $named_arg | cut -d= -f2) sed -i "s/\$$NAME/$ARG/g" $JOB_FILE done condor_submit $JOB_FILE condor_q if [ "$CLEAN" ]; then rm $JOB_FILE fi
<reponame>Ashindustry007/competitive-programming // https://www.codechef.com/FEB18/problems/CHEFPTNT #include <algorithm> #include <iostream> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m, x, k; cin >> n >> m >> x >> k; string s; cin >> s; int e = count(s.begin(), s.end(), 'E'); int o = s.size() - e; int sum = min(m / 2 * x, e) + min((m + 1) / 2 * x, o); cout << (sum >= n ? "yes\n" : "no\n"); } }
<reponame>soarqin/blitzd #include "Mutex_POSIX.h" #include "Timestamp.h" #include <sys/select.h> #include <unistd.h> #include <sys/time.h> #if defined(_POSIX_TIMEOUTS) && (_POSIX_TIMEOUTS - 200112L) >= 0L #if defined(_POSIX_THREADS) && (_POSIX_THREADS - 200112L) >= 0L #define HAVE_MUTEX_TIMEOUT #endif #endif namespace Utils { MutexImpl::MutexImpl() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); #if defined(PTHREAD_MUTEX_RECURSIVE_NP) pthread_mutexattr_settype_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP); #else pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); #endif if (pthread_mutex_init(&_mutex, &attr)) { pthread_mutexattr_destroy(&attr); throw ("cannot create mutex"); } pthread_mutexattr_destroy(&attr); } MutexImpl::MutexImpl(bool fast) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); #if defined(PTHREAD_MUTEX_RECURSIVE_NP) pthread_mutexattr_settype_np(&attr, fast ? PTHREAD_MUTEX_NORMAL_NP : PTHREAD_MUTEX_RECURSIVE_NP); #else pthread_mutexattr_settype(&attr, fast ? PTHREAD_MUTEX_NORMAL : PTHREAD_MUTEX_RECURSIVE); #endif if (pthread_mutex_init(&_mutex, &attr)) { pthread_mutexattr_destroy(&attr); throw ("cannot create mutex"); } pthread_mutexattr_destroy(&attr); } MutexImpl::~MutexImpl() { pthread_mutex_destroy(&_mutex); } bool MutexImpl::tryLockImpl(long milliseconds) { #if defined(HAVE_MUTEX_TIMEOUT) struct timespec abstime; struct timeval tv; gettimeofday(&tv, NULL); abstime.tv_sec = tv.tv_sec + milliseconds / 1000; abstime.tv_nsec = tv.tv_usec*1000 + (milliseconds % 1000)*1000000; if (abstime.tv_nsec >= 1000000000) { abstime.tv_nsec -= 1000000000; abstime.tv_sec++; } int rc = pthread_mutex_timedlock(&_mutex, &abstime); if (rc == 0) return true; else if (rc == ETIMEDOUT) return false; else throw ("cannot lock mutex"); #else const int sleepMillis = 5; Timestamp now; Timestamp::TimeDiff diff(Timestamp::TimeDiff(milliseconds)*1000); do { int rc = pthread_mutex_trylock(&_mutex); if (rc == 0) return true; else if (rc != EBUSY) throw ("cannot lock mutex"); struct timeval tv; tv.tv_sec = 0; tv.tv_usec = sleepMillis * 1000; select(0, NULL, NULL, NULL, &tv); } while (!now.isElapsed(diff)); return false; #endif } FastMutexImpl::FastMutexImpl(): MutexImpl(true) { } FastMutexImpl::~FastMutexImpl() { } } // namespace Utils
#!/bin/bash function docker_tag_exists() { EXISTS=$(curl -s https://hub.docker.com/v2/repositories/$1/tags/?page_size=10000 | jq -r "[.results | .[] | .name == \"$2\"] | any") test $EXISTS = true } if docker_tag_exists svenruppert/maven-3.1.1-zulu 1.6.93; then echo skip building, image already existing - svenruppert/maven-3.1.1-zulu 1.6.93 else echo start building the images docker build -t svenruppert/maven-3.1.1-zulu . docker tag svenruppert/maven-3.1.1-zulu:latest svenruppert/maven-3.1.1-zulu:1.6.93 docker push svenruppert/maven-3.1.1-zulu:1.6.93 fi docker image rm svenruppert/maven-3.1.1-zulu:latest docker image rm svenruppert/maven-3.1.1-zulu:1.6.93
#!/bin/bash # Keras Tensorflow Backend using tf.keras # Credit: # Script modified from TensoFlow Benchmark repo: # https://github.com/tensorflow/benchmarks/blob/keras-benchmarks/scripts/keras_benchmarks/run_tf_backend.sh python -c "from keras import backend" KERAS_BACKEND=tensorflow sed -i -e 's/"backend":[[:space:]]*"[^"]*/"backend":\ "'$KERAS_BACKEND'/g' ~/.keras/keras.json; echo -e "Running tests with the following config:\n$(cat ~/.keras/keras.json)" # Use "cpu_config", "gpu_config", "4_gpu_config", and "8_gpu_config" as command line arguments to load the right # config file. #models='resnet50 resnet50_tf_keras lstm_synthetic lstm_nietzsche lstm_wikitext2' models='resnet50_tf_keras' dir=`pwd` for name in $models do python $dir/run_benchmark.py --pwd=$dir --mode="$1" --model_name="$name" --dry_run=True --inference="$2" --epochs="$3" done #!/usr/bin/env bash
<filename>Python/Current_Season.py import pandas as pd from Player import Player, s, bran, eli, mal, sab import math import matplotlib.pyplot as plt season = 2022 def player_season_standings(): summary = pd.DataFrame() summary["Year"] = [season] * 4 summary["Player"] = [sab.player_name, mal.player_name, bran.player_name, eli.player_name] summary["Mp"] = [sum(sab.mini_standings()["MP"]), sum(mal.mini_standings()["MP"]), sum(bran.mini_standings()["MP"]), sum(eli.mini_standings()["MP"])] summary["W"] = [sum(sab.mini_standings()["W"]), sum(mal.mini_standings()["W"]), sum(bran.mini_standings()["W"]), sum(eli.mini_standings()["W"])] summary["D"] = [sum(sab.mini_standings()["D"]), sum(mal.mini_standings()["D"]), sum(bran.mini_standings()["D"]), sum(eli.mini_standings()["D"])] summary["L"] = [sum(sab.mini_standings()["L"]), sum(mal.mini_standings()["L"]), sum(bran.mini_standings()["L"]), sum(eli.mini_standings()["L"])] summary["Pts"] = [sum(sab.mini_standings()["Pts"]), sum(mal.mini_standings()["Pts"]), sum(bran.mini_standings()["Pts"]), sum(eli.mini_standings()["Pts"])] summary["Pts/G"] = (summary["Pts"] / summary["Mp"]).round(2) summary["GF"] = [sum(sab.mini_standings()["GF"]), sum(mal.mini_standings()["GF"]), sum(bran.mini_standings()["GF"]), sum(eli.mini_standings()["GF"])] summary["GA"] = [sum(sab.mini_standings()["GA"]), sum(mal.mini_standings()["GA"]), sum(bran.mini_standings()["GA"]), sum(eli.mini_standings()["GA"])] summary["GD"] = [sum(sab.mini_standings()["GD"]), sum(mal.mini_standings()["GD"]), sum(bran.mini_standings()["GD"]), sum(eli.mini_standings()["GD"])] summary = summary.sort_values(["Pts/G","GD"], ascending=False).reset_index(drop=True) return summary def player_season_Xstandings(): xsummary = pd.DataFrame() xsummary["Year"] = [season] * 4 xsummary["Player"] = [sab.player_name, mal.player_name, bran.player_name, eli.player_name] xsummary["Mp"] = [sum(sab.expected_mini_standings()["MP"]), sum(mal.expected_mini_standings()["MP"]), sum(bran.expected_mini_standings()["MP"]), sum(eli.expected_mini_standings()["MP"])] xsummary["xW"] = [sum(sab.expected_mini_standings()["xW"]), sum(mal.expected_mini_standings()["xW"]), sum(bran.expected_mini_standings()["xW"]), sum(eli.expected_mini_standings()["xW"])] xsummary["xD"] = [sum(sab.expected_mini_standings()["xD"]), sum(mal.expected_mini_standings()["xD"]), sum(bran.expected_mini_standings()["xD"]), sum(eli.expected_mini_standings()["xD"])] xsummary["xL"] = [sum(sab.expected_mini_standings()["xL"]), sum(mal.expected_mini_standings()["xL"]), sum(bran.expected_mini_standings()["xL"]), sum(eli.expected_mini_standings()["xL"])] xsummary["xPts"] = [sum(sab.expected_mini_standings()["xPts"]), sum(mal.expected_mini_standings()["xPts"]), sum(bran.expected_mini_standings()["xPts"]), sum(eli.expected_mini_standings()["xPts"])] xsummary["xPts/G"] = (xsummary["xPts"] / xsummary["Mp"]).round(2) xsummary["xGF"] = [sum(sab.expected_mini_standings()["xGF"]), sum(mal.expected_mini_standings()["xGF"]), sum(bran.expected_mini_standings()["xGF"]), sum(eli.expected_mini_standings()["xGF"])] xsummary["xGA"] = [sum(sab.expected_mini_standings()["xGA"]), sum(mal.expected_mini_standings()["xGA"]), sum(bran.expected_mini_standings()["xGA"]), sum(eli.expected_mini_standings()["xGA"])] xsummary["xGD"] = [sum(sab.expected_mini_standings()["xGD"]), sum(mal.expected_mini_standings()["xGD"]), sum(bran.expected_mini_standings()["xGD"]), sum(eli.expected_mini_standings()["xGD"])] xsummary = xsummary.sort_values("xPts/G", ascending=False).reset_index(drop=True) return xsummary def week_by_week_stat(df, stat): selected_columns = [col for col in df.columns if stat in col] selected_columns.insert(0, "Mp") df = df[selected_columns] return df def standings_verse_players(user, opp1, opp2, opp3, win_or_lose="Winner"): stat_vs_opp1 = 0 stat_vs_opp2 = 0 stat_vs_opp3 = 0 win_or_lose = win_or_lose.title() for u_t in user.players_teams: for opp1_t in opp1.players_teams: away_vs_opp1 = user.teams_fixture_results()[(user.teams_fixture_results()["Home"] == opp1_t) & (user.teams_fixture_results()["Away"] == u_t)] home_vs_opp1 = user.teams_fixture_results()[(user.teams_fixture_results()["Away"] == opp1_t) & (user.teams_fixture_results()["Home"] == u_t)] if win_or_lose == "Draw": stat_away = len(away_vs_opp1[away_vs_opp1["Winner"] == "Tie"]) stat_vs_opp1 += stat_away stat_home = len(home_vs_opp1[home_vs_opp1["Winner"] == "Tie"]) stat_vs_opp1 += stat_home else: stat_away = len(away_vs_opp1[away_vs_opp1[win_or_lose] == f"{u_t}"]) stat_vs_opp1 += stat_away stat_home = len(home_vs_opp1[home_vs_opp1[win_or_lose] == f"{u_t}"]) stat_vs_opp1 += stat_home for opp2_t in opp2.players_teams: away_vs_opp2 = user.teams_fixture_results()[(user.teams_fixture_results()["Home"] == opp2_t) & (user.teams_fixture_results()["Away"] == u_t)] home_vs_opp2 = user.teams_fixture_results()[(user.teams_fixture_results()["Away"] == opp2_t) & (user.teams_fixture_results()["Home"] == u_t)] if win_or_lose == "Draw": stat_away = len(away_vs_opp2[away_vs_opp2["Winner"] == "Tie"]) stat_vs_opp2 += stat_away stat_home = len(home_vs_opp2[home_vs_opp2["Winner"] == "Tie"]) stat_vs_opp2 += stat_home else: stat_away = len(away_vs_opp2[away_vs_opp2[win_or_lose] == f"{u_t}"]) stat_vs_opp2 += stat_away stat_home = len(home_vs_opp2[home_vs_opp2[win_or_lose] == f"{u_t}"]) stat_vs_opp2 += stat_home for opp3_t in opp3.players_teams: away_vs_opp3 = user.teams_fixture_results()[(user.teams_fixture_results()["Home"] == opp3_t) & (user.teams_fixture_results()["Away"] == u_t)] home_vs_opp3 = user.teams_fixture_results()[(user.teams_fixture_results()["Away"] == opp3_t) & (user.teams_fixture_results()["Home"] == u_t)] if win_or_lose == "Draw": stat_away = len(away_vs_opp3[away_vs_opp3["Winner"] == "Tie"]) stat_vs_opp3 += stat_away stat_home = len(home_vs_opp3[home_vs_opp3["Winner"] == "Tie"]) stat_vs_opp3 += stat_home else: stat_away = len(away_vs_opp3[away_vs_opp3[win_or_lose] == f"{u_t}"]) stat_vs_opp3 += stat_away stat_home = len(home_vs_opp3[home_vs_opp3[win_or_lose] == f"{u_t}"]) stat_vs_opp3 += stat_home return [stat_vs_opp1, stat_vs_opp2, stat_vs_opp3] sab_weekly = sab.weekly_df() mal_weekly = mal.weekly_df() brandon_weekly = bran.weekly_df() eli_weekly = eli.weekly_df() player_merge = sab_weekly.merge(mal_weekly, on="Mp", suffixes=("_Sab", "_Mal")) other_player_merge = brandon_weekly.merge(eli_weekly, on="Mp", suffixes=("_Bra", "_Eli")) player_weekly_merged = player_merge.merge(other_player_merge, on="Mp") player_weekly_merged_pts = week_by_week_stat(player_weekly_merged, "Points") def player_rank_by_week(stat): pts_rank = pd.DataFrame() players_weekly = week_by_week_stat(player_weekly_merged, stat) pts_rank["Mp"] = [i for i in range(1, len(players_weekly) + 1)] for player in players_weekly.columns[1:]: pts_list = [] for i in range(len(players_weekly)): ranking = players_weekly.iloc[i, 1:].rank(ascending=False) pts_list.append(math.floor(ranking[player])) pts_rank[player] = pts_list return pts_rank # stand = player_rank_by_week("Points") # Player vs player standings sab_wins = standings_verse_players(sab, bran, mal, eli, "Winner") sab_loss = standings_verse_players(sab, bran, mal, eli, "Loser") sab_draw = standings_verse_players(sab, bran, mal, eli, "Draw") sab_vs = pd.DataFrame() sab_vs["vs_Player"] = [f"{sab.player_name}_V_Brandon", f"{sab.player_name}_V_Malachi", f"{sab.player_name}_V_Eli"] sab_vs["W"] = sab_wins sab_vs["L"] = sab_loss sab_vs["D"] = sab_draw sab_vs["Pts"] = (sab_vs["W"] *3) + sab_vs["D"] sab_vs["Pts/G"] = sab_vs["Pts"]/((sab_vs["W"])+(sab_vs["L"])+(sab_vs["D"])) sab_vs = sab_vs[["vs_Player", "W", "D", "L", "Pts", "Pts/G"]] mal_wins = standings_verse_players(mal, bran, sab, eli, "Winner") mal_loss = standings_verse_players(mal, bran, sab, eli, "Loser") mal_draw = standings_verse_players(mal, bran, sab, eli, "Draw") mal_vs = pd.DataFrame() mal_vs["vs_Player"] = [f"{mal.player_name}_V_Brandon", f"{mal.player_name}_V_Sabastian", f"{mal.player_name}_V_Eli"] mal_vs["W"] = mal_wins mal_vs["L"] = mal_loss mal_vs["D"] = mal_draw mal_vs["Pts"] = (mal_vs["W"] *3) + mal_vs["D"] mal_vs["Pts/G"] = mal_vs["Pts"]/((mal_vs["W"])+(mal_vs["L"])+(mal_vs["D"])) mal_vs = mal_vs[["vs_Player", "W", "D", "L", "Pts", "Pts/G"]] bran_wins = standings_verse_players(bran, mal, sab, eli, "Winner") bran_loss = standings_verse_players(bran, mal, sab, eli, "Loser") bran_draw = standings_verse_players(bran, mal, sab, eli, "Draw") bran_vs = pd.DataFrame() bran_vs["vs_Player"] = [f"{bran.player_name}_V_Malachi", f"{bran.player_name}_V_Sabastian", f"{bran.player_name}_V_Eli"] bran_vs["W"] = bran_wins bran_vs["L"] = bran_loss bran_vs["D"] = bran_draw bran_vs["Pts"] = (bran_vs["W"] *3) + bran_vs["D"] bran_vs["Pts/G"] = bran_vs["Pts"]/((bran_vs["W"])+(bran_vs["L"])+(bran_vs["D"])) bran_vs = bran_vs[["vs_Player", "W", "D", "L", "Pts", "Pts/G"]] eli_wins = standings_verse_players(eli, mal, sab, bran, "Winner") eli_loss = standings_verse_players(eli, mal, sab, bran, "Loser") eli_draw = standings_verse_players(eli, mal, sab, bran, "Draw") eli_vs = pd.DataFrame() eli_vs["vs_Player"] = [f"{eli.player_name}_V_Malachi", f"{eli.player_name}_V_Sabastian", f"{eli.player_name}_V_Brandon"] eli_vs["W"] = eli_wins eli_vs["L"] = eli_loss eli_vs["D"] = eli_draw eli_vs["Pts"] = (eli_vs["W"] *3) + eli_vs["D"] eli_vs["Pts/G"] = eli_vs["Pts"]/((eli_vs["W"])+(eli_vs["L"])+(eli_vs["D"])) eli_vs = eli_vs[["vs_Player", "W", "D", "L", "Pts", "Pts/G"]] standings = s.standings xstandings = s.xStandings # Sabastian Team Standings sab_team_standings = sab.mini_standings() sab_team_standings.insert(0, "Year", [season] * 5) sab_team_Xstandings = sab.expected_mini_standings() sab_team_Xstandings.insert(0, "Year", [season] * 5) # Malachi Team Standings mal_team_standings = mal.mini_standings() mal_team_standings.insert(0, "Year", [season] * 5) mal_team_Xstandings = mal.expected_mini_standings() mal_team_Xstandings.insert(0, "Year", [season] * 5) # Brandon Team Standings bran_team_standings = bran.mini_standings() bran_team_standings.insert(0, "Year", [season] * 5) bran_team_Xstandings = bran.expected_mini_standings() bran_team_Xstandings.insert(0, "Year", [season] * 5) # Eli Team Standings eli_team_standings = eli.mini_standings() eli_team_standings.insert(0, "Year", [season] * 5) eli_team_Xstandings = eli.expected_mini_standings() eli_team_Xstandings.insert(0, "Year", [season] * 5) # Creates the workbook writer = pd.ExcelWriter(fr"C:\Users\sabzu\Documents\All EPL Project Files\Seasons\Fantasy Premier League {season}.xlsx") # Adds Standings to the Standings sheet standings.to_excel(writer, sheet_name="Standings", index=False) xstandings.to_excel(writer, sheet_name="Standings", index=False, startcol=10) # Add Player Standings to Standings sheet ps = player_season_standings() pxs = player_season_Xstandings() ps.to_excel(writer, sheet_name="Standings", index=False, startcol=20) pxs.to_excel(writer, sheet_name="Standings", index=False, startcol=20, startrow=7) player_weekly_merged_pts.to_excel(writer, sheet_name="Standings", index=False, startcol=32) # Format the column widths of Standings Sheet sd_sheet = writer.sheets["Standings"] sd_sheet.set_column('A:A', 13.75) sd_sheet.set_column('B:J', 5) sd_sheet.set_column('K:K', 13.75) sd_sheet.set_column('L:U', 5) sd_sheet.set_column('W:AA', 5) sd_sheet.set_column('AB:AB', 5.85) sd_sheet.set_column('AC:AG', 5) sd_sheet.set_column('AH:AK', 9.5) # Add player weekly stats to each players sheet sab_weekly.to_excel(writer, sheet_name=f"{sab.player_name}") mal_weekly.to_excel(writer, sheet_name=f"{mal.player_name}") brandon_weekly.to_excel(writer, sheet_name=f"{bran.player_name}") eli_weekly.to_excel(writer, sheet_name=f"{eli.player_name}") # Format the column widths sab_sheet = writer.sheets["Sabastian"] sab_sheet.set_column('B:L', 6.5) sab_sheet.set_column('M:M', 13.75) sab_sheet.set_column('N:T', 5) mal_weekly.to_excel(writer, sheet_name="Malachi") mal_sheet = writer.sheets["Malachi"] mal_sheet.set_column('B:L', 6.5) mal_sheet.set_column('M:M', 13.75) mal_sheet.set_column('N:T', 5) brandon_weekly.to_excel(writer, sheet_name="Brandon") bran_sheet = writer.sheets["Brandon"] bran_sheet.set_column('B:L', 6.5) bran_sheet.set_column('M:M', 13.75) bran_sheet.set_column('N:T', 5) eli_weekly.to_excel(writer, sheet_name="Eli") eli_sheet = writer.sheets["Eli"] eli_sheet.set_column('B:L', 6.5) eli_sheet.set_column('M:M', 13.75) eli_sheet.set_column('N:T', 5) # Adds players mini table to each players sheet sab_team_table = sab.mini_standings() sab_team_table.insert(0, "Year", [season] * 5) mal_team_table = mal.mini_standings() mal_team_table.insert(0, "Year", [season] * 5) bran_team_table = bran.mini_standings() bran_team_table.insert(0, "Year", [season] * 5) eli_team_table = eli.mini_standings() eli_team_table.insert(0, "Year", [season] * 5) sab_team_table.to_excel(writer, sheet_name="Sabastian", startcol=11, index=False) mal_team_table.to_excel(writer, sheet_name="Malachi", startcol=11, index=False) bran_team_table.to_excel(writer, sheet_name="Brandon", startcol=11, index=False) eli_team_table.to_excel(writer, sheet_name="Eli", startcol=11, index=False) sab_Xteam_table = sab.expected_mini_standings() sab_Xteam_table.insert(0, "Year", [season] * 5) mal_Xteam_table = mal.expected_mini_standings() mal_Xteam_table.insert(0, "Year", [season] * 5) bran_Xteam_table = bran.expected_mini_standings() bran_Xteam_table.insert(0, "Year", [season] * 5) eli_Xteam_table = eli.expected_mini_standings() eli_Xteam_table.insert(0, "Year", [season] * 5) sab_Xteam_table.to_excel(writer, sheet_name="Sabastian", startcol=11, startrow=7, index=False) mal_Xteam_table.to_excel(writer, sheet_name="Malachi", startcol=11, startrow=7, index=False) bran_Xteam_table.to_excel(writer, sheet_name="Brandon", startcol=11, startrow=7, index=False) eli_Xteam_table.to_excel(writer, sheet_name="Eli", startcol=11, startrow=7, index=False) # Add player vs other player sab_vs.to_excel(writer, sheet_name="Sabastian", startcol=22, index=False) sab_sheet.set_column("W:W", 18.65) sab_sheet.set_column("X:AA", 5) mal_vs.to_excel(writer, sheet_name="Malachi", startcol=22, index=False) mal_sheet.set_column("W:W", 18.65) mal_sheet.set_column("X:AA", 5) bran_vs.to_excel(writer, sheet_name="Brandon", startcol=22, index=False) bran_sheet.set_column("W:W", 18.65) bran_sheet.set_column("X:AA", 5) eli_vs.to_excel(writer, sheet_name="Eli", startcol=22, index=False) eli_sheet.set_column("W:W", 18.65) eli_sheet.set_column("X:AA", 5) writer.save()
<reponame>dorranh/clowdr-web-app<filename>src/components/Pages/Admin/Registration/Registration.tsx import { Registration } from "@clowdr-app/clowdr-db-schema"; import assert from "assert"; import Parse from "parse"; import React, { useState } from "react"; import { Redirect } from "react-router-dom"; import { addError, addNotification } from "../../../../classes/Notifications/Notifications"; import useConference from "../../../../hooks/useConference"; import useHeading from "../../../../hooks/useHeading"; import useSafeAsync from "../../../../hooks/useSafeAsync"; import useUserRoles from "../../../../hooks/useUserRoles"; import Column, { DefaultItemRenderer, Item as ColumnItem } from "../../../Columns/Column/Column"; import Columns from "../../../Columns/Columns"; import { LoadingSpinner } from "../../../LoadingSpinner/LoadingSpinner"; import "./Registration.scss"; interface Props { } type RegistrationSpec = { name: string; email: string; affiliation: string; country: string; newRole: "attendee" | "manager" | "admin"; }; interface NewRegistrationEmailsData { conference: string; registrations: Array<RegistrationSpec>; } type UploadRegistrationEmailsResponse = Array<{ index: number; result: string | boolean }>; interface SendRegistrationEmailsData { sendOnlyUnsent: boolean; conference: string; } interface SendRegistrationEmailsResponse { success: boolean; results: { success: boolean, to: string, reason?: string }[] } export default function AdminRegistration(props: Props) { const conference = useConference(); const { isAdmin } = useUserRoles(); const [isSending, setIsSending] = useState<boolean>(false); const [isUploading, setIsUploading] = useState<boolean>(false); const [isProcessing, setIsProcessing] = useState<boolean>(false); const [newRegsData, setNewRegsData] = useState<any>(null); const [existingRegs, setExistingRegs] = useState<Registration[] | null>(null); const [sentRepeats, setSentRepeats] = useState<boolean>(false); useSafeAsync(async () => Registration.getAll(conference.id), setExistingRegs, [conference.id]); useHeading({ title: "Admin: Registrations", }); async function doUploadRegistrations(data: NewRegistrationEmailsData): Promise<UploadRegistrationEmailsResponse> { setIsUploading(true); const response = await Parse.Cloud.run("registration-create-many", data) as UploadRegistrationEmailsResponse; return response; } function uploadRegistrations(): void { doUploadRegistrations({ conference: conference.id, registrations: newRegsData }) .then(responses => { const failedIdxs: number[] = []; let successCount = 0; for (const response of responses) { if (!response.result) { failedIdxs.push(response.index); } else { successCount++; } } if (successCount > 0) { addNotification(`Uploaded ${successCount} registrations.`); } if (failedIdxs.length > 0) { addError(`Failed to upload ${failedIdxs.length} registrations.`); } setIsUploading(false); }) .catch(_ => { addError("Error when attempting to upload new registrations."); setIsUploading(false); }); } async function doSendRegistrationEmails(data: SendRegistrationEmailsData): Promise<SendRegistrationEmailsResponse> { setIsSending(true); setSentRepeats(!data.sendOnlyUnsent); const response = await Parse.Cloud.run("registration-send-emails", data) as SendRegistrationEmailsResponse; return response; } function sendRegistrationEmails(sendOnlyUnsent: boolean): void { doSendRegistrationEmails({ sendOnlyUnsent, conference: conference.id }) .then(response => { if (response.success) { addNotification(`Sent ${response.results.length} registration ${response.results.length === 1 ? "email" : "emails"}.`); } else { addError(`Failed to send ${response.results.filter(result => !result.success).length} of ${response.results.length} registration ${response.results.length === 1 ? "email" : "emails"}.`) } setIsSending(false); }) .catch(e => { console.error(e); addError("Error when attempting to send registration emails."); setIsSending(false); }); } function regRenderer(item: ColumnItem<Registration>): JSX.Element { const data = item.renderData; const linkURL = `${process.env.REACT_APP_FRONTEND_URL}/register/${conference.id}/${data.id}/${data.email}`; return <> <div className="name"> {data.name} </div> <div className="email"> {data.email} </div> <div className="link"> <a href={linkURL}>{linkURL}</a> </div> </>; } const adminPanel = <> <h2>Upload new registrations</h2> <p> You can upload new registrations using a JSON file. The required format is specified below. Emails will not be sent to new addresses until you press one of the Send buttons below. Duplicate registrations will not be created for existing email addresses. </p> <div> {isUploading ? <LoadingSpinner message="Uploading registrations" /> : <> <div> <label htmlFor="newRegistrationsFile">Select JSON file</label><br /> <input id="newRegistrationsFile" type="file" accept="application/json" disabled={isProcessing} onChange={async (ev) => { setIsProcessing(true); let result: Array<any> | null = null; if (ev.target.files) { for (const file of ev.target.files) { try { const fileContents = await file.text(); const fileData = JSON.parse(fileContents); assert(fileData instanceof Array); result = (result || [] as any[]).concat(fileData); } catch (e) { addError(`File "${file.name}" contains invalid data.`); } } } setNewRegsData(result); setIsProcessing(false); }} /> </div><br /> <button disabled={isProcessing || isUploading || !newRegsData || newRegsData.length === 0} onClick={() => uploadRegistrations()}> Upload registrations </button> </>} </div> <br /> <h5>Registration data format</h5> <p> <pre>{`type registrationsFile = Array<RegistrationSpec>; type RegistrationSpec = { name: string; email: string; affiliation: string; country: string; newRole: "attendee" | "manager" | "admin"; };`} </pre> </p> <h2>Send initial registration emails</h2> <p>Send the first registration email to any users that have not yet been sent one.</p> <p>{isSending ? <LoadingSpinner message="Sending emails" /> : <button disabled={isSending} onClick={() => sendRegistrationEmails(true)}>Send initial registration emails</button>}</p> <h2>Send repeat registration emails</h2> <p>Send a repeat registration email to all users that have not yet registered. Includes users that have not yet received any registration email.</p> <p>{sentRepeats ? <>You have alrerady sent repeat emails. Pressing this button again will send the same people another copy of their registration email. If this is what you would like to do, please refresh the page.</> : isSending ? <LoadingSpinner message="Sending emails" /> : <button disabled={isSending} onClick={() => sendRegistrationEmails(false)}>Send repeat registration emails</button>}</p> <Columns className="admin-registrations"> <Column className="col" items={existingRegs?.map(reg => ({ key: reg.id, text: reg.name, renderData: reg })) ?? undefined} itemRenderer={{ render: regRenderer }} loadingMessage="Loading existing registrations"> <h2>Existing Registrations{existingRegs ? ` (${existingRegs.length})` : ""}</h2> </Column> </Columns> </>; return isAdmin === null ? <LoadingSpinner /> : isAdmin ? adminPanel : <Redirect to="/notfound" />; }
<reponame>lhbruneton/taormina import { Injectable } from '@angular/core'; import { select, Store } from '@ngrx/store'; import * as LandsPileCardsActions from './lands-pile-cards.actions'; import * as LandsPileCardsFeature from './lands-pile-cards.reducer'; import * as LandsPileCardsSelectors from './lands-pile-cards.selectors'; @Injectable() export class LandsPileCardsFacade { /** * Combine pieces of state using createSelector, * and expose them as observables through the facade. */ loaded$ = this.store.pipe( select(LandsPileCardsSelectors.getLandsPileCardsLoaded) ); allLandsPileCards$ = this.store.pipe( select(LandsPileCardsSelectors.getAllLandsPileCards) ); selectedLandsPileCards$ = this.store.pipe( select(LandsPileCardsSelectors.getLandsPileCardsSelected) ); constructor( private store: Store<LandsPileCardsFeature.LandsPileCardsPartialState> ) {} /** * Use the initialization action to perform one * or more tasks in your Effects. */ initNewGame(): void { this.store.dispatch(LandsPileCardsActions.initLandsPileCardsNewGame()); } initSavedGame(): void { this.store.dispatch(LandsPileCardsActions.initLandsPileCardsSavedGame()); } selectLandsPileCard(pivotId: string): void { this.store.dispatch( LandsPileCardsActions.selectLandsPileCard({ id: pivotId }) ); } removeLandsPileCard(id: string): void { this.store.dispatch(LandsPileCardsActions.removeLandsPileCard({ id })); } }
#!/bin/sh mkdir -p data temp wget http://www.kdd.org/cupfiles/KDDCup2000.zip -P temp unzip temp/KDDCup2000.zip assoc/BMS-POS.dat.gz -d temp gunzip temp/assoc/BMS-POS.dat.gz -c > data/bms-pos.dat wget http://fimi.ua.ac.be/data/kosarak.dat -P data wget https://archive.org/download/AOL_search_data_leak_2006/AOL_search_data_leak_2006.zip -P temp unzip temp/AOL_search_data_leak_2006.zip AOL-user-ct-collection/* -d temp mkdir -p data/aol mv temp/AOL-user-ct-collection/*.gz data/aol/ rm -rf temp
#!/bin/sh #/Applications/myapps/jetty/jetty-distribution-9.2.6.v20141205/bin/jetty.sh start #!/bin/sh export JETTY_HOME=/c/temp/automon/jetty export JAVA_OPTIONS=' -server -Xms256m -Xmx512m -Dorg.aspectj.weaver.loadtime.configuration=file:C:/temp/automon/examples/config/automon-aop.xml -javaagent:C:/temp/automon/examples/libs/aspectjweaver.jar ' $JETTY_HOME/bin/jetty.sh start
/* * Copyright 2011 the original author or 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 org.vertx.tests.core.http; import org.testng.annotations.Test; import org.vertx.java.core.Handler; import org.vertx.java.core.SimpleHandler; import org.vertx.java.core.buffer.Buffer; import org.vertx.java.core.http.HttpClient; import org.vertx.java.core.http.HttpServer; import org.vertx.java.core.http.WebSocket; import org.vertx.java.core.http.WebSocketVersion; import org.vertx.java.core.internal.VertxInternal; import org.vertx.java.core.logging.Logger; import org.vertx.tests.Utils; import org.vertx.tests.core.TestBase; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author <a href="http://tfox.org"><NAME></a> */ public class WebsocketTest extends TestBase { private static final Logger log = Logger.getLogger(WebsocketTest.class); @Test public void testWSBinaryHybi00() throws Exception { testWS(true, WebSocketVersion.HYBI_00); throwAssertions(); } @Test public void testWSStringHybi00() throws Exception { testWS(false, WebSocketVersion.HYBI_00); throwAssertions(); } @Test public void testWSBinaryHybi08() throws Exception { testWS(true, WebSocketVersion.HYBI_08); throwAssertions(); } @Test public void testWSStringHybi08() throws Exception { testWS(false, WebSocketVersion.HYBI_08); throwAssertions(); } @Test public void testWSBinaryHybi17() throws Exception { testWS(true, WebSocketVersion.HYBI_17); throwAssertions(); } @Test public void testWSStringHybi17() throws Exception { testWS(false, WebSocketVersion.HYBI_17); throwAssertions(); } private void testWS(final boolean binary, final WebSocketVersion version) throws Exception { final String host = "localhost"; final boolean keepAlive = true; final String path = "/some/path"; final int port = 8181; final CountDownLatch latch = new CountDownLatch(1); VertxInternal.instance.go(new Runnable() { public void run() { final HttpClient client = new HttpClient().setPort(port).setHost(host).setKeepAlive(keepAlive).setMaxPoolSize(5); final HttpServer server = new HttpServer().websocketHandler(new Handler<WebSocket>() { public void handle(final WebSocket ws) { azzert(path.equals(ws.uri)); ws.dataHandler(new Handler<Buffer>() { public void handle(Buffer data) { //Echo it back ws.writeBuffer(data); } }); } }).listen(port, host); final int bsize = 100; final int sends = 10; client.connectWebsocket(path, version, new Handler<WebSocket>() { public void handle(final WebSocket ws) { final Buffer received = Buffer.create(0); ws.dataHandler(new Handler<Buffer>() { public void handle(Buffer data) { received.appendBuffer(data); if (received.length() == bsize * sends) { ws.close(); server.close(new SimpleHandler() { public void handle() { client.close(); latch.countDown(); } }); } } }); final Buffer sent = Buffer.create(0); for (int i = 0; i < sends; i++) { if (binary) { Buffer buff = Buffer.create(Utils.generateRandomByteArray(bsize)); ws.writeBinaryFrame(buff); sent.appendBuffer(buff); } else { String str = Utils.randomAlphaString(100); ws.writeTextFrame(str); sent.appendBuffer(Buffer.create(str, "UTF-8")); } } } }); } }); azzert(latch.await(5, TimeUnit.SECONDS)); throwAssertions(); } }
/* XTal = 16MHz Toggle LED using General Purpose Timer Register Here we use TIMER2 which is 32bit timer attached to APB1 bus */ #include "stm32f4xx.h" // Device header int main(void){ RCC->AHB1ENR |=0x1; //Enable GPIOA GPIOA->MODER |=0x400; //Enable OUTPUT mode RCC->APB1ENR |=0x1; //Enable TIMER2 TIM2->PSC = 1600-1; //16 000 000 divide by 1600 = 10000 TIM2->ARR = 10000-1; //10 000 divide by 10000 = 1sec delay TIM2->CNT = 0; //Clear Timer Counter becoz not used TIM2->CR1 = 1; //Enable Timer control while(1){ while(!(TIM2->SR & 1)){} GPIOA->ODR ^= 0x20; //Toggle GPIOA TIM2->SR=0; } }
<reponame>bertmaher/tvm<filename>vta/apps/tsim_example/tests/python/add_by_one.py<gh_stars>10-100 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import numpy as np from tsim.driver import driver def test_tsim(i): rmin = 1 # min vector size of 1 rmax = 64 n = np.random.randint(rmin, rmax) ctx = tvm.cpu(0) a = tvm.nd.array(np.random.randint(rmax, size=n).astype("uint64"), ctx) b = tvm.nd.array(np.zeros(n).astype("uint64"), ctx) f = driver("libhw", "libsw") f(a, b) emsg = "[FAIL] test number:{} n:{}".format(i, n) np.testing.assert_equal(b.asnumpy(), a.asnumpy() + 1, err_msg=emsg) print("[PASS] test number:{} n:{}".format(i, n)) if __name__ == "__main__": times = 10 for i in range(times): test_tsim(i)
def loss(self, prediction_dict, groundtruth_lists): """Compute scalar loss tensors with respect to provided groundtruth. Args: prediction_dict: A dictionary holding prediction tensors. groundtruth_lists: A dict of tensors holding groundtruth information, with one entry for each image in the batch. Returns: loss_tensor: A scalar tensor representing the computed loss. """ logits = prediction_dict['logits'] predicted_classes = prediction_dict['classes'] # Assuming a classification task with cross-entropy loss loss_tensor = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=groundtruth_lists) ) return loss_tensor
import { HTTPTransport, HTTPRequestEncoder } from '@alicloud/mpserverless-core'; import { QueryService } from './query'; export interface TransactionJSONObject { transactionId: string; } export declare enum TransactionStatus { INIT = "init", COMMIT = "commit", ROLLBACK = "rollback" } export declare class Transaction { protected id: string; protected status: TransactionStatus; protected httpTransport: HTTPTransport; protected httpRequestEncoder: HTTPRequestEncoder; protected queryService: QueryService; constructor(httpTransport: HTTPTransport, httpRequestEncoder: HTTPRequestEncoder); init(): Promise<void>; collection(name: string): QueryService; commit(): Promise<import("./result").ResultJSONObject | import("./query").QueryJSONObject>; rollback(): Promise<import("./result").ResultJSONObject | import("./query").QueryJSONObject>; private checkStatus; }
<gh_stars>0 /************************************************************************** * * Copyright (c) 2012-2017 <NAME> All Rights Reserved. * **************************************************************************/ "use strict"; /** * A simple Assynchronous Module Definition implementation. Intended * only for use in browsers. */ (function ( topContext ) { var _isStarted = false; var _baseUrl = null; var _paths = null; var _startFunction = null; var _pendingLoads = []; // Used as cache for speeding access to class objects. Keys are // the classes fully qualified names. var _allClassesByName = {}; // Number of classes still waiting to be loaded. var _loadInProgressCount = 0; // Populated by the "define(...)" function. var _lastDefineClassBuilder = null; /** * */ function define ( classBuilder ) { if ( _lastDefineClassBuilder != null ) { var msg = "Called twice inside the same module."; throw msg } _lastDefineClassBuilder = classBuilder; } // Emulate a RequireJS environment. define.amd = true; /** * */ function _log ( msg ) { window.console.log(msg); } /** * */ function _lazyClassLoad ( className ) { var wrapperClass = function () { var klass = _allClassesByName[className]; if ( klass == null ) { var msg = "Class \"" + className + "\" is not loaded yet"; throw msg; } return klass.apply(this, arguments); }; if ( _isStarted ) { _scheduleClassLoad(className, wrapperClass); } else { _pendingLoads.push({ className : className, wrapperClass : wrapperClass }); } return wrapperClass; } /** * */ function _scheduleClassLoad ( className, wrapperClass ) { var scriptUrl = _buildScriptUrl(className); var loadCompletedCallback = function () { _onLoadCompleted(className, wrapperClass, scriptUrl); }; ++_loadInProgressCount; _scheduleScriptLoad(scriptUrl, loadCompletedCallback); } /** * */ function _onLoadCompleted ( className, wrapperClass, scriptUrl ) { _processIfDefineWasCalled(className); var klass = _findClassWithName(className); if ( klass == null ) { var msg = "" + "Class \"" + className + "\" " + "not defined on script \"" + scriptUrl + "\""; throw msg; } _extend(wrapperClass, klass); wrapperClass.prototype = klass.prototype; --_loadInProgressCount; if ( _loadInProgressCount == 0 ) { // All asynchronous loads have completed by now. _startFunction(); } } /** * */ function _processIfDefineWasCalled ( className ) { if ( _lastDefineClassBuilder != null ) { try { _allClassesByName[className] = _lastDefineClassBuilder(_require); } catch ( error ) { _log("Failed to define class \"" + className + "\" - " + error); } _lastDefineClassBuilder = null; } } /** * */ function _require ( classPath ) { var className = classPath; var klass = _findClassWithName(className); if ( klass == null ) { klass = _lazyClassLoad(className); } return klass; } /** * It will return null if the given class has not yet been * defined. */ function _findClassWithName ( className ) { return _allClassesByName[className]; } /** * */ function _buildScriptUrl ( className ) { var scriptUrl = _paths[className]; if ( scriptUrl == null ) { scriptUrl = _baseUrl + className + ".js"; } return scriptUrl; } /** * */ function _scheduleScriptLoad ( scriptUrl, loadCompletedCallback ) { var tag = document.createElement('script'); var isDone = false; tag.src = scriptUrl; tag.type = "text/javascript"; tag.async = "true"; tag.onload = function() { var readyState = this.readyState; var isLoaded = true && readyState && (readyState!="complete") && (readyState!="loaded"); if ( !isLoaded && !isDone ) { loadCompletedCallback(); isDone = true; } }; tag.onreadystatechange = tag.onload; var scriptNode = document.getElementsByTagName('script')[0]; scriptNode.parentNode.insertBefore(tag, scriptNode); } /** * */ function _extend ( target, object ) { for ( var fieldName in object ) { target[fieldName] = object[fieldName]; } } /** * */ function _amdConfig ( config ) { _baseUrl = config.baseUrl; _paths = config.paths || {}; } /** * */ function _bootstrap ( loadCompletedCallback ) { _startFunction = loadCompletedCallback; _isStarted = true; _pendingLoads.forEach(function ( item ) { _scheduleClassLoad(item.className, item.wrapperClass); }); _pendingLoads = []; if ( _loadInProgressCount == 0 ) { // All asynchronous loads have completed by now. _startFunction(); } } /** * */ function amd ( classPathList, mainFunction ) { var classList = classPathList.map(_require); var onLoadCompleted = function () { mainFunction.apply(null, classList); }; _bootstrap(onLoadCompleted); } amd.config = _amdConfig; /** * */ var methodMap = { amd : amd, }; topContext.varmateo = topContext.varmateo ? topContext.varmateo : {}; _extend(topContext.varmateo, methodMap); var topContextMethodMap = { define : define, } _extend(topContext, topContextMethodMap); })(window);
echo "Getting login token..." curlRequest1=$(curl --form client_id=$CONSUMER_KEY \ --form client_secret=$CONSUMER_SECRET \ --form grant_type=password \ --form username=$USERNAME\ --form password=$PASSWORD \ https://login.salesforce.com/services/oauth2/token) authToken=$(jq -r '.access_token' <<<"$curlRequest1") instanceURL=$(jq -r '.instance_url' <<<"$curlRequest1") echo "authToken: $authToken" echo "instanceURL: $instanceURL" arraySandboxes=('dev1' 'dev2' 'dev3') echo "Query sandbox ids..." curlRequest2=$(curl -H "Authorization: Bearer ${authToken}" \ "${instanceURL}/services/data/v42.0/tooling/query?q=SELECT+id,sourceid,sandboxname+from+sandboxinfo+where+sandboxname+in%20('dev1'%2C'dev2'%2C'dev3')") echo "Query active work requests..." curlRequest3=$(curl -H "Authorization: Bearer ${authToken}" \ -H "Content-Type: application/json" \ "${instanceURL}/services/data/v43.0/query?q=SELECT+Id%2CName%2Cagf__Scheduled_Build_Name__c+FROM+agf__ADM_Work__c+WHERE+agf__Scheduled_Build_Name__c+%21%3D+null+AND+%28NOT+agf__Status__c+LIKE+%27Closed%25%27%29") arraySandboxesInUse=$(jq -r '.records[] | .agf__Scheduled_Build_Name__c' <<<"$curlRequest3") echo "Sandboxes In Use: ${arraySandboxesInUse}" sandboxString=" ${arraySandboxes[*]} " for item in ${arraySandboxesInUse[@]}; do sandboxString=${sandboxString/ ${item} / } done arraySandboxes=( $sandboxString ) echo "Sandboxes To Be Refreshed: ${arraySandboxes[*]}" for sbox in ${arraySandboxes[@]}; do echo "Refreshing ${sbox}" sboxId=$(jq -r --arg vname "${sbox}" '.records[] | select(.SandboxName==$vname) | .Id' <<<"$curlRequest2") echo "Sandbox ID: $sboxId" curlRequest4=$(curl -H "Authorization: Bearer ${authToken}" \ -H "Content-Type: application/json" \ -d '{"LicenseType": "DEVELOPER","AutoActivate": true,"ApexClassId": "01p31000006BQ5M"}' \ --request "PATCH" "${instanceURL}/services/data/v42.0/tooling/sobjects/SandboxInfo/${sboxId}") echo "$curlRequest4" | jq . done
angular .module('pulse') .controller('memberCtl', memberCtl); function memberCtl($scope, API, $location) { var brandId = $location.search()['brandid']; var memberId = $location.search()['memberid']; var name = $location.search().name; var phone = $location.search().phone; var page = $location.search().page; var startTime = $location.search()['starttime']; var endTime = $location.search()['endtime']; var dataParam = 'brandid=' + brandId; if(typeof(memberId)!="undefined"&&memberId!=null&&memberId!="") dataParam += '&memberid=' + memberId; if(typeof(name)!="undefined"&&name!=null&&name!="") dataParam += '&name=' + name; if(typeof(phone)!="undefined"&&phone!=null&&phone!="") dataParam += '&phone=' + phone; if(typeof(startTime)!="undefined"&&startTime!=null&&startTime!="") dataParam += '&starttime=' + startTime; if(typeof(endTime)!="undefined"&&endTime!=null&&endTime!="") dataParam += '&endtime=' + endTime; if(typeof(page)!="undefined"&&page!=null&&page!="") { dataParam += '&start=' + page; }else{ dataParam += '&start=1'; } dataParam += '&sort=0'; dataParam += '&size=10'; API.member(dataParam, function(result) { $scope.wsorts = [ {name:'0', value:'按消费总额'}, {name:'1', value:'按消费次数'}, {name:'2', value:'按最近消费时间'} ]; $scope.brandId = result.brandId; $scope.stores = result.stores; $scope.memberId = result.memberId; $scope.name = result.name; $scope.source = result.source; //$scope.sortss = result.sort; $scope.phone = result.phone; $scope.beginTime = result.startTime; $scope.endTime = result.endTime; $scope.userList = result.data; $scope.pageCount = result.pageCount; $scope.page = result.page; $scope.pageNum = []; if(result.pageCount<=10) { for (var i = 0; i < result.pageCount; i++) { $scope.pageNum.push(i + 1); } }else{ if((result.pageCount-result.page)<5){ for (var i = 9; i >= 0; i--) { $scope.pageNum.push(result.pageCount-i); } }else{ //alert('1-' + JSON.stringify($scope.pageNum)); if(result.page<=5){ for(var j=1; j<11; j++){ $scope.pageNum.push(j); } }else{ for (var i = 5; i > 0; i--) { $scope.pageNum.push(result.page-i); } $scope.pageNum.push(result.page); for (var i = 1; i < 5; i++) { $scope.pageNum.push(result.page+i); } } } } }, function(){ alert("get data error"); }); $scope.qureyMember = function(brandId,memberId,name,source,sort,phone,beginTime,endsTime,page){ $scope.wsorts = [ {name:'0', value:'按消费总额'}, {name:'1', value:'按消费次数'}, {name:'2', value:'按最近消费时间'} ]; var startTime; var endTime; if(typeof(beginTime)!="undefined"&&beginTime!=null&&beginTime!="") { startTime = beginTime; }else{ startTime = $("#datetime_begin").val(); } if(typeof(endsTime)!="undefined"&&endsTime!=null&&endsTime!="") { endTime = endsTime; }else{ endTime = $("#datetime_end").val(); } var dataParam = 'brandid=' + brandId; if(typeof(memberId)!="undefined"&&memberId!=null) dataParam += '&memberid=' + memberId; if(typeof(name)!="undefined"&&name!=null) dataParam += '&name=' + name; if(typeof(source)!="undefined"&&source!=null) dataParam += '&source=' + source; if(typeof(sort)!="undefined"&&sort!=null) dataParam += '&sort=' + sort; if(typeof(phone)!="undefined"&&phone!=null) dataParam += '&phone=' + phone; if(typeof(startTime)!="undefined"&&startTime!=null&&startTime!="") dataParam += '&starttime=' + startTime; if(typeof(endTime)!="undefined"&&endTime!=null&&endTime!="") dataParam += '&endtime=' + endTime; if(typeof(page)!="undefined"&&page!=null&&page!="") { dataParam += '&start=' + page; }else{ dataParam += '&start=1'; } dataParam += '&size=10'; if(!brandId){ alert("品牌ID不能为空") return; } API.member(dataParam, function(result) { $scope.brandId = result.brandId; $scope.stores = result.stores; $scope.memberId = result.memberId; $scope.name = result.name; $scope.source = result.source; //$scope.sortss = result.sort; $scope.phone = result.phone; $scope.beginTime = result.startTime; $scope.endTime = result.endTime; $scope.userList = result.data; $scope.pageCount = result.pageCount; $scope.page = result.page; $scope.pageNum = []; if(result.pageCount<=10) { for (var i = 0; i < result.pageCount; i++) { $scope.pageNum.push(i + 1); } }else{ if((result.pageCount-result.page)<5){ for (var i = 9; i >= 0; i--) { $scope.pageNum.push(result.pageCount-i); } }else{ //alert('1-' + JSON.stringify($scope.pageNum)); if(result.page<=5){ for(var j=1; j<11; j++){ $scope.pageNum.push(j); } }else{ for (var i = 5; i > 0; i--) { $scope.pageNum.push(result.page-i); } $scope.pageNum.push(result.page); for (var i = 1; i < 5; i++) { $scope.pageNum.push(result.page+i); } } } } }, function(){ alert("get data error"); }); } var beginTimePicker = $("#datetime_begin"); var endTimePicker = $("#datetime_end"); //初始化日期时间控件 beginTimePicker.datetimepicker({ format: 'Y-m-d H:00', lang: 'ch', onShow: function() { } }); endTimePicker.datetimepicker({ format: 'Y-m-d H:00', lang: 'ch', onShow: function() { } }); $scope.jinYong = function(id,status,brandId,memberId,name,sort,phone,beginTime,endsTime,page){ var dataParam = "id=" + id + "&status=" + status; API.userInfoStatus(dataParam, function(result) { if(status==0) alert("启用成功"); if(status==1) alert("禁用成功"); }, function(){ alert("jinyong error"); }); var param = 'brandid=' + brandId; if(typeof(memberId)!="undefined"&&memberId!=null&&memberId!="") param += '&memberid=' + memberId; if(typeof(name)!="undefined"&&name!=null) param += '&name=' + name; if(typeof(sort)!="undefined"&&sort!=null) param += '&sort=' + sort; if(typeof(phone)!="undefined"&&phone!=null) param += '&phone=' + phone; if(typeof(beginTime)!="undefined"&&beginTime!=null&&beginTime!="") param += '&starttime=' + beginTime; if(typeof(endsTime)!="undefined"&&endsTime!=null&&endsTime!="") param += '&endtime=' + endsTime; if(typeof(page)!="undefined"&&page!=null&&page!="") { param += '&start=' + page; }else{ param += '&start=1'; } param += '&size=10'; API.member(param, function(result) { $scope.brandId = result.brandId; $scope.stores = result.stores; $scope.memberId = result.memberId; $scope.name = result.name; //$scope.sortss = result.sort; $scope.phone = result.phone; $scope.beginTime = result.startTime; $scope.endTime = result.endTime; $scope.userList = result.data; $scope.pageCount = result.pageCount; $scope.page = result.page; $scope.pageNum = []; if(result.pageCount<=10) { for (var i = 0; i < result.pageCount; i++) { $scope.pageNum.push(i + 1); } }else{ if((result.pageCount-result.page)<5){ for (var i = 9; i >= 0; i--) { $scope.pageNum.push(result.pageCount-i); } }else{ //alert('1-' + JSON.stringify($scope.pageNum)); if(result.page<=5){ for(var j=1; j<11; j++){ $scope.pageNum.push(j); } }else{ for (var i = 5; i > 0; i--) { $scope.pageNum.push(result.page-i); } $scope.pageNum.push(result.page); for (var i = 1; i < 5; i++) { $scope.pageNum.push(result.page+i); } } } } }, function(){ alert("jinyong get data error"); }); } }
// Copyright 2019 BlueCat Networks. All rights reserved. // JavaScript for your page goes in here. content_box = $("#data_display") for (var ip in content) { console.log(ip) records = "" for (var record in content[ip]) { records += content[ip][record] + " " } content_box.append("<p>"+ip + " | " + records+"</p>") }
<reponame>CMPUT301W21T02/Kotlout package xyz.kotlout.kotlout.model.experiment.trial; import xyz.kotlout.kotlout.model.geolocation.Geolocation; /** * A trial with a binary (true or false) outcome */ public class BinomialTrial extends Trial { private boolean result; /** * Default public constructor for Firebase to use. */ public BinomialTrial() { } /** * Parameterized constructor for creating new instances before storing into Firebase. * * @param result Result to store in the trial * @param experimenterId Experimenter who did the trial. * @param location Location of the trial */ public BinomialTrial(boolean result, String experimenterId, Geolocation location) { super(experimenterId, location); this.result = result; } /** * Get result stored in trial. * * @return result of trial. */ public boolean getResult() { return result; } /** * Set trial with a result. SHOULD ONLY BE USED FOR FIREBASE. * * @param result Boolean result to set. */ public void setResult(boolean result) { this.result = result; } }
<filename>register-order-models_test.go package cdek import "testing" func TestOrderResp_GetError(t *testing.T) { type fields struct { Error Error DispatchNumber *int Number *string } tests := []struct { name string fields fields wantErr bool }{ { name: "err", fields: fields{ Error: Error{ ErrorCode: strLink("err_code"), Msg: strLink("error text"), }, DispatchNumber: intLink(192957), Number: strLink("test_number"), }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { o := &OrderResp{ Error: tt.fields.Error, DispatchNumber: tt.fields.DispatchNumber, Number: tt.fields.Number, } if err := o.GetError(); (err != nil) != tt.wantErr { t.Errorf("OrderResp.GetError() error = %v, wantErr %v", err, tt.wantErr) } }) } }
function selector(x) { switch (x) { case 1: document.getElementsByClassName("gamecards-container")[0].children[x - 1].children[0].src = "../images/games/snake3dS.png"; break; case 2: document.getElementsByClassName("gamecards-container")[0].children[x - 1].children[0].src = "../images/games/Untitled.png"; break; case 3: document.getElementsByClassName("gamecards-container")[0].children[x - 1].children[0].src = "../images/games/Untitled.png"; break; default: break; } } function removeSelector(x) { switch (x) { case 1: document.getElementsByClassName("gamecards-container")[0].children[x - 1].children[0].src = "../images/games/snake3d.png"; break; case 2: document.getElementsByClassName("gamecards-container")[0].children[x - 1].children[0].src = "../images/games/oksok.png"; break; case 3: document.getElementsByClassName("gamecards-container")[0].children[x - 1].children[0].src = "../images/games/oksok.png"; break; default: break; } } var char8; var charH; var charK; var charC; var charS; function tbPassword_KeyUp() { char8 = document.getElementById("char8"); charH = document.getElementById("charH"); charK = document.getElementById("charK"); charC = document.getElementById("charC"); charS = document.getElementById("charS"); char8.style.color = "white"; charH.style.color = "white"; charK.style.color = "white"; charC.style.color = "white"; charS.style.color = "white"; var hallo = document.getElementById("password").value; if (hallo.length > 0) { validatePass(hallo); } } function validatePass(x) { var bool8 = false; var boolH = false; var boolK = false; var boolC = false; var boolS = false; bool8 = /.{8,}/.test(x); boolH = /[A-Z]/.test(x); boolK = /[a-z]/.test(x); boolC = /[0-9]/.test(x); boolS = /[!#$%&'"()*+,-./:;<=>?@[\]^_`{|}~]/.test(x); if (!bool8) { char8.style.color = "red"; } if (!boolH) { charH.style.color = "red"; } if (!boolK) { charK.style.color = "red"; } if (!boolC) { charC.style.color = "red"; } if (!boolS) { charS.style.color = "red"; } } function showPassword(y) { var x = document.getElementById("password"); if (x.type === "password") { x.type = "text"; y.src = "../images/eyeline.png"; } else { x.type = "password"; y.src = "../images/eye.png"; } } function showPasswordConfirm(y) { var x = document.getElementById("password-confirm"); if (x.type === "password") { x.type = "text"; y.src = "../images/eyeline.png"; } else { x.type = "password"; y.src = "../images/eye.png"; } } // mobiele navigatebar var x = 1; function openAccountMenu() { var el = document.getElementById("dropdown-account"); var arr = el.children; if (x == 1) { x = 0; el.style.height = 100 + "px"; el.style.borderBottomWidth = "2px"; el.style.borderLeftWidth = "2px"; for (let i = 0; i < arr.length; i++) { arr[i].style.display = "block"; } } else{ x = 1; el.style.height = 0 + "px"; el.style.borderBottomWidth = "0px"; el.style.borderLeftWidth = "0px"; for (let i = 0; i < arr.length; i++) { arr[i].style.display = "none"; } } } // var hoi = 1; // function hahalol() { // var randomX = Math.floor(Math.random() * document.getElementById('welcome-grid').clientWidth); // var randomY = Math.floor(Math.random() * document.getElementById('welcome-grid').clientHeight); // if (hoi == 1) { // document.getElementById("hahalol").style.transform = "translate(" + (-randomX + 170) + "px," + (randomY - 100) + "px)"; // // document.getElementById("hahalol").style.transform = "translateY(" + randomY + "px)"; // hoi = 0; // } // else { // document.getElementById("hahalol").style.transform = "translateY(0px)"; // document.getElementById("hahalol").style.transform = "translateX(0px)"; // hoi = 1; // } // }
package io.opensphere.core.util.javafx; import java.util.function.Consumer; import javafx.beans.InvalidationListener; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; /** * Thread-safe {@link SimpleBooleanProperty}. */ public class ConcurrentBooleanProperty extends SimpleBooleanProperty implements Consumer<Boolean> { /** * The constructor of {@code BooleanProperty}. */ public ConcurrentBooleanProperty() { super(); } /** * The constructor of {@code BooleanProperty}. * * @param initialValue the initial value of the wrapped value */ public ConcurrentBooleanProperty(boolean initialValue) { super(initialValue); } /** * The constructor of {@code BooleanProperty}. * * @param bean the bean of this {@code BooleanProperty} * @param name the name of this {@code BooleanProperty} */ public ConcurrentBooleanProperty(Object bean, String name) { super(bean, name); } /** * The constructor of {@code BooleanProperty}. * * @param bean the bean of this {@code BooleanProperty} * @param name the name of this {@code BooleanProperty} * @param initialValue the initial value of the wrapped value */ public ConcurrentBooleanProperty(Object bean, String name, boolean initialValue) { super(bean, name, initialValue); } @Override public synchronized void addListener(InvalidationListener listener) { super.addListener(listener); } @Override public synchronized void removeListener(InvalidationListener listener) { super.removeListener(listener); } @Override public synchronized void addListener(ChangeListener<? super Boolean> listener) { super.addListener(listener); } @Override public synchronized void removeListener(ChangeListener<? super Boolean> listener) { super.removeListener(listener); } @Override public synchronized void fireValueChangedEvent() { super.fireValueChangedEvent(); } @Override @SuppressWarnings("PMD.BooleanGetMethodName") public synchronized boolean get() { return super.get(); } @Override public synchronized void set(boolean newValue) { super.set(newValue); } @Override public synchronized boolean isBound() { return super.isBound(); } @Override public synchronized void bind(ObservableValue<? extends Boolean> newObservable) { super.bind(newObservable); } @Override public synchronized void unbind() { super.unbind(); } @Override public void accept(Boolean newValue) { setValue(newValue); } /** * Sets the value. If forceFire is true a change event will be fired even if * the value hasn't changed. * * @param value the value * @param forceFire whether to force a change event */ public void set(boolean value, boolean forceFire) { if (forceFire && get() == value) { fireValueChangedEvent(); } else { set(value); } } }
<gh_stars>0 const { MessageEmbed } = require("discord.js"); const { getGuildById } = require("../../utils/functions"); module.exports = { name: "messageUpdate", async execute(bot, oldMsg, newMsg) { if (!newMsg.guild) return; if (!newMsg.guild.me.hasPermission("MANAGE_WEBHOOKS")) { return; } const webhook = await bot.getWebhook(newMsg.guild); if (!webhook) return; const guild = await getGuildById(newMsg.guild.id); const blacklistedWords = guild.blacklistedwords; if (!oldMsg.content || !newMsg.content) { return; } if (newMsg.author?.id === bot.user.id) return; if (oldMsg.content === newMsg.content) return; if (blacklistedWords !== null && blacklistedWords[0]) { blacklistedWords.forEach((word) => { if (newMsg.content.toLowerCase().includes(word.toLowerCase())) { newMsg.delete(); return newMsg .reply( "You used a bad word the admin has set, therefore your message was deleted!" ) .then((msg) => { setTimeout(() => { msg.delete(); }, 5000); }); } }); } const pOldMsg = oldMsg.content.length > 1024 ? `${oldMsg.content.slice(0, 1010)}...` : oldMsg; const PNewMsg = newMsg.content.length > 1024 ? `${newMsg.content.slice(0, 1010)}...` : newMsg; const messageLink = `https://discord.com/channels/${newMsg.guild.id}/${newMsg.channel.id}/${newMsg.id}`; const embed = new MessageEmbed() .setTitle(`Message updated in **${newMsg.channel.name}**`) .setDescription( `Message send by **${newMsg.author.tag}** was edited [jump to message](${messageLink})` ) .addField("**Old Message**", `${pOldMsg}`) .addField("**New Message**", `${PNewMsg}`) .setColor("ORANGE") .setTimestamp(); webhook.send(embed); }, };
<filename>server/config/instagram.js var passport = require('passport'), InstagramStrategy = require('passport-instagram'); module.exports = function() { passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(obj, done) { done(null, obj); }); passport.use(new InstagramStrategy({ clientID : '90ba6e4257404b0e87e28d9297d6ad93', clientSecret : '236275c7dce24640b986e4f7ed8f0fe5', callbackURL : 'http://www.supercarsta.com/callback' }, function(accessToken, refreshToken, profile, done) { console.log(accessToken,'!!!!!!!!!!!!!!!!!\n'); var userInfo = { user_token: accessToken, user_name:profile.username, user_picture:profile._json.data.profile_picture, user_id:profile._json.data.id, user_bio:profile._json.data.bio, user_counts:profile._json.data.counts }; return done(null, userInfo); })); };
import AuthActions from '../Actions/AuthActions'; import Options from '../Utils/Options'; export default{ getAccessToken: (code) => { fetch('http://www.reddit.api/api/proxy/token', { mode: 'same-origin', method: 'post', headers: { "Content-Type": "application/x-www-form-urlencoded" }, // TODO: Better way of defining this without a long string body: `grant_type=authorization_code&code=${code}` }).then((response) => { return response.json(); }).then((data) => { AuthActions.receivedAuthToken(data); }).catch((error) => { AuthActions.authTokenError(error); }) }, loadFrontPage: (id, listType) => { console.log('Loading front page...'); let accessToken = localStorage.getItem("AccessToken"); fetch(`https://oauth.reddit.com/api/v1/me`, { mode: 'cors', method: 'GET', headers: { "Content-Type": "application/x-www-form-urlencoded", "Authorization" : `bearer ${accessToken}` } }).then((response) => { if(response.status !== 401) return response.json(); else{ throw new Error("You need to refresh the token"); } }).then((data) => { console.log(data); }).catch((error) => { console.log(error.message); }) } }
module.exports = { extends: ['../.eslintrc',], plugins: ['cypress'], env: { 'cypress/globals': true, }, // TODO: change first two to error and fix. rules: { 'cypress/no-assigning-return-values': 'warn', 'cypress/no-unnecessary-waiting': 'warn', 'cypress/assertion-before-screenshot': 'warn', 'cypress/no-force': 'warn', 'require-data-selectors': 'off', }, }
#!/bin/bash ########################################################################## # This is the EOSIO automated install script for Linux and Mac OS. # This file was downloaded from https://github.com/EOSIO/eos # # Copyright (c) 2017, Respective Authors all rights reserved. # # After June 1, 2018 this software is available under the following terms: # # The MIT License # # 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. # # https://github.com/EOSIO/eos/blob/master/LICENSE ########################################################################## SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" function usage() { printf "\\tUsage: %s \\n\\t[Build Option -o <Debug|Release|RelWithDebInfo|MinSizeRel>] \\n\\t[CodeCoverage -c] \\n\\t[Doxygen -d] \\n\\t[CoreSymbolName -s <1-7 characters>] \\n\\t[Avoid Compiling -a]\\n\\n" "$0" 1>&2 exit 1 } ARCH=$( uname ) if [ "${SOURCE_DIR}" == "${PWD}" ]; then BUILD_DIR="${PWD}/build" else BUILD_DIR="${PWD}" fi CMAKE_BUILD_TYPE=Release DISK_MIN=20 DOXYGEN=false ENABLE_COVERAGE_TESTING=false CORE_SYMBOL_NAME="SYS" START_MAKE=true TEMP_DIR="/tmp" TIME_BEGIN=$( date -u +%s ) VERSION=1.2 txtbld=$(tput bold) bldred=${txtbld}$(tput setaf 1) txtrst=$(tput sgr0) if [ $# -ne 0 ]; then while getopts ":cdo:s:ah" opt; do case "${opt}" in o ) options=( "Debug" "Release" "RelWithDebInfo" "MinSizeRel" ) if [[ "${options[*]}" =~ "${OPTARG}" ]]; then CMAKE_BUILD_TYPE="${OPTARG}" else printf "\\n\\tInvalid argument: %s\\n" "${OPTARG}" 1>&2 usage exit 1 fi ;; c ) ENABLE_COVERAGE_TESTING=true ;; d ) DOXYGEN=true ;; s) if [ "${#OPTARG}" -gt 6 ] || [ -z "${#OPTARG}" ]; then printf "\\n\\tInvalid argument: %s\\n" "${OPTARG}" 1>&2 usage exit 1 else CORE_SYMBOL_NAME="${OPTARG}" fi ;; a) START_MAKE=false ;; h) usage exit 1 ;; \? ) printf "\\n\\tInvalid Option: %s\\n" "-${OPTARG}" 1>&2 usage exit 1 ;; : ) printf "\\n\\tInvalid Option: %s requires an argument.\\n" "-${OPTARG}" 1>&2 usage exit 1 ;; * ) usage exit 1 ;; esac done fi if [ ! -d "${SOURCE_DIR}/.git" ]; then printf "\\n\\tThis build script only works with sources cloned from git\\n" printf "\\tPlease clone a new eos directory with 'git clone https://github.com/EOSIO/eos --recursive'\\n" printf "\\tSee the wiki for instructions: https://github.com/EOSIO/eos/wiki\\n" exit 1 fi pushd "${SOURCE_DIR}" &> /dev/null STALE_SUBMODS=$(( $(git submodule status --recursive | grep -c "^[+\-]") )) if [ $STALE_SUBMODS -gt 0 ]; then printf "\\n\\tgit submodules are not up to date.\\n" printf "\\tPlease run the command 'git submodule update --init --recursive'.\\n" exit 1 fi printf "\\n\\tBeginning build version: %s\\n" "${VERSION}" printf "\\t%s\\n" "$( date -u )" printf "\\tUser: %s\\n" "$( whoami )" printf "\\tgit head id: %s\\n" "$( cat .git/refs/heads/master )" printf "\\tCurrent branch: %s\\n" "$( git rev-parse --abbrev-ref HEAD )" printf "\\n\\tARCHITECTURE: %s\\n" "${ARCH}" popd &> /dev/null if [ "$ARCH" == "Linux" ]; then if [ ! -e /etc/os-release ]; then printf "\\n\\tEOSIO currently supports Amazon, Centos, Fedora, Mint & Ubuntu Linux only.\\n" printf "\\tPlease install on the latest version of one of these Linux distributions.\\n" printf "\\thttps://aws.amazon.com/amazon-linux-ami/\\n" printf "\\thttps://www.centos.org/\\n" printf "\\thttps://start.fedoraproject.org/\\n" printf "\\thttps://linuxmint.com/\\n" printf "\\thttps://www.ubuntu.com/\\n" printf "\\tExiting now.\\n" exit 1 fi OS_NAME=$( cat /etc/os-release | grep ^NAME | cut -d'=' -f2 | sed 's/\"//gI' ) case "$OS_NAME" in "Amazon Linux AMI") FILE="${SOURCE_DIR}/scripts/eosio_build_amazon.sh" CXX_COMPILER=g++ C_COMPILER=gcc MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf export LLVM_DIR=${HOME}/opt/wasm/lib/cmake/llvm export CMAKE=${HOME}/opt/cmake/bin/cmake export PATH=${HOME}/opt/mongodb/bin:$PATH ;; "CentOS Linux") FILE="${SOURCE_DIR}/scripts/eosio_build_centos.sh" CXX_COMPILER=g++ C_COMPILER=gcc MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf export LLVM_DIR=${HOME}/opt/wasm/lib/cmake/llvm export CMAKE=${HOME}/opt/cmake/bin/cmake export PATH=${HOME}/opt/mongodb/bin:$PATH ;; "elementary OS") FILE="${SOURCE_DIR}/scripts/eosio_build_ubuntu.sh" CXX_COMPILER=clang++-4.0 C_COMPILER=clang-4.0 MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf export PATH=${HOME}/opt/mongodb/bin:$PATH ;; "Fedora") FILE="${SOURCE_DIR}/scripts/eosio_build_fedora.sh" CXX_COMPILER=g++ C_COMPILER=gcc MONGOD_CONF=/etc/mongod.conf export LLVM_DIR=${HOME}/opt/wasm/lib/cmake/llvm ;; "Linux Mint") FILE="${SOURCE_DIR}/scripts/eosio_build_ubuntu.sh" CXX_COMPILER=clang++-4.0 C_COMPILER=clang-4.0 MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf export PATH=${HOME}/opt/mongodb/bin:$PATH ;; "Ubuntu") FILE="${SOURCE_DIR}/scripts/eosio_build_ubuntu.sh" CXX_COMPILER=clang++-4.0 C_COMPILER=clang-4.0 MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf export PATH=${HOME}/opt/mongodb/bin:$PATH ;; "Debian GNU/Linux") FILE=${SOURCE_DIR}/scripts/eosio_build_ubuntu.sh CXX_COMPILER=clang++-4.0 C_COMPILER=clang-4.0 MONGOD_CONF=${HOME}/opt/mongodb/mongod.conf export PATH=${HOME}/opt/mongodb/bin:$PATH ;; *) printf "\\n\\tUnsupported Linux Distribution. Exiting now.\\n\\n" exit 1 esac export BOOST_ROOT="${HOME}/opt/boost" OPENSSL_ROOT_DIR=/usr/include/openssl fi if [ "$ARCH" == "Darwin" ]; then FILE="${SOURCE_DIR}/scripts/eosio_build_darwin.sh" CXX_COMPILER=clang++ C_COMPILER=clang MONGOD_CONF=/usr/local/etc/mongod.conf OPENSSL_ROOT_DIR=/usr/local/opt/openssl fi ${SOURCE_DIR}/scripts/clean_old_install.sh if [ $? -ne 0 ]; then printf "\\n\\tError occurred while trying to remove old installation!\\n\\n" exit -1 fi . "$FILE" printf "\\n\\n>>>>>>>> ALL dependencies sucessfully found or installed . Installing EOSIO\\n\\n" printf ">>>>>>>> CMAKE_BUILD_TYPE=%s\\n" "${CMAKE_BUILD_TYPE}" printf ">>>>>>>> ENABLE_COVERAGE_TESTING=%s\\n" "${ENABLE_COVERAGE_TESTING}" printf ">>>>>>>> DOXYGEN=%s\\n\\n" "${DOXYGEN}" if [ ! -d "${BUILD_DIR}" ]; then if ! mkdir -p "${BUILD_DIR}" then printf "Unable to create build directory %s.\\n Exiting now.\\n" "${BUILD_DIR}" exit 1; fi fi if ! cd "${BUILD_DIR}" then printf "Unable to enter build directory %s.\\n Exiting now.\\n" "${BUILD_DIR}" exit 1; fi if [ -z "$CMAKE" ]; then CMAKE=$( command -v cmake ) fi if ! "${CMAKE}" -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" -DCMAKE_CXX_COMPILER="${CXX_COMPILER}" \ -DCMAKE_C_COMPILER="${C_COMPILER}" -DWASM_ROOT="${WASM_ROOT}" -DCORE_SYMBOL_NAME="${CORE_SYMBOL_NAME}" \ -DOPENSSL_ROOT_DIR="${OPENSSL_ROOT_DIR}" -DBUILD_MONGO_DB_PLUGIN=true \ -DENABLE_COVERAGE_TESTING="${ENABLE_COVERAGE_TESTING}" -DBUILD_DOXYGEN="${DOXYGEN}" \ -DCMAKE_INSTALL_PREFIX="/usr/local/eosio" "${SOURCE_DIR}" then printf "\\n\\t>>>>>>>>>>>>>>>>>>>> CMAKE building EOSIO has exited with the above error.\\n\\n" exit -1 fi if [ "${START_MAKE}" == "false" ]; then printf "\\n\\t>>>>>>>>>>>>>>>>>>>> EOSIO has been successfully configured but not yet built.\\n\\n" exit 0 fi if ! make -j"${CPU_CORE}" then printf "\\n\\t>>>>>>>>>>>>>>>>>>>> MAKE building EOSIO has exited with the above error.\\n\\n" exit -1 fi TIME_END=$(( $(date -u +%s) - ${TIME_BEGIN} )) printf "\n\n${bldred}\t _______ _______ _______ _________ _______\n" printf '\t( ____ \( ___ )( ____ \\\\__ __/( ___ )\n' printf "\t| ( \/| ( ) || ( \/ ) ( | ( ) |\n" printf "\t| (__ | | | || (_____ | | | | | |\n" printf "\t| __) | | | |(_____ ) | | | | | |\n" printf "\t| ( | | | | ) | | | | | | |\n" printf "\t| (____/\| (___) |/\____) |___) (___| (___) |\n" printf "\t(_______/(_______)\_______)\_______/(_______)\n${txtrst}" printf "\\n\\tEOSIO has been successfully built. %02d:%02d:%02d\\n\\n" $(($TIME_END/3600)) $(($TIME_END%3600/60)) $(($TIME_END%60)) printf "\\tTo verify your installation run the following commands:\\n" print_instructions printf "\\tFor more information:\\n" printf "\\tEOSIO website: https://eos.io\\n" printf "\\tEOSIO Telegram channel @ https://t.me/EOSProject\\n" printf "\\tEOSIO resources: https://eos.io/resources/\\n" printf "\\tEOSIO Stack Exchange: https://eosio.stackexchange.com\\n" printf "\\tEOSIO wiki: https://github.com/EOSIO/eos/wiki\\n\\n\\n"
<reponame>lkc-adm/databricks-terraform<filename>vendor/github.com/terraform-providers/terraform-provider-azuread/azuread/helpers/graph/replication.go package graph import ( "fmt" "time" "github.com/Azure/go-autorest/autorest" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" "github.com/terraform-providers/terraform-provider-azuread/azuread/helpers/ar" ) func WaitForCreationReplication(f func() (interface{}, error)) (interface{}, error) { return (&resource.StateChangeConf{ Pending: []string{"404", "BadCast"}, Target: []string{"Found"}, Timeout: 5 * time.Minute, MinTimeout: 1 * time.Second, ContinuousTargetOccurence: 10, Refresh: func() (interface{}, string, error) { i, err := f() if err == nil { return i, "Found", nil } r, ok := i.(autorest.Response) if !ok { return i, "BadCast", nil // sometimes the SDK bubbles up an entirely empty object } if ar.ResponseWasNotFound(r) { return i, "404", nil } return i, "Error", fmt.Errorf("Error calling f, response was not 404 (%d): %v", r.StatusCode, err) }, }).WaitForState() }
#!/bin/bash cd ../src/main/ui/ NODE_ENV="LOCAL" LOCAL_SPRING_API="http://localhost:8080/api/" npm start
public class ArraySorter { public static int[] sortArrayAsc(int[] arr) { // Bubble sort algorithm for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } public static void main(String[] args) { int[] arr = {2, 4, 7, 1, 3}; int[] sortedArr = sortArrayAsc(arr); for (int x : sortedArr) { System.out.println(x); } } }
<reponame>gfpaiva/iddogs const Categories = [ { category: 'husky', key: 'husky', name: 'Husky', }, { category: 'labrador', key: 'labrador', name: 'Labrador', }, { category: 'hound', key: 'hound', name: 'Hound', }, { category: 'pug', key: 'pug', name: 'Pug', }, ]; export default Categories;
import React, { Component } from "react"; import Dropzone from "../dropzone/Dropzone"; import "./Upload.css"; import Progress from "../progress/Progress"; // import axios from "axios"; class Upload extends Component { constructor(props) { super(props); this.state = { files: [], uploading: false, uploadProgress: {}, successfullUploaded: false }; this.onFilesAdded = this.onFilesAdded.bind(this); this.uploadFiles = this.uploadFiles.bind(this); this.sendRequest = this.sendRequest.bind(this); this.renderActions = this.renderActions.bind(this); this.sendRequestwithChunks = this.sendRequestwithChunks.bind(this); } onFilesAdded(files) { this.setState(prevState => ({ files: prevState.files.concat(files) })); } async uploadFiles() { this.setState({ uploadProgress: {}, uploading: true }); const promises = []; this.state.files.forEach(file => { promises.push(this.sendRequest(file)); // promises.push(this.sendRequestwithChunks(file)); }); try { await Promise.all(promises); this.setState({ successfullUploaded: true, uploading: false }); } catch (e) { // Not Production ready! Do some error handling here instead... this.setState({ successfullUploaded: true, uploading: false }); } } sendRequestwithChunks(file) { return new Promise((resolve, reject) => { // const req = new XMLHttpRequest(); console.log(file); console.log("sendRequestwithChunks"); const fileReader = new FileReader(); fileReader.onload = function(readerEvt) { console.log("fileLoaded"); console.log(readerEvt); }; fileReader.onloadend = function(readerEvt) { console.log("fileLoadedend"); console.log(readerEvt); }; fileReader.onprogress = readerEvt => { console.log("progress"); console.log(readerEvt.target.result); }; fileReader.readAsArrayBuffer(file); }); } sendRequest(file) { return new Promise((resolve, reject) => { const req = new XMLHttpRequest(); req.upload.addEventListener("progress", event => { if (event.lengthComputable) { const copy = { ...this.state.uploadProgress }; copy[file.name] = { state: "pending", percentage: (event.loaded / event.total) * 100 }; this.setState({ uploadProgress: copy }); } }); req.upload.addEventListener("load", event => { const copy = { ...this.state.uploadProgress }; copy[file.name] = { state: "done", percentage: 100 }; this.setState({ uploadProgress: copy }); resolve(req.response); }); req.upload.addEventListener("error", event => { const copy = { ...this.state.uploadProgress }; copy[file.name] = { state: "error", percentage: 0 }; this.setState({ uploadProgress: copy }); reject(req.response); }); const formData = new FormData(); formData.append("file", file, file.name); console.log("hello"); req.open("POST", "http://localhost:8080/upload"); req.send(formData); }); } renderProgress(file) { const uploadProgress = this.state.uploadProgress[file.name]; if (this.state.uploading || this.state.successfullUploaded) { return ( <div className="ProgressWrapper"> <Progress progress={uploadProgress ? uploadProgress.percentage : 0} /> <img className="CheckIcon" alt="done" src="baseline-check_circle_outline-24px.svg" style={{ opacity: uploadProgress && uploadProgress.state === "done" ? 0.5 : 0 }} /> </div> ); } } renderActions() { if (this.state.successfullUploaded) { return ( <button onClick={() => { // axios // .post("localhost:8080/clean", { // "Access-Control-Allow-Origin": "*" // }) // .then(response => { // console.log(response); // this.setState({ files: [], successfullUploaded: false }); // }) const xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:8080/clean", false); xhr.send("formData"); this.setState({ files: [], successfullUploaded: false }); }} > Clear </button> ); } else { return ( <button disabled={this.state.files.length < 0 || this.state.uploading} onClick={this.uploadFiles} > Upload </button> ); } } render() { return ( <div className="Upload"> <span className="Title">Upload Files bitches</span> <div className="Content"> <div> <Dropzone onFilesAdded={this.onFilesAdded} disabled={this.state.uploading || this.state.successfullUploaded} /> </div> <div className="Files"> {this.state.files.map(file => { return ( <div key={file.name} className="Row"> <span className="Filename">{file.name}</span> {this.renderProgress(file)} </div> ); })} </div> </div> <div className="Actions">{this.renderActions()}</div> </div> ); } } export default Upload;
<reponame>marvelperseus/Real-Estate-website-frontend import React, { Component } from 'react'; import { observer } from 'mobx-react'; import { withStyles } from 'material-ui/styles'; import ArrowDownIcon from '@material-ui/icons/KeyboardArrowDown'; import MainListingFilters from '../MainListingFilters'; const styles = theme => ({ root: { display: 'flex', height: '46px', justifyContent: 'flex-end', alignItems: 'center', minWidth: '540px', backgroundColor: '#fff', }, filterItem: { display: 'flex', height: '100%', paddingLeft: '15px', paddingRight: '15px', alignItems: 'center', fontSize: '0.9rem', color: 'rgba(0,0,0,.7)', cursor: 'pointer', border: 'none', backgroundColor: 'transparent', transition: 'color .2s ease-in-out', '&:hover': { color: 'rgba(0,0,0,.9)', '& span svg': { backgroundColor: 'rgba(0,0,0,.6)', }, }, }, expandArrowWrapper: { display: 'flex', alignItems: 'center', marginLeft: '15px', overflow: 'visible', }, expandArrow: { display: 'flex', justifyContent: 'center', alignItems: 'center', height: '20px', width: '20px', fontSize: '1.1rem', backgroundColor: 'rgba(0,0,0,.4)', color: '#fff', borderRadius: '50%', padding: '2px', paddingTop: '4px', overflow: 'visible', transition: 'background-color .2s ease-in-out', }, mainFilters: { marginRight: 'auto', paddingLeft: '15px', }, }); @observer @withStyles(styles) class FineGrainListingsFilters extends Component { constructor(props) { super(props); this.state = { currentOpenFilter: '', }; } render() { const { classes, onFilterClick } = this.props; const { currentOpenFilter } = this.state; return ( <div className={classes.root}> <div className={classes.mainFilters}> <MainListingFilters /> </div> <button className={classes.filterItem} id="neighborhood" onClick={onFilterClick} > Neighborhood <span className={classes.expandArrowWrapper}> <ArrowDownIcon color="inherit" classes={{ root: classes.expandArrow }} /> </span> </button> <button className={classes.filterItem} id="price" onClick={onFilterClick} > Price <span className={classes.expandArrowWrapper}> <ArrowDownIcon color="inherit" classes={{ root: classes.expandArrow }} /> </span> </button> <button className={classes.filterItem} id="beds" onClick={onFilterClick} > Beds <span className={classes.expandArrowWrapper}> <ArrowDownIcon color="inherit" classes={{ root: classes.expandArrow }} /> </span> </button> <button className={classes.filterItem} id="baths" onClick={onFilterClick} > Baths <span className={classes.expandArrowWrapper}> <ArrowDownIcon color="inherit" classes={{ root: classes.expandArrow }} /> </span> </button> <button className={classes.filterItem} id="filters" onClick={onFilterClick} > Filters <span className={classes.expandArrowWrapper}> <ArrowDownIcon color="inherit" classes={{ root: classes.expandArrow }} /> </span> </button> </div> ); } } export default FineGrainListingsFilters;
#!/bin/bash export API_PATH="$1" export MLP_API_BASEPATH="http://127.0.0.1:8081/v1" export MERLIN_API_BASEPATH="http://127.0.0.1:8080/v1" kubectl port-forward --namespace=mlp svc/mlp 8081:8080 & MLP_SVC_PID=$! kubectl port-forward --namespace=mlp svc/merlin 8080 & MERLIN_SVC_PID=$! sleep 15 echo "Creating merlin project: e2e-test" curl "${MLP_API_BASEPATH}/projects" -d '{"name": "e2e-test", "team": "gojek", "stream": "gojek"}' sleep 5 cd ${API_PATH} for example in client/examples/*; do [[ -e $example ]] || continue echo $example go run $example/main.go done # TODO: Run python/sdk e2e test kill ${MLP_SVC_PID} kill ${MERLIN_SVC_PID}
GPUID=0 OUTDIR=outputs/permuted_MNIST_incremental_domain_100 REPEAT=10 N_PERMUTATION=100 mkdir -p $OUTDIR IBATCHLEARNPATH=/home/hikmat/Desktop/JWorkspace/CL/Continuum/ContinuumBenchmarks/MNIST/Continual-Learning-Benchmark EPOCHS=10 BATCH_SIZE=128 #128 python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --lr 0.0001 --offline_training | tee ${OUTDIR}/Offline.log python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --lr 0.0001 | tee ${OUTDIR}/Adam.log python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer SGD --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --lr 0.001 | tee ${OUTDIR}/SGD.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adagrad --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --lr 0.001 | tee ${OUTDIR}/Adagrad.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type customization --agent_name EWC_online --lr 0.0001 --reg_coef 250 | tee ${OUTDIR}/EWC_online.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type customization --agent_name EWC --lr 0.0001 --reg_coef 150 | tee ${OUTDIR}/EWC.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type regularization --agent_name SI --lr 0.0001 --reg_coef 10 | tee ${OUTDIR}/SI.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type regularization --agent_name L2 --lr 0.0001 --reg_coef 0.02 | tee ${OUTDIR}/L2.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type customization --agent_name Naive_Rehearsal_4000 --lr 0.0001 | tee ${OUTDIR}/Naive_Rehearsal_4000.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type customization --agent_name Naive_Rehearsal_16000 --lr 0.0001 | tee ${OUTDIR}/Naive_Rehearsal_16000.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer Adam --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type regularization --agent_name MAS --lr 0.0001 --reg_coef 0.1 | tee ${OUTDIR}/MAS.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer SGD --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type customization --agent_name GEM_4000 --lr 0.1 --reg_coef 0.5 | tee ${OUTDIR}/GEM_4000.log #python -u ${IBATCHLEARNPATH}/iBatchLearn.py --outdir $OUTDIR --gpuid $GPUID --repeat $REPEAT --optimizer SGD --n_permutation $N_PERMUTATION --no_class_remap --force_out_dim 10 --schedule $EPOCHS --batch_size $BATCH_SIZE --model_name MLP1000 --agent_type customization --agent_name GEM_16000 --lr 0.1 --reg_coef 0.5 | tee ${OUTDIR}/GEM_16000.log
// create the web component const MyDataList = { // render the component render: () => { // create a container element const element = document.createElement('div'); // get the list of data const data = MyDataList.data; // create a list element const list = document.createElement('ul'); // loop over the data and create a list item for each one for (let index = 0; index < data.length; index++) { const item = document.createElement('li'); item.textContent = data[index]; list.appendChild(item); } // add the list element to the container element element.appendChild(list); // return the container element return element; }, // set the data for the component setData: (data) => { MyDataList.data = data; } }
<reponame>1thorsten/timeset // Package for time related functions (ntp - gettime, windows - settime) package handleTime
<reponame>parmarsuraj99/objax<gh_stars>1-10 # Copyright 2020 Google LLC # # 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 # # https://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. __all__ = ['DEFAULT_GENERATOR', 'Generator', 'randint', 'normal', 'truncated_normal', 'uniform'] from typing import Optional, Tuple import jax.random as jr from objax.module import Module from objax.variable import RandomState, VarCollection class Generator(Module): """Random number generator module.""" def __init__(self, seed: int = 0): """Create a random key generator, seed is the random generator initial seed.""" super().__init__() self.initial_seed = seed self._key: Optional[RandomState] = None @property def key(self): """The random generator state (a tensor of 2 int32).""" if self._key is None: self._key = RandomState(self.initial_seed) return self._key def seed(self, seed: int = 0): """Sets a new random generator seed.""" self.initial_seed = seed if self._key is not None: self._key.seed(seed) def __call__(self): """Generate a new generator state.""" return self.key.split(1)[0] def vars(self, scope: str = '') -> VarCollection: self.key # Make sure the key is created before collecting the vars. return super().vars(scope) DEFAULT_GENERATOR = Generator(0) def normal(shape: Tuple[int, ...], *, mean: float = 0, stddev: float = 1, generator: Generator = DEFAULT_GENERATOR): """Returns a ``JaxArray`` of shape ``shape`` with random numbers from a normal distribution with mean ``mean`` and standard deviation ``stddev``.""" return jr.normal(generator(), shape=shape) * stddev + mean def randint(shape: Tuple[int, ...], low: int, high: int, generator: Generator = DEFAULT_GENERATOR): """Returns a ``JaxAarray`` of shape ``shape`` with random integers in {low, ..., high-1}.""" return jr.randint(generator(), shape=shape, minval=low, maxval=high) def truncated_normal(shape: Tuple[int, ...], *, stddev: float = 1, lower: float = -2, upper: float = 2, generator: Generator = DEFAULT_GENERATOR): """Returns a ``JaxArray`` of shape ``shape`` with random numbers from a normal distribution with mean 0 and standard deviation ``stddev`` truncated by (``lower``, ``upper``).""" return jr.truncated_normal(generator(), shape=shape, lower=lower, upper=upper) * stddev def uniform(shape: Tuple[int, ...], generator: Generator = DEFAULT_GENERATOR): """Returns a ``JaxArray`` of shape ``shape`` with random numbers from a uniform distribution [0, 1].""" return jr.uniform(generator(), shape=shape)
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.archive = void 0; var archive = { "viewBox": "0 0 1792 1792", "children": [{ "name": "path", "attribs": { "d": "M1088 832q0-26-19-45t-45-19h-256q-26 0-45 19t-19 45 19 45 45 19h256q26 0 45-19t19-45zM1664 640v960q0 26-19 45t-45 19h-1408q-26 0-45-19t-19-45v-960q0-26 19-45t45-19h1408q26 0 45 19t19 45zM1728 192v256q0 26-19 45t-45 19h-1536q-26 0-45-19t-19-45v-256q0-26 19-45t45-19h1536q26 0 45 19t19 45z" } }] }; exports.archive = archive;
#!/bin/bash sudo apt-get install python3-pil python3-pil.imagetk sudo pip3 install evdev sudo groupadd uinput sudo usermod -a -G uinput pi sudo cp 98-keyboard.rules /etc/udev/rules.d/ sudo udevadm control --reload sudo udevadm trigger sudo modprobe uinput echo "You should see these permissions: crw-rw---- 1 root uinput ... " ls -l /dev/uinput sudo cp multikey /usr/sbin sudo mkdir -p /usr/share/multikey sudo sudo cp keyboard.gif /usr/share/multikey/
<reponame>heylenz/python27 #!/usr/bin/env python ############################################################################ ## ## Copyright (C) 2004-2005 Trolltech AS. All rights reserved. ## ## This file is part of the example classes of the Qt Toolkit. ## ## This file may be used under the terms of the GNU General Public ## License version 2.0 as published by the Free Software Foundation ## and appearing in the file LICENSE.GPL included in the packaging of ## this file. Please review the following information to ensure GNU ## General Public Licensing requirements will be met: ## http://www.trolltech.com/products/qt/opensource.html ## ## If you are unsure which license is appropriate for your use, please ## review the following information: ## http://www.trolltech.com/products/qt/licensing.html or contact the ## sales department at <EMAIL>. ## ## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ## ############################################################################ from PySide import QtCore, QtGui, QtSql import connection class TableEditor(QtGui.QDialog): def __init__(self, tableName, parent=None): super(TableEditor, self).__init__(parent) self.model = QtSql.QSqlTableModel(self) self.model.setTable(tableName) self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) self.model.select() self.model.setHeaderData(0, QtCore.Qt.Horizontal, "ID") self.model.setHeaderData(1, QtCore.Qt.Horizontal, "First name") self.model.setHeaderData(2, QtCore.Qt.Horizontal, "Last name") view = QtGui.QTableView() view.setModel(self.model) submitButton = QtGui.QPushButton("Submit") submitButton.setDefault(True) revertButton = QtGui.QPushButton("&Revert") quitButton = QtGui.QPushButton("Quit") buttonBox = QtGui.QDialogButtonBox(QtCore.Qt.Vertical) buttonBox.addButton(submitButton, QtGui.QDialogButtonBox.ActionRole) buttonBox.addButton(revertButton, QtGui.QDialogButtonBox.ActionRole) buttonBox.addButton(quitButton, QtGui.QDialogButtonBox.RejectRole) submitButton.clicked.connect(self.submit) revertButton.clicked.connect(self.model.revertAll) quitButton.clicked.connect(self.close) mainLayout = QtGui.QHBoxLayout() mainLayout.addWidget(view) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("Cached Table") def submit(self): self.model.database().transaction() if self.model.submitAll(): self.model.database().commit() else: self.model.database().rollback() QtGui.QMessageBox.warning(self, "Cached Table", "The database reported an error: %s" % self.model.lastError().text()) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) if not connection.createConnection(): sys.exit(1) editor = TableEditor('person') editor.show() sys.exit(editor.exec_())
#!/bin/bash if [ "$1" != "" ]; then echo "joining network: $2 with interface $1" #sudo ifdown $1 sudo su <<EOF ifdown $1 #ifup $1 rm /var/run/wpa_supplicant/$1 wpa_supplicant -i $1 -c /home/pi/$1.conf -Dnl80211,wext dhclient $1 EOF iwconfig else echo "Usage: join_network.sh device ssid password" fi
import Vue from 'vue' import Vuex from 'vuex' import trackService from '@/services/track' Vue.use(Vuex) const store = new Vuex.Store({ state: { track: {}, trackList: [], searchQuery: '', showNotification: false, notificationIsError: false, notificationText: '', showLoader: false, showPlayer: false }, getters: { trackTitle (state) { if (!state.track.name) { return '' } return `${state.track.name} - ${state.track.artists[0].name}` } }, mutations: { setTrack (state, track) { state.track = track }, setTrackList (state, trackList) { state.trackList = trackList }, setSearchQuery (state, searchQuery) { state.searchQuery = searchQuery }, setShowNotification (state, payload) { if (payload) { state.showNotification = payload.showNotification state.notificationIsError = payload.notificationIsError state.notificationText = payload.notificationText } }, setShowLoader (state, showLoader) { state.showLoader = showLoader }, setShowPlayer (state, showPlayer) { state.showPlayer = showPlayer } }, actions: { getTrackById (context, payload) { return trackService.getById(payload.id) .then(res => { context.commit('setTrack', res) return res }) } } }) export default store
package br.com.tasklist.core.endpoint; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; //tasklist - 19/01/2018 - SUPERO @ApplicationPath("/api") public class ApplicationEndpoint extends Application { }
function ResetScoreboard() { let table = document.getElementsByTagName("table")[0]; table.getElementsByTagName("tbody")[0].innerHTML = table.rows[0].innerHTML; let tableOuter = document.getElementsByClassName("table")[0]; tableOuter.scrollTop = 0; } function AddPlayer(id, accountid, name, ping, job, health, hunger, thirst, admin) { let table = document.getElementsByTagName("table")[0]; let tableContent = table.getElementsByTagName("tbody")[0].innerHTML; table.getElementsByTagName("tbody")[0].innerHTML = tableContent + `<tr class="${job != "" ? "job-"+job:""} ${admin == 1 ? "is-admin":""}"> <td>#${accountid}</td> <td class="name">${name}</td> <td>${job}</td> <td> <span class="btn health">${health} %</span>&nbsp; <span class="btn hunger">${hunger} %</span>&nbsp; <span class="btn thirst">${thirst} %</span> </td> <td>${ping} ms</td> <td class="right"> <button class=" btn btn-level-0" onclick="spec(${id})">SPC</button>&nbsp; <button class=" btn btn-level-0" onclick="heal(${id})">HEAL</button>&nbsp; <button class=" btn btn-level-0" onclick="rez(${id})">REZ</button>&nbsp; <button class=" btn btn-level-0" onclick="cuff(${id})">CUFF</button>&nbsp; <button class=" btn btn-level-1" onclick="goto(${id})">GOTO</button>&nbsp; <button class=" btn btn-level-1" onclick="bring(${id})"> BRING</button>&nbsp; <button class=" btn btn-level-2" onclick="freeze(${id})">FRZ</button>&nbsp; <button class=" btn btn-level-2" onclick="ragdoll(${id})">RGD</button>&nbsp; <button class=" btn btn-level-3 btn-margin-left" onclick="kick(${id})">KICK</button>&nbsp; <button class=" btn btn-level-3" onclick="ban(${id})">BAN</button> </td> </tr>`; } function SecondsToTime(d) { d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor((d % 3600) / 60); var s = Math.floor((d % 3600) % 60); var hDisplay = h > 0 ? h + (h == 1 ? " hr, " : " hrs, ") : ""; var mDisplay = m > 0 ? m + (m == 1 ? " min, " : " mins, ") : ""; var sDisplay = s > 0 ? s + (s == 1 ? " sec" : " secs") : ""; return hDisplay + mDisplay + sDisplay; } function SetInformation(players, maxplayers) { let infoPlayers = document.getElementsByClassName("players")[0]; infoPlayers.getElementsByTagName( "small" )[0].innerHTML = `Players: ${players}/${maxplayers}`; } function heal(player) { window.ue.game.callevent("scoreboard:admin:heal", player); } function rez(player) { window.ue.game.callevent("scoreboard:admin:rez", player); } function cuff(player) { window.ue.game.callevent("scoreboard:admin:cuff", player); } function freeze(player) { window.ue.game.callevent("scoreboard:admin:freeze", player); } function ragdoll(player) { window.ue.game.callevent("scoreboard:admin:ragdoll", player); } function bring(player) { window.ue.game.callevent("scoreboard:admin:bring", player); } function goto(player) { window.ue.game.callevent("scoreboard:admin:goto", player); } function kick(player) { window.ue.game.callevent("scoreboard:admin:kick", player); } function ban(player) { window.ue.game.callevent("scoreboard:admin:ban", player); } function spec(player) { window.ue.game.callevent("scoreboard:admin:spectate", player); }
<reponame>ChaituKNag/react-form-element-hook<gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useReactFormElement = void 0; var _react = _interopRequireWildcard(require("react")); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } var useReactFormElement = function useReactFormElement() { var ref = (0, _react.useRef)(); var _useState = (0, _react.useState)(), _useState2 = _slicedToArray(_useState, 2), isValid = _useState2[0], setIsValid = _useState2[1]; var _useState3 = (0, _react.useState)(), _useState4 = _slicedToArray(_useState3, 2), value = _useState4[0], setValue = _useState4[1]; var handleChange = function handleChange(e) { setValue(e.target.value); if (ref.current.checkValidity()) { setIsValid(true); } else { setIsValid(false); } }; (0, _react.useEffect)(function () { if (ref.current) { ref.current.addEventListener('change', handleChange); if (ref.current.checkValidity()) { setIsValid(true); } else { setIsValid(false); } } return function () { ref.current.removeEventListener('change', handleChange); }; }, [ref.current]); (0, _react.useEffect)(function () { if (ref.current) { setValue(ref.current.value); } }, [ref.current]); return [ref, value, isValid]; }; exports.useReactFormElement = useReactFormElement;
<reponame>wuximing/dsshop import { __assign, __extends } from "tslib"; import GroupComponent from '../abstract/group-component'; import Theme from '../util/theme'; import { regionToBBox } from '../util/util'; var RegionAnnotation = /** @class */ (function (_super) { __extends(RegionAnnotation, _super); function RegionAnnotation() { return _super !== null && _super.apply(this, arguments) || this; } /** * @protected * 默认的配置项 * @returns {object} 默认的配置项 */ RegionAnnotation.prototype.getDefaultCfg = function () { var cfg = _super.prototype.getDefaultCfg.call(this); return __assign(__assign({}, cfg), { name: 'annotation', type: 'region', locationType: 'region', start: null, end: null, style: {}, defaultCfg: { style: { lineWidth: 0, fill: Theme.regionColor, opacity: 0.4, }, } }); }; RegionAnnotation.prototype.renderInner = function (group) { this.renderRegion(group); }; RegionAnnotation.prototype.renderRegion = function (group) { var start = this.get('start'); var end = this.get('end'); var style = this.get('style'); var bbox = regionToBBox({ start: start, end: end }); this.addShape(group, { type: 'rect', id: this.getElementId('region'), name: 'annotation-region', attrs: __assign({ x: bbox.x, y: bbox.y, width: bbox.width, height: bbox.height }, style), }); }; return RegionAnnotation; }(GroupComponent)); export default RegionAnnotation; //# sourceMappingURL=region.js.map
function hideelement( el, swapel, speed ) { var seconds = speed/2000; el.style.transition = "opacity "+seconds+"s ease"; el.style.opacity = 0; setTimeout(function() { el.style.display = 'none'; //bring in the new element after first one is collapsed swapel.style.display = 'flex'; swapel.style.opacity = 0; swapel.style.transition = "opacity "+seconds+"s ease"; swapel.style.opacity = 1; }, speed); }
package de.otto.edison.mongo.configuration; import com.mongodb.*; import com.mongodb.event.CommandListener; import de.otto.edison.status.domain.Datasource; import org.bson.codecs.configuration.CodecRegistry; import org.slf4j.Logger; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import java.util.List; import java.util.Objects; import java.util.stream.Stream; import static com.mongodb.MongoCredential.createCredential; import static de.otto.edison.status.domain.Datasource.datasource; import static java.util.Objects.nonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.stream.Collectors.toList; import static org.slf4j.LoggerFactory.getLogger; /** * Properties used to configure MongoDB clients. * * @since 1.0.0 */ @ConfigurationProperties(prefix = "edison.mongo") @Validated public class MongoProperties { private static final Logger LOG = getLogger(MongoProperties.class); /** * The MongoDB servers. Comma-separated list of host:port pairs. */ @NotEmpty private String[] host = {"localhost"}; /** * The MongoDB connection uri pattern */ private String uriPattern; /** * The MongoDB database. */ private String authenticationDb = ""; /** * The MongoDB database. */ @NotEmpty private String db; /** * database user name */ private String user = ""; /** * database user password */ private String password = ""; /** * database user password */ private boolean sslEnabled; /** * Represents preferred replica set members to which a query or command can be sent. */ @NotEmpty private String readPreference = "primaryPreferred"; /** * Represents preferred write concern to which a query or command can be sent. */ private String writeConcern; /** * Maximum time that a thread will block waiting for a connection. */ @Min(10) private int maxWaitTime = 5000; /** * Connection timeout in milliseconds. Must be &gt; 0 */ @Min(10) private int connectTimeout = 5000; /** * The default timeout in milliseconds to use for reading operations. */ @Min(10) private int defaultReadTimeout = 2000; /** * The default timeout in milliseconds to use for writing operations. */ @Min(10) private int defaultWriteTimeout = 2000; /** * Sets the server selection timeout in milliseconds, which defines how long the driver will wait for server selection to * succeed before throwing an exception. */ @Min(1) private int serverSelectionTimeout = 30000; @Valid private Status status = new Status(); /** * Connection pool properties. */ @Valid private Connectionpool connectionpool = new Connectionpool(); /** * Sets whether client server connections will be compressed. * Set to "true", to enable. * <p> * You need to add dependencies to your application in order to use certain compression algorithms: * <ul> * <li>for ZstdCompressor, add the dependency to com.github.luben:zstd-jni:1.4.4-9</li> * <li>for SnappyCompressor, add the dependency to org.xerial.snappy:snappy-java:172.16.17.32</li> * </ul> */ private boolean clientServerCompressionEnabled = false; public Status getStatus() { return status; } public void setStatus(final Status status) { this.status = status; } public int getDefaultReadTimeout() { return defaultReadTimeout; } public void setDefaultReadTimeout(int defaultReadTimeout) { this.defaultReadTimeout = defaultReadTimeout; } public int getDefaultWriteTimeout() { return defaultWriteTimeout; } public void setDefaultWriteTimeout(int defaultWriteTimeout) { this.defaultWriteTimeout = defaultWriteTimeout; } public List<Datasource> toDatasources() { return Stream.of(getHost()) .map(host -> datasource(host + "/" + getDb())) .collect(toList()); } public List<ServerAddress> getServers() { return Stream.of(host) .filter(Objects::nonNull) .map(this::toServerAddress) .filter(Objects::nonNull) .collect(toList()); } public String[] getHost() { return host; } public void setHost(final String[] host) { this.host = host; } public String getUriPattern() { return uriPattern; } public void setUriPattern(final String uriPattern) { this.uriPattern = uriPattern; } public String getAuthenticationDb() { return authenticationDb; } public void setAuthenticationDb(final String authenticationDb) { this.authenticationDb = authenticationDb; } public String getDb() { return db; } public void setDb(final String db) { this.db = db; } public String getUser() { return user; } public void setUser(final String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(final String password) { this.password = password; } public boolean isSslEnabled() { return sslEnabled; } public void setSslEnabled(final boolean sslEnabled) { this.sslEnabled = sslEnabled; } public String getReadPreference() { return readPreference; } public void setReadPreference(final String readPreference) { this.readPreference = readPreference; } public String getWriteConcern() { return writeConcern; } public void setWriteConcern(final String writeConcern) { this.writeConcern = writeConcern; } public int getMaxWaitTime() { return maxWaitTime; } public void setMaxWaitTime(final int maxWaitTime) { this.maxWaitTime = maxWaitTime; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(final int connectTimeout) { this.connectTimeout = connectTimeout; } public int getServerSelectionTimeout() { return serverSelectionTimeout; } public void setServerSelectionTimeout(final int serverSelectionTimeout) { this.serverSelectionTimeout = serverSelectionTimeout; } public Connectionpool getConnectionpool() { return connectionpool; } public void setConnectionpool(final Connectionpool connectionpool) { this.connectionpool = connectionpool; } public boolean isClientServerCompressionEnabled() { return clientServerCompressionEnabled; } public void setClientServerCompressionEnabled(boolean clientServerCompressionEnabled) { this.clientServerCompressionEnabled = clientServerCompressionEnabled; } public MongoClientSettings toMongoClientSettings(final CodecRegistry codecRegistry, final List<MongoCompressor> possibleCompressors, final List<CommandListener> commandListeners) { MongoClientSettings.Builder clientOptionsBuilder = MongoClientSettings.builder() .applyToSslSettings(builder -> builder.enabled(sslEnabled)) .codecRegistry(codecRegistry) .readPreference(ReadPreference.valueOf(readPreference)) .applyToConnectionPoolSettings(pool -> pool .minSize(connectionpool.getMinSize()) .maxSize(connectionpool.getMaxSize()) .maxConnectionIdleTime(connectionpool.getMaxIdleTime(), MILLISECONDS) .maxConnectionLifeTime(connectionpool.getMaxLifeTime(), MILLISECONDS) .maxWaitTime(maxWaitTime, MILLISECONDS)) .applyToSocketSettings(socket -> socket .connectTimeout(connectTimeout, MILLISECONDS)); if (nonNull(uriPattern) && !uriPattern.isBlank()) { clientOptionsBuilder .applyConnectionString(getConnectionString()) .applyToClusterSettings(cluster -> cluster .serverSelectionTimeout(serverSelectionTimeout, MILLISECONDS)); } else { clientOptionsBuilder.applyToClusterSettings(cluster -> cluster .hosts(getServers()) .serverSelectionTimeout(serverSelectionTimeout, MILLISECONDS)); if (useAuthorizedConnection()) { clientOptionsBuilder.credential(getMongoCredentials()); } } if (isClientServerCompressionEnabled()) { clientOptionsBuilder.compressorList(possibleCompressors); } if (nonNull(writeConcern)) { clientOptionsBuilder.writeConcern(WriteConcern.valueOf(writeConcern)); } if (nonNull(commandListeners)) { commandListeners.forEach(e->clientOptionsBuilder.addCommandListener(e)); } return clientOptionsBuilder.build(); } private ConnectionString getConnectionString() { final String connectionString = uriPattern.contains("%s:%s@") ? String.format(getUriPattern(), getUser(), getPassword()) : getUriPattern(); return new ConnectionString(connectionString); } private boolean useAuthorizedConnection() { return !getUser().isEmpty() && !getPassword().isEmpty(); } private MongoCredential getMongoCredentials() { return createCredential( getUser(), getAuthenticationDb(), getPassword().toCharArray() ); } private ServerAddress toServerAddress(final String server) { try { if (server.contains(":")) { final String[] hostNamePortPair = server.split(":"); return new ServerAddress(hostNamePortPair[0], Integer.parseInt(hostNamePortPair[1])); } else { return new ServerAddress(server); } } catch (final NumberFormatException e) { LOG.warn("Invalid portNumber: " + e.getMessage(), e); return null; } } /** * Creates a StatusDetailIndicator that checks the MongoDB connection through a ping command */ public static class Status { /** * Enable / disable the MongoDB StatusDetailIndicator */ private boolean enabled = true; public boolean isEnabled() { return enabled; } public void setEnabled(final boolean enabled) { this.enabled = enabled; } } public static class Connectionpool { /** * Maximum number of connections allowed per host. */ @Min(1) private int maxSize = 100; /** * The minimum number of connections per host. A value of <code>0</code> will create connections lazily. */ @Min(0) private int minSize = 2; /** * This multiplier, multiplied with the maxSize property, gives the maximum number of threads that may be waiting for a * connection to become available from the pool. */ @Min(1) private int blockedConnectionMultiplier = 2; /** * Maximum life time for a pooled connection. */ @Min(1) private int maxLifeTime = 100000; /** * Maximum idle time for a pooled connection. */ @Min(1) private int maxIdleTime = 10000; public int getMaxSize() { return maxSize; } public void setMaxSize(final int maxSize) { this.maxSize = maxSize; } public int getMinSize() { return minSize; } public void setMinSize(final int minSize) { this.minSize = minSize; } public int getBlockedConnectionMultiplier() { return blockedConnectionMultiplier; } public void setBlockedConnectionMultiplier(final int blockedConnectionMultiplier) { this.blockedConnectionMultiplier = blockedConnectionMultiplier; } public int getMaxLifeTime() { return maxLifeTime; } public void setMaxLifeTime(final int maxLifeTime) { this.maxLifeTime = maxLifeTime; } public int getMaxIdleTime() { return maxIdleTime; } public void setMaxIdleTime(final int maxIdleTime) { this.maxIdleTime = maxIdleTime; } } }
#!/bin/bash set -e CONF="/usr/local/etc/zabbix_server.conf.d" if [ -z ${DB_HOST} ]; then echo "No Default DB Host Provided. Assuming 'db'" DB_HOST="db" fi if [ -z ${DB_PORT} ]; then echo "No Default port for Db Provided. Assuming 5432." DB_PORT=5432 fi if [ -z ${DB_USER} ]; then echo "No Default User provided for Db. Assuming zabbix" DB_USER="zabbix" fi if [ -z ${DB_PASS} ]; then echo "No Default DB Password provided. Assuming zabbix" DB_PASS="zabbix" fi if [ -z ${DB_NAME} ]; then echo "No default db name provided. Assuming zabbix" DB_NAME="zabbix" fi cat <<EOT > $CONF/automatic.conf DBHost=${DB_HOST} DBPort=${DB_PORT} DBUser=${DB_USER} DBName=${DB_NAME} DBPassword=${DB_PASS} LogFile=/tmp/zabbix_server.log LogFileSize=1024 LogType=console ListenPort=10051 EOT if [ ! -z ${EVENT_EXPORT_DIR} ]; then echo "Export event flag reconized. Creating dir and set permissions if needed and configuring zabbix_server." if [[ ! -d ${EVENT_EXPORT_DIR} ]]; then mkdir -p ${EVENT_EXPORT_DIR} fi echo "ExportDir=${EVENT_EXPORT_DIR}" >> $CONF/automatic.conf fi if [[ ! -z ${EVENT_EXPORT_FILESIZE} ]]; then echo "Defining the filezie as ${EVENT_EXPORT_FILESIZE}" echo "ExportFileSize=${EVENT_EXPORT_FILESIZE} >> $CONF/autmoatic.conf" fi exec /usr/local/sbin/zabbix_server -f -c "/usr/local/etc/zabbix_server.conf"
#!/bin/sh curl -s -XDELETE "http://localhost:9200/test" echo curl -s -XPUT "http://localhost:9200/test/" -d '{ "settings": { "index.number_of_shards": 1, "index.number_of_replicas": 0 }, "mappings": { "type1": { "properties": { "name": { "type": "string" }, "number": { "type": "integer" } } } } }' echo for i in {0..100}; do curl -s -XPUT "localhost:9200/test/type1/$i" -d "{\"name\":\"rec $i\", \"number\":$i}"; done curl -s -XPOST "http://localhost:9200/test/_refresh" echo echo "Salt 123" curl -s "localhost:9200/test/type1/_search?pretty=true" -d '{ "query": { "match_all": {} }, "sort": { "_script": { "script": "random", "lang": "native", "type": "number", "params": { "salt": "123" } } } } ' | grep \"_id\" echo "Salt 123" curl -s "localhost:9200/test/type1/_search?pretty=true" -d '{ "query": { "match_all": {} }, "sort": { "_script": { "script": "random", "lang": "native", "type": "number", "params": { "salt": "123" } } } } ' | grep \"_id\" echo "Salt 124" curl -s "localhost:9200/test/type1/_search?pretty=true" -d '{ "query": { "match_all": {} }, "sort": { "_script": { "script": "random", "lang": "native", "type": "number", "params": { "salt": "124" } } } } ' | grep \"_id\" echo "No salt" curl -s "localhost:9200/test/type1/_search?pretty=true" -d '{ "query": { "match_all": {} }, "sort": { "_script": { "script": "random", "lang": "native", "type": "number" } } } ' | grep \"_id\" echo "No salt" curl -s "localhost:9200/test/type1/_search?pretty=true" -d '{ "query": { "match_all": {} }, "sort": { "_script": { "script": "random", "lang": "native", "type": "number" } } } ' | grep \"_id\" echo
// For loop to print numbers from 0 to 10 for(int i = 0; i <= 10; i++) { cout << i << endl; }
<filename>src/core/createRefectStore.js import createRefectEnhancer from './enhancer'; import createDefaultTaskMiddleware from './middleware'; import { compose, applyMiddleware, createStore } from 'redux'; import { combineRefectReducer, parseRefectEffects } from './parseRefect'; import { identity } from '../utils'; const defaultCustom = () => ({}); const noOp = () => {}; export default function createRefectStore(storeConfig = {}) { const { middlewares = [], enhancers = [], rootEffects = [], initReducers = identity, initialState, storeCreated = noOp, createTaskMiddleware = createDefaultTaskMiddleware } = storeConfig; const { effectors, putinReducers } = parseRefectEffects(rootEffects); const taskMiddleware = createTaskMiddleware(effectors); const finalCreateStore = compose( applyMiddleware(...middlewares, taskMiddleware), createRefectEnhancer(putinReducers), ...enhancers, )(createStore); const store = finalCreateStore(initReducers, initialState); store.runTask = taskMiddleware.runTask; storeCreated(store); return store; }
#!/bin/bash set -e if [ -x "$(command -v c_rehash)" ]; then # c_rehash is run here instead of update-ca-certificates because the latter requires root privileges # and the aks-operator container is run as non-root user. c_rehash fi aks-operator
/* Info: JavaScript for JavaScript Basics Lesson 3, JavaScript Loops, Arrays, Strings, Task 17*, Extract Element Content Author: Removed for reasons of anonymity Successfully checked as valid in JSLint Validator at: http://www.jslint.com/ and JSHint Validator at: http://www.jshint.com/ */ 'use strict'; function buildStringBuilder() { return { strs: [], len: 0, append: function (str) { this.strs[this.len++] = str; return this; }, toString: function () { return this.strs.join(""); } }; } function extractContent(text) { var extractedText, closeBraketIndex, extractedData; var textLen = text.length; extractedText = buildStringBuilder(); closeBraketIndex = text.indexOf(">"); while (closeBraketIndex >= 1 && closeBraketIndex !== textLen - 1) { if (text[closeBraketIndex + 1] !== "<") { extractedData = text.substring(closeBraketIndex + 1, text.indexOf("<", closeBraketIndex + 1)); extractedText.append(extractedData).append(" "); } closeBraketIndex = text.indexOf(">", closeBraketIndex + 1); } return extractedText.toString(); } /* For html result view */ function extractContentHTML() { var output = document.getElementById("res"); var element = document.getElementById('test'); var data = element.innerHTML; var outText = extractContent(data); output.innerText = outText; } function extractContentByInput() { var output = document.getElementById("output"); var data = document.getElementById('data').value; var outText = extractContent(data); var elementP; elementP = document.createElement("p"); elementP.innerHTML = outText; output.appendChild(elementP); } /* For console result */ var htmlContents = [ "<p>Hello</p><a href='http://w3c.org'>W3C</a>", "<html><head><title>Sample site</title></head><body><div>text<div>more text</div>and more...</div>in body</body></html>" ]; var length = htmlContents.length; var m = 0; var extrText; for (m = 0; m < length; m = m + 1) { extrText = extractContent(htmlContents[m]); console.log(extrText); }
<reponame>jibrelnetwork/jibrel-contracts-jsapi<filename>src/utils/txUtils.js /** * @file Manages helper functions for sending of transactions * @author <NAME> <<EMAIL>> */ import Promise from 'bluebird' import Tx from 'ethereumjs-tx' import config from '../config' import add0x from '../utils/add0x' /** * @function signTx * * @description Signs raw transaction data with the specified private key * * @param {object} rawTx - Transaction data * @param {string} privateKey - Private key (64 hex symbols, without '0x' prefix) * * @returns {string} Serialized string of signed transaction */ export function signTx(rawTx, privateKey) { const tx = new Tx(rawTx) tx.sign(new Buffer(privateKey, 'hex')) const signedTx = tx.serialize().toString('hex') return add0x(signedTx) } /** * @async * @function getRawTx * * @description Gets raw transaction data * * @param {object} props - Properties * @param {string} props.address - Address of the transaction sender * @param {string} props.to - Address of the transaction receiver * @param {BigNumber} props.value - Transaction value * @param {BigNumber} [props.gasLimit] - Gas limit for the transaction * @param {BigNumber} [props.gasPrice] - Gas price for the transaction * @param {number} [props.nonce] - Nonce for the transaction * @param {string} [props.data] - Transaction data * * @returns Promise that will be resolved with raw transaction data */ export async function getRawTx(props) { const { address, to, gasLimit, gasPrice, nonce, data } = props const value = jWeb3.toHex(props.value) const [txGasPrice, txNonce, txGasLimit] = await Promise.all([ gasPrice || getGasPrice(), nonce || getTransactionCount(address), gasLimit || estimateGas({ data, to, value, from: address }), ]) return { to, data, value, nonce: jWeb3.toHex(txNonce), gasPrice: jWeb3.toHex(txGasPrice), gasLimit: jWeb3.toHex(txGasLimit), } } /** * @async * @function getContractRawTx * * @description Gets raw contract transaction data * * @param {object} payload - Payload object * @param {object} payload.props - API function properties * @param {string} payload.props.contractAddress - Contract address * @param {BigNumber} [payload.props.gasLimit] - Gas limit for the contract transaction * @param {BigNumber} [payload.props.gasPrice] - Gas price for the transaction * @param {number} [payload.props.nonce] - Nonce for the transaction * @param {string} payload.address - Address of the transaction sender * @param {function} payload.contractMethod - Contract method that used to send transaction * @param {array} payload.args - Contract method arguments * * @returns Promise that will be resolved with raw contract transaction data */ export async function getContractRawTx(payload) { const { props, address, contractMethod, args } = payload const { contractAddress, gasLimit, gasPrice, nonce } = props const [txData, txGasPrice, txNonce, txGasLimit] = await Promise.all([ contractMethod.getData(...args), gasPrice || getGasPrice(), nonce || getTransactionCount(address), gasLimit || estimateContractGas(contractMethod, args), ]) return { data: txData, to: contractAddress, nonce: jWeb3.toHex(txNonce), gasPrice: jWeb3.toHex(txGasPrice), gasLimit: jWeb3.toHex(txGasLimit), } } /** * @async * @function estimateGas * * @description Gets gas limit for the transaction * * @param {object} props - Properties of the web3.eth.estimateGas function * * @returns Promise that will be resolved with estimate gas for sending of the transaction */ export function estimateGas(props) { return Promise .promisify(jWeb3.eth.estimateGas)(props) .timeout(config.promiseTimeout, new Error('Can not get estimate gas')) } /** * @async * @function estimateContractGas * * @description Gets gas limit for the contract transaction * * @param {function} method - Contract method that used to send transaction * @param {array} args - Contract method argumets * * @returns Promise that will be resolved with estimate gas for sending of the contract transaction */ export function estimateContractGas(method, args) { return Promise .promisify(method.estimateGas)(...args) .timeout(config.promiseTimeout, new Error('Can not get estimate gas for contract method')) } /** * @async * @function getTransactionCount * * @description Gets transaction count for specified address * * @param {string} address - Ethereum address * @param {number|string} [defaultBlock] - Redefines of web3.eth.defaultBlock * * @returns Promise that will be resolved with nonce for sending the transaction */ export function getTransactionCount(address, defaultBlock) { const block = (defaultBlock == null) ? 'pending' : defaultBlock return Promise .promisify(jWeb3.eth.getTransactionCount)(address, block) .timeout(config.promiseTimeout, new Error('Can not get transaction count')) } /** * @function getGasPrice * * @description Request current gas price from ethereum node * * @returns Promise that will be resolved with gasPrice for sending the transaction */ export function getGasPrice() { return Promise .promisify(jWeb3.eth.getGasPrice)() .timeout(config.promiseTimeout, new Error('Can not get gas price')) }
#!/bin/bash puppet apply --modulepath ./modules manifests/default.pp
#!/usr/bin/env bash # Color files PFILE="$HOME/.config/polybar/material/colors.ini" RFILE="$HOME/.config/polybar/material/scripts/rofi/colors.rasi" # Change colors change_color() { # polybar sed -i -e 's/background = #.*/background = #FFFFFF/g' $PFILE sed -i -e 's/foreground = #.*/foreground = #2E2E2E/g' $PFILE sed -i -e 's/foreground-alt = #.*/foreground-alt = #656565/g' $PFILE sed -i -e "s/module-fg = #.*/module-fg = $MF/g" $PFILE sed -i -e "s/primary = #.*/primary = $AC/g" $PFILE sed -i -e 's/secondary = #.*/secondary = #E53935/g' $PFILE sed -i -e 's/alternate = #.*/alternate = #7cb342/g' $PFILE # rofi cat > $RFILE <<- EOF /* colors */ * { al: #00000000; bg: #FFFFFFFF; bga: ${AC}33; bar: ${MF}FF; fg: #2E2E2EFF; ac: ${AC}FF; } EOF polybar-msg cmd restart } if [[ $1 = "--amber" ]]; then MF="#2E2E2E" AC="#ffb300" change_color elif [[ $1 = "--blue" ]]; then MF="#2E2E2E" AC="#1e88e5" change_color elif [[ $1 = "--blue-gray" ]]; then MF="#FFFFFF" AC="#546e7a" change_color elif [[ $1 = "--brown" ]]; then MF="#FFFFFF" AC="#6d4c41" change_color elif [[ $1 = "--cyan" ]]; then MF="#2E2E2E" AC="#00acc1" change_color elif [[ $1 = "--deep-orange" ]]; then MF="#FFFFFF" AC="#f4511e" change_color elif [[ $1 = "--deep-purple" ]]; then MF="#FFFFFF" AC="#5e35b1" change_color elif [[ $1 = "--green" ]]; then MF="#FFFFFF" AC="#43a047" change_color elif [[ $1 = "--gray" ]]; then MF="#FFFFFF" AC="#757575" change_color elif [[ $1 = "--indigo" ]]; then MF="#FFFFFF" AC="#3949ab" change_color elif [[ $1 = "--light-blue" ]]; then MF="#2E2E2E" AC="#039be5" change_color elif [[ $1 = "--light-green" ]]; then MF="#2E2E2E" AC="#7cb342" change_color elif [[ $1 = "--lime" ]]; then MF="#2E2E2E" AC="#c0ca33" change_color elif [[ $1 = "--orange" ]]; then MF="#2E2E2E" AC="#fb8c00" change_color elif [[ $1 = "--pink" ]]; then MF="#FFFFFF" AC="#d81b60" change_color elif [[ $1 = "--purple" ]]; then MF="#FFFFFF" AC="#8e24aa" change_color elif [[ $1 = "--red" ]]; then MF="#FFFFFF" AC="#e53935" change_color elif [[ $1 = "--teal" ]]; then MF="#FFFFFF" AC="#00897b" change_color elif [[ $1 = "--yellow" ]]; then MF="#2E2E2E" AC="#fdd835" change_color else cat <<- _EOF_ No option specified, Available options: --amber --blue --blue-gray --brown --cyan --deep-orange --deep-purple --green --gray --indigo --light-blue --light-green --lime --orange --pink --purple --red --teal --yellow _EOF_ fi
package net.community.chest.net; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.SocketException; import java.nio.channels.SocketChannel; /** * Copyright 2007 as per GPLv2 * * Provides some default implementations for the {@link NetConnection} interface * * @author <NAME>. * @since Jul 4, 2007 7:45:51 AM */ public abstract class AbstractNetConnection implements NetConnection { protected AbstractNetConnection () { super(); } /* NOTE !!! override either this method or the other "attach" one * @see net.community.chest.net.NetConnection#attach(java.net.Socket) */ @Override public void attach (Socket sock) throws IOException { if (null == sock) throw new SocketException("No " + Socket.class.getName() + " instance to attach"); attach(sock.getChannel()); } /* NOTE !!! override either this method or the other "attach" one * @see net.community.chest.net.NetConnection#attach(java.nio.channels.SocketChannel) */ @Override public void attach (SocketChannel channel) throws IOException { if (null == channel) throw new SocketException("No " + SocketChannel.class.getName() + " instance to attach"); attach(channel.socket()); } /* NOTE !!! override either this method or the "getSocket" one * @see net.community.chest.net.NetConnection#getChannel() */ @Override public SocketChannel getChannel () { final Socket sock=getSocket(); return (null == sock) ? null : sock.getChannel(); } /* NOTE !!! override either this method or the "getChannel" one * @see net.community.chest.net.NetConnection#getSocket() */ @Override public Socket getSocket () { final SocketChannel channel=getChannel(); return (null == channel) ? null : channel.socket(); } /* NOTE !!! override either this method or the "detachSocket" one * @see net.community.chest.net.NetConnection#detachChannel() */ @Override public SocketChannel detachChannel () throws IOException { final Socket sock=detachSocket(); return (null == sock) ? null : sock.getChannel(); } /* NOTE !!! override either this method or the "detachChannel" one * @see net.community.chest.net.NetConnection#detachSocket() */ @Override public Socket detachSocket () throws IOException { final SocketChannel channel=detachChannel(); return (null == channel) ? null : channel.socket(); } /* * @see java.io.Closeable#close() */ @Override public void close () throws IOException { IOException exc=null; if (isOpen()) { try { flush(); } catch(IOException ioe) { exc = ioe; } } // see http://java.sun.com/j2se/1.5.0/docs/guide/net/articles/connection_release.html final Socket s=detachSocket(); if (s != null) { try { s.shutdownOutput(); } catch(IOException ioe) { if (null == exc) exc = ioe; } try(InputStream in=s.getInputStream()) { // no more data is expected, but consume it anyway for (int v=in.read(), numRead=0; v >= 0; numRead++, v=in.read()) { if (numRead < 0) numRead = 0; } } catch(IOException e) { // ignored } try { s.close(); } catch(IOException ioe) { if (null == exc) exc = ioe; } } if (exc != null) throw exc; } }
import React, { useState } from 'react'; // useState - função do React que retorna um Array de dois elementos // o primeiro elemento é um valor e o segundo uma função que controla esse valor const UseStateBasics = () => { const [title, setTitle] = useState("Ficar com certeza"); const onClickHandler = () => { if (title === "Ficar com certeza") { setTitle("Maluco beleza"); } else { setTitle("Ficar com certeza"); } } return ( <React.Fragment> <h1>{title}</h1> <input type="button" className="btn" onClick={onClickHandler} value="Mudar título" /> </React.Fragment> ); }; export default UseStateBasics;
import { gql } from 'apollo-server-express'; export default gql` extend type Mutation { addForward(input: AddForwardInput): AddForwardPayload! } type Forward { id: ID! createdAt: DateTime! user: User! url: String! method: String! statusCode: Int! success: Boolean! headers: [KeyValue!]! query: [KeyValue!]! contentType: String body: String } input AddForwardInput { webhookId: ID! url: String! method: String! statusCode: Int! headers: [KeyValueInput!]! query: [KeyValueInput!]! body: String } type AddForwardPayload { forward: Forward! webhook: Webhook! } `;
#!/bin/bash -e -o pipefail source ~/utils/invoke-tests.sh # MongoDB object-value database # installs last version of MongoDB Community Edition # https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/v echo "Installing mongodb..." brew tap mongodb/brew brew install mongodb-community invoke_tests "Common" "Mongo"
<filename>src/js/components/BoardSquare.js /** * Created by huangling on 21/01/2017. */ import React, {Component} from 'react'; import update from 'react/lib/update'; import {ItemTypes} from '../constants'; import {DropTarget, DragDropContext} from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; import Box from './Box'; const squareTarget = { drop(props, monitor, component) { const item = monitor.getItem(); const delta = monitor.getDifferenceFromInitialOffset(); const left = Math.round(item.left + delta.x); const top = Math.round(item.top + delta.y); component.moveBox(item.id, left, top); } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), }; } class BoardSquare extends Component { constructor(props) { super(props); this.state = { boxes: props.boxes }; } componentWillReceiveProps(nextProps) { if (nextProps.newBox) { this.setState({boxes: this.state.boxes.concat(nextProps.newBox)}); } } moveBox(id, left, top) { this.setState(update(this.state, { boxes: { [id]: { $merge: { left: left, top: top } } } })); } render() { const {hideSourceOnDrag, connectDropTarget} = this.props; const {boxes} = this.state; return connectDropTarget( <div className="board"> {boxes.map((box, index) => { const {left, top, title} = box; return ( <Box key={index} id={index} left={left} top={top} hideSourceOnDrag={hideSourceOnDrag}> {title} </Box> ); })} </div> ); } } export default DragDropContext(HTML5Backend)(DropTarget(ItemTypes.Text, squareTarget, collect)(BoardSquare));
<filename>minos-security-demo/src/main/java/cm/xxx/minos/leetcode/Solution6.java package cm.xxx.minos.leetcode; /** * Description: 滑动窗口 算法 * Author: lishangmin * Created: 2018-08-23 10:16 */ public class Solution6 { public int reverse(int x) { String temp = String.valueOf(x); StringBuilder builder = new StringBuilder(0); for (int i = temp.length() - 1; i > 0 ; i--) { builder.append(temp.charAt(i)); } if(x > 0) builder.append(temp.charAt(0)); int y = 0; try { y = Integer.valueOf(builder.toString()); }catch (NumberFormatException ignored){ } return x < 0 ? ~y + 1 : y; } public static void main(String[] args) { Solution6 solution6 = new Solution6(); System.out.println(solution6.reverse(901)); int x = Integer.MAX_VALUE; boolean isNegative = x < 0 ? true : false; int y = 0; int next; while (x != 0){ next = x % 10; x = x / 10; y = y * 10 + next; if (isNegative){ y = y > 0 ? 0:y; }else { y = y < 0 ? 0:y; } System.out.println(y); } } }
import { ControllerTestData } from "../types"; export declare type ShieldTestData = ControllerTestData & { workerName?: string; }; export declare const initShield: (shieldInstance: any, data?: ShieldTestData) => ShieldTestData;
from flask_restx import Api from flask import Blueprint from .main.controller.login_controller import api as login_ns from .main.controller.logout_controller import api as logout_ns from .main.controller.users_controller import api as users_ns from .main.controller.registration_controller import api as register_ns from .main.controller.stats_controller import api as stats_ns from .main.controller.refresh_token_controller import api as refresh_ns blueprint = Blueprint('server', __name__) server = Api( blueprint, title='Engineering Thesis Server', version='1.0', description='Server created for Engineering Thesis' ) server.add_namespace(login_ns, path='/login') server.add_namespace(logout_ns, path='/logout') server.add_namespace(users_ns, path='/user') server.add_namespace(register_ns, path='/register') server.add_namespace(stats_ns, path='/stats') server.add_namespace(refresh_ns, path='/refresh')
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Task } from '../task.model'; import { map } from 'rxjs/operators'; @Injectable() export class TaskService { constructor(private http: Http) { } // Store all tasks in this array. tasks: Task[] = []; // Implement this method to fetch tasks from a remote server. fetchTasks(url: string): void { this.http.get(url) .pipe( map(response => response.json()) ) .subscribe( (data: Task[]) => { this.tasks = data; }, error => { console.error('Error fetching tasks:', error); } ); } }
import getStorageMock from './getStorageMock'; const clearCompletedMock = (todos) => { const newTodos = todos.filter((el) => el.completed === false); getStorageMock.setItem('todos', newTodos); return newTodos; }; export default clearCompletedMock;
<filename>packageA/pages/matchBrand/matchBrand.js const util = require('../../../utils/util.js'); const api = require('../../../config/api.js'); import Toast from '../../../lib/vant-weapp/toast/toast'; const citys = { // '浙江': ['杭州', '宁波', '温州', '嘉兴', '湖州'], // '福建': [{name:'福州',code:11111}, {name:'厦门'}], }; Page({ /** * 页面的初始数据 */ data: { contentList: [ { name: '我的预估投资:', value: '', id: 0, placeholder: '请选择预估投资', gbCode: '' }, { name: '我想加盟的行业:', value: '', id: 1, placeholder: '请选择行业', gbCode: '', index:'' }, { name: '我想开店的城市:', value: '', id: 2, placeholder: '请选择城市', gbCode: '' } ], codeList: [ "BRAND_CATEGORY", "BRAND_INVESTMENT", "BRAND_AREA", "REGION_TAG" ], //获取筛选项的请求参数 dataList: [], isClickSubmit: true, areaList1: [], areaList2: [], areaList3: [], popTitle: '12312312', isShowPop1: false, isShowPop2: false, isShowPop3: false, gbCode: '', isReset:false, pageNum:1, total:'', allDataCitys:[], allTagList:[] }, backPage() { wx.navigateBack({ delta: 1 }) }, contentClick(e) { const { contentList } = this.data let newId = e.currentTarget.dataset.id let areaList1 let gbCode = contentList[0].gbCode if (newId == 0) { console.log(gbCode, 111111111111); areaList1 = [{ name: '10-20万', gbCode: 1 ,}, { name: '20-30万', gbCode: 2 }, { name: '30-50万', gbCode: 3 }, { name: '50万以上', gbCode: 4 }] this.setData({ isShowPop1: true, popTitle: '请选择预估投资', areaList1: areaList1, }) } else if (newId == 1) { this.setData({ isShowPop2: true, popTitle: '请选择行业', }) } else if (newId == 2) { this.setData({ isShowPop3: true, popTitle: '请选择城市', }) } }, confirmClick(event) { const { popTitle } = this.data const { contentList } = this.data if (popTitle == '请选择预估投资') { console.log(event.detail); contentList[0].value = event.detail.value.name contentList[0].gbCode = event.detail.value.gbCode this.setData({ contentList: contentList, isShowPop1: false, isShowPop2: false, isShowPop3: false, }) } else if (popTitle == '请选择行业') { contentList[1].value = event.detail.value.name contentList[1].gbCode = event.detail.value.gbCode contentList[1].index = event.detail.index this.setData({ contentList: contentList, isShowPop1: false, isShowPop2: false, isShowPop3: false, }) } else if (popTitle == '请选择城市') { console.log(event.detail.value[0], event.detail.value[1].name, event.detail.value[1].gbCode); contentList[2].value = event.detail.value[0] + '-' + event.detail.value[1].name contentList[2].gbCode = event.detail.value[1].gbCode this.setData({ contentList: contentList, isShowPop1: false, isShowPop2: false, isShowPop3: false, }) } this.setData({ isReset:true }) }, cancelClick() { this.setData({ isShowPop1: false, isShowPop2: false, isShowPop3: false, }) }, nowSubmit() { let that = this const {contentList,isReset,pageNum,total} = this.data if(!contentList[0].value){ Toast('请选择您的投资预估'); return } if(!contentList[1].value){ Toast('请选择您要加盟的行业'); return } if(!contentList[2].value){ Toast('请选择您要开店的城市'); return } let joinInvestMin let joinInvestMax let newPageNum if(contentList[0].gbCode==1){ joinInvestMin=10 joinInvestMax=20 }else if(contentList[0].gbCode==2){ joinInvestMin=20 joinInvestMax=50 }else if(contentList[0].gbCode==3){ joinInvestMin=30 joinInvestMax=50 }else if(contentList[0].gbCode==4){ joinInvestMin=50 joinInvestMax=0 } if(isReset){ newPageNum=1 }else{ if(pageNum<total/3){ newPageNum=pageNum+1 }else{ Toast('已展示全部,可更换条件重新匹配~'); return } } util.request(api.javaBrandHost + "brand/v1.0/phone/brandMatch", { "joinInvestMin": joinInvestMin, "joinInvestMax": joinInvestMax, "brandCategory": contentList[1].gbCode, "cityGbCode": contentList[2].gbCode, "pageNum": newPageNum }, 'POST') .then(res => { if (res.code == "0") { console.log(res.data.list); that.setData({ dataList: res.data.list, isReset:false, pageNum:newPageNum, total:res.data.total }) } }) .catch(err => { console.log(err.status, err.message); }); }, onChange(event) { const { picker, value, index } = event.detail; const { popTitle } = this.data if (popTitle == '请选择预估投资') { } else if (popTitle == '请选择行业') { } else if (popTitle == '请选择城市') { picker.setColumnValues(1, citys[value[0]]); } }, // 餐饮分类列表 initCatering() { const { codeList, contentList } = this.data let newTopTagList = [] util.request(api.baseUrl + "mobile/brand/listTags", { codeList: codeList }, 'POST') .then(res => { if (res.code == "0") { newTopTagList = res.data[0].tagList[0].childList newTopTagList.map((item) => { item.gbCode = item.id }) this.setData({ areaList2: newTopTagList, allTagList:res.data, popTitle: '请选择行业', },()=>{ this.getPersonas() }) } }) .catch(err => { console.log(err.status, err.message); }); }, cityInit() { const { contentList } = this.data util.request(api.javaBrandHost + "brand/v1.0/phone/cityList", 'get') .then(res => { if (res.code == "0") { res.data.map((item) => { citys[item.name] = item.cityList }) } this.setData({ allDataCitys:res.data },()=>{ this.initCatering() }) }) .catch(err => { console.log(err.status, err.message); }); }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.cityInit() }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, dataProcessing(allData){ const {allDataCitys,contentList,allTagList} = this.data let tagName='北京-东城区'.split('-') let defaultIndex0=0 let defaultIndex1=0 allData.map((item,indexTop)=>{ // 城市 if(item.tagTypeId=='ADDRESS'){ tagName=item.tagId.split('-') allDataCitys.map((itemCity,indexCity)=>{ itemCity.cityList.map((itemCityChild,indexChild)=>{ if(itemCityChild.name==tagName[1]){ contentList[2].value=item.tagId contentList[2].gbCode=itemCityChild.gbCode // console.log(indexTop,indexCity,indexChild); defaultIndex0=indexCity defaultIndex1=indexChild } }) }) } // 预估投资 if(item.tagTypeId=='BRAND_INVESTMENT'){ allTagList.map((itemBrand)=>{ if(itemBrand.classifyCode=='BRAND_INVESTMENT'){ itemBrand.tagList.map((itemBrandChild,index)=>{ if(itemBrandChild.id==item.tagId&&itemBrandChild.name=='10-20万'){ contentList[0].value=itemBrandChild.name } }) } }) } // 加盟行业 if(item.tagTypeId=='BRAND_CATEGORY'){ allTagList.map((itemBrand)=>{ if(itemBrand.classifyCode=='BRAND_CATEGORY'){ itemBrand.tagList[0].childList.map((itemBrandChild,index)=>{ if(itemBrandChild.id==item.tagId){ contentList[1].value=itemBrandChild.name contentList[1].index=index contentList[1].gbCode=itemBrandChild.id } }) } }) } }) console.log(defaultIndex0,defaultIndex1,citys); this.setData({ areaList3: [{ values: Object.keys(citys), className: 'column1', defaultIndex: defaultIndex0, }, { values: citys[tagName[0]], className: 'column2', defaultIndex: defaultIndex1, }], popTitle: '请选择城市', contentList:contentList }) }, getPersonas() { const { contentList } = this.data util.request(api.javaUserHost + "v2.0/app/sys/getPersonas", { userId:wx.getStorageSync("userId") },'POST') .then(res => { if (res.code == "0") { this.dataProcessing(res.data) } }) .catch(err => { console.log(err.status, err.message); }); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { return { title: '加盟好餐饮,就找餐盟严选!', } } })
package endpoint import ( "github.com/emilhauk/identity-api/store" "net/http" ) type Endpoints struct { LoginHandler http.HandlerFunc JwtHandler http.HandlerFunc LogoutHandler http.HandlerFunc WebHandler http.HandlerFunc PublicKeyHandler http.HandlerFunc RegisterHandler http.HandlerFunc } func NewEndpoints(dbStore *store.MongoStore, keyStore *store.RSAKeyStore) *Endpoints { endpoint := &Endpoints{ LoginHandler: func(w http.ResponseWriter, r *http.Request) { LoginHandler(w, r, dbStore, keyStore) }, JwtHandler: func(w http.ResponseWriter, r *http.Request) { JwtHandler(w, r, dbStore, keyStore) }, LogoutHandler: func(w http.ResponseWriter, r *http.Request) { LogoutHandler(w, r, dbStore, keyStore) }, WebHandler: func(w http.ResponseWriter, r *http.Request) { WebHandler(w, r) }, PublicKeyHandler: func(w http.ResponseWriter, r *http.Request) { PublicKeyHandler(w, r, keyStore) }, RegisterHandler: func(w http.ResponseWriter, r *http.Request) { RegisterHandler(w, r, dbStore) }, } return endpoint }
import React, { Component } from 'react'; import CitizenService from '../../../services/CitizenService' import './taskList.css' class TaskList extends Component { constructor(props) { super(props) this.state = { taskList: [], govtEntityAddress: '', title: '', description: '', expectedStartTimestamp: '', expectedDurationTimestamp: '', complaintHash: '', taskId: '', reviews: {} } this.newTaskListener = this.newTaskListener.bind(this); this.renderTaskTable = this.renderTaskTable.bind(this); this.submitNewtask = this.submitNewtask.bind(this); this.handleChange = this.handleChange.bind(this); this.startTask = this.startTask.bind(this); this.startTaskSetMetadata = this.startTaskSetMetadata.bind(this); this.updateTask = this.updateTask.bind(this); this.lastTask = this.lastTask.bind(this); this.getReview = this.getReview.bind(this); } componentWillMount() { this.citizenService = new CitizenService() this.citizenService.init(this.props.match.params.id).then(() => { this.citizenService.newTaskEvent(this.newTaskListener) }) console.log(this.props.match.params.id) this.myLocation = this.citizenService.getLocation() } newTaskListener(err, event) { console.log(event) let self = this this.citizenService.getTask( event.returnValues.complaintHash, Number(event.returnValues.taskId) ).then(res => { let actualStart = Date(res.timestamps[2]); let actualEnd = Date(res.timestamps[3]) let expectedStart = ( res.timestamps[0] / 60 / 60 / 24 ) + ' days' if(res.title === 'Assign POC') { expectedStart = Date(res.timestamps[0]) } self.setState({ taskList: [...self.state.taskList, { complaintHash: event.returnValues.complaintHash, taskId: Number(event.returnValues.taskId), title: res.title, description: res.description, govtEntityAddress: res.govtEntityAddress, expectedStartTimestamp: expectedStart, expectedDurationTimestamp: res.timestamps[1] + ' days', actualStartTimestamp: actualStart, actualEndTimestamp: actualEnd, status: res.status, }] }, () => {console.log(self.state)}) }) } startTaskSetMetadata(complaintHash, taskId) { this.state.complaintHash = complaintHash this.state.taskId = taskId } startTask(complaintHash, taskId) { this.citizenService.startTask(complaintHash, taskId) } updateTask(e) { e.preventDefault() this.citizenService.updateTaskDetails( this.state.complaintHash, this.state.taskId, { expectedStartTimestamp: this.state.expectedStartTimestamp, expectedDurationTimestamp: this.state.expectedDurationTimestamp } ) } getReview(complaintHash, taskId, msg) { if(msg === 'UnderReview') { console.log(complaintHash, taskId) let self = this; this.citizenService.getReview(complaintHash, taskId).then((res) => { console.log(res) let newState = Object.assign({}, this.state); let score = 0 if(Number(res.total) !== 0 && Number(res.sum) !== 0) { score = Number(res.sum) / Number(res.total) console.log(res.sum, res.total) } newState.reviews[complaintHash + taskId] = score + ' points'; console.log('fdsfdfd' + score) console.log(newState) self.setState(newState, console.log) }) } } endTask(complaintHash, taskId) { this.citizenService.endTask( complaintHash, taskId ) } renderTaskTable(item, index) { let self = this; let statusInfo = this.citizenService.statusResolve(item.status) console.log(statusInfo) let action = <button type="button" className="btn btn-primary btn-sm btn-block" data-toggle="modal" data-target="#exampleModalCenter" onClick={() => this.startTaskSetMetadata(item.complaintHash, item.taskId)}>Follow up</button> if(statusInfo.msg === 'Open') { action = <button type="button" className="btn btn-primary btn-sm btn-block" data-toggle="modal" data-target="#expectedDuration" onClick={() => this.startTaskSetMetadata(item.complaintHash, item.taskId)}>Update</button> } else if(statusInfo.msg === 'Viewed') { action = <button type="button" className="btn btn-primary btn-sm btn-block" onClick={() => this.startTask(item.complaintHash, item.taskId)}>Start</button> } else if(statusInfo.msg === 'UnderReview') { action = <button type="button" className="btn btn-primary btn-sm btn-block" onClick={() => this.endTask(item.complaintHash, item.taskId)}>Close</button> } else if(statusInfo.msg === 'Closed') { action = '' } let actionBox = <span className={`badge badge-${statusInfo.theme}`} onClick={() => this.getReview(item.complaintHash, item.taskId, statusInfo.msg)}>{statusInfo.msg}</span> return( <tr key={index}> <th scope="row">{index+1}</th> <td><a href={`/complaint-details/${self.props.match.params.id}/${item.complaintHash}`} target="_blank">{item.complaintHash.substring(0,14)}...</a></td> <td data-toggle="tooltip" data-placement="top" title={item.description}>{item.title}</td> <td>{item.expectedStartTimestamp}</td> <td>{item.expectedDurationTimestamp}</td> <td>{item.actualStartTimestamp}</td> <td>{item.actualEndTimestamp}</td> <td>{actionBox}<span className="badge badge-light">{this.state.reviews[item.complaintHash + item.taskId]}</span></td> <td>{action}</td> </tr> ) } handleChange(e) { this.state[e.target.name] = e.target.value; console.log(this.state) } submitNewtask(e) { e.preventDefault(); this.setState({ complaintHash: 'Complaint on its way' }) this.citizenService.addTask({ complaintHash: this.state.complaintHash, title: this.state.title, description: this.state.description, govtEntityAddress: this.state.govtEntityAddress }) } lastTask() { this.citizenService.lastTask( this.state.complaintHash, this.state.taskId, ) } render() { return( <section className="container"> <div className="card"> <div className="card-header"> Tasks </div> <div className="card-body"> <table className="table table-hover"> <thead> <tr> <th scope="col">#</th> <th scope="col">Complaint Hash</th> <th scope="col">Title</th> <th scope="col">Expected Start Time</th> <th scope="col">Expected Duration</th> <th scope="col">Actual Start Time</th> <th scope="col">Actual End Time</th> <th scope="col">Status</th> <th scope="col">Action</th> </tr> </thead> <tbody> {this.state.taskList.map(this.renderTaskTable)} </tbody> </table> </div> </div> <div className="modal fade bd-example-modal-lg" id="exampleModalCenter" tabIndex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div className="modal-dialog modal-dialog-centered modal-lg" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLongTitle">Complaint Follow Up</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <div className="form-group row"> <div className="col-sm-12"> <button type="button" className="btn btn-danger btn-lg btn-block" onClick={this.lastTask}>End of Complaint</button> </div> </div> <h3 className="or-big">or</h3> <h3>Add a follow up</h3> <form onSubmit={this.submitNewtask}> <div className="form-group row"> <label htmlFor="govtEntityAddress" className="col-sm-2 col-form-label">Allocated to</label> <div className="col-sm-10"> <input type="text" className="form-control" id="govtEntityAddress" name="govtEntityAddress" placeholder="0x04b2b54197e68642C6C7216dc7F693e144857A0D" onChange={this.handleChange}/> </div> </div> <div className="form-group row"> <label htmlFor="title" className="col-sm-2 col-form-label">Title</label> <div className="col-sm-10"> <input type="text" className="form-control" id="title" name="title" placeholder="brief about this task" onChange={this.handleChange}/> </div> </div> <div className="form-group row"> <label htmlFor="description" className="col-sm-2 col-form-label">Description</label> <div className="col-sm-10"> <textarea className="form-control" id="description" name="description" placeholder="add description to the follow up" onChange={this.handleChange}></textarea> <small id="passwordHelpBlock" className="form-text text-muted"> Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji. </small> </div> </div> <div className="form-group row"> <div className="col-sm-12"> <button type="submit" className="btn btn-success btn-lg btn-block">Open Task</button> </div> </div> </form> </div> </div> </div> </div> <div className="modal fade" id="expectedDuration" tabIndex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div className="modal-dialog modal-dialog-centered" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLongTitle">Add expected time to complete</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <form onSubmit={this.updateTask}> <div className="form-group row"> <label htmlFor="expectedStartTimestamp" className="col-sm-3 col-form-label">Expected Start Time</label> <div className="col-sm-9"> <input type="text" className="form-control" id="expectedStartTimestamp" name="expectedStartTimestamp" placeholder="25 July 2018" onChange={this.handleChange}/> <small id="passwordHelpBlock" className="form-text text-muted"> This is an expected start date of this task. </small> </div> </div> <div className="form-group row"> <label htmlFor="expectedDurationTimestamp" className="col-sm-3 col-form-label">Duration</label> <div className="col-sm-9"> <input type="text" className="form-control" id="expectedDurationTimestamp" name="expectedDurationTimestamp" placeholder="3" onChange={this.handleChange}/> </div> </div> <div className="form-group row"> <div className="col-sm-12"> <button type="submit" className="btn btn-success btn-lg btn-block">Update</button> </div> </div> </form> </div> </div> </div> </div> </section> ) } } export default TaskList;
<reponame>uwplse/stng from stencil_ir import * import asp.codegen.ast_tools as ast_tools import sympy import random import re import logging ARRAYSIZE = 10000 AOFFSET = 99 def is_int(x): try: a = int(x) return True except Exception: return False class Interpreter(ast_tools.NodeVisitor): """ A concrete interpreter over the IR that uses symbolic values for array entries. """ def __init__(self, inputs, outputs): self.result = None self.inputs = inputs self.outputs = outputs self.state = {} self.initialize_state() def initialize_state(self): """ Initializes accessible variables/arrays. """ for x in self.inputs: if "[" in x[1]: # it is an array self.state[x[0]] = [sympy.sympify(x[0]+"_"+str(i)) for i in range(ARRAYSIZE)] else: # it's a scalar if x[1] == 'int': self.state[x[0]] = sympy.sympify(random.randint(1,9)) for x in self.outputs: if "[" in x[1]: # it is an array self.state[x[0]] = [sympy.sympify(x[0]+"_"+str(i)) for i in range(ARRAYSIZE)] logging.debug("Finished initializing interpreter state.") def outputs_changed(self): """ Check to see if any outputs are changed. """ outputs_changed = False for output in self.outputs: i = 0 while (i < ARRAYSIZE) and (self.state[output[0]][i] == sympy.sympify(output[0]+"_"+str(i))): i += 1 if i<ARRAYSIZE: outputs_changed = True logging.debug("Outputs have changed.") break return outputs_changed def interpret(self, tree): """ Top-level function for interpretation. """ tries_left = 10 while tries_left > 0: self.visit(tree) if self.outputs_changed(): break tries_left -= 1 self.initialize_state() if tries_left == 0: logging.info("WARNING: Interpreter may have exhausted all tries.") return self.state def visit_NumNode(self, node): return node.val def visit_VarNode(self, node): if node.name in self.state: return self.state[node.name] else: return node.name def visit_ArrExp(self, node): loc = self.visit(node.loc) logging.debug("Array access to loc %s", loc+AOFFSET) return self.state[node.name.name][loc+AOFFSET] def visit_BinExp(self, node): # if it's a conditional, we don't want to sympify, but rather to interpret it directly if node.op in ['<', '>', '==', '!=', '<=', '>=']: if node.op != '<': raise else: left = self.visit(node.left) right = self.visit(node.right) ret = left < right #print "binop conditional: ", tree_to_str(node), " aka ", left, "<", right, " evaluates to ", ret return ret ret = sympy.sympify("(("+str(self.visit(node.left))+")" + node.op +"("+str(self.visit(node.right))+"))") return ret def visit_Block(self, node): map(self.visit, node.body) def visit_WhileLoop(self, node): # we evaluate condition before entry while self.visit(node.test): self.visit(node.body) def visit_AssignExp(self, node): if type(node.lval) == VarNode: self.state[node.lval.name] = self.visit(node.rval) else: # it is an array self.state[node.lval.name.name][self.visit(node.lval.loc)+AOFFSET] = self.visit(node.rval) class Guesser(object): def __init__(self, inputs, outputs): self.postcondition = None self.inputs = inputs self.outputs = outputs def guess_postcondition(self, results): # do the simplest thing. for each output, find the first changed value and convert it to # a function of indices guess = {} for output in self.outputs: logging.debug("Finding first changed value for output %s", output[0]) if "[" in output[1]: # find changed value i = 0 while results[output[0]][i] == sympy.sympify(output[0]+"_"+str(i)): i += 1 logging.debug("first changed value in %s is at %s and is %s", output[0], i, results[output[0]][i]) template = str(results[output[0]][i]) # replace _XX with an idx generator for inp in self.inputs: template = re.sub(inp[0]+'_\d+', "%s[ptgen_%s()]" % (inp[0], inp[0]), template) logging.debug("replaced with: %s", template) guess[output[0]] = template return guess
<gh_stars>10-100 //##################################################################### // Copyright 2004-2012, <NAME>, <NAME>. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_WGL_PBUFFER.h> #ifdef WIN32 #include <iostream> using namespace PhysBAM; // pbuffer function prototypes static PFNWGLMAKECONTEXTCURRENTARBPROC wglMakeContextCurrentARB = 0; static PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0; static PFNWGLCREATEPBUFFERARBPROC wglCreatePbufferARB = 0; static PFNWGLDESTROYPBUFFERARBPROC wglDestroyPbufferARB = 0; static PFNWGLGETPBUFFERDCARBPROC wglGetPbufferDCARB = 0; static PFNWGLRELEASEPBUFFERDCARBPROC wglReleasePbufferDCARB = 0; static PFNWGLQUERYPBUFFERARBPROC wglQueryPbufferARB = 0; static PFNWGLBINDTEXIMAGEARBPROC wglBindTexImageARB = 0; static PFNWGLRELEASETEXIMAGEARBPROC wglReleaseTexImageARB = 0; static PFNWGLSETPBUFFERATTRIBARBPROC wglSetPbufferAttribARB = 0; static PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0; static PFNWGLGETPIXELFORMATATTRIBFVARBPROC wglGetPixelFormatAttribfvARB = 0; LRESULT CALLBACK MainWndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { return DefWindowProc(hwnd,uMsg,wParam,lParam); } bool OPENGL_PBUFFER::Create(int width, int height) { // record size pbufferWidth=width; pbufferHeight=height; // make a window WNDCLASSEX wndclass; // Initialize the entire structure to zero. char szMainWndClass[]="stupid_offscreen_reg_class"; memset (&wndclass, 0, sizeof(WNDCLASSEX)); wndclass.lpszClassName = szMainWndClass; wndclass.cbSize = sizeof(WNDCLASSEX); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = MainWndProc; wndclass.hInstance = GetModuleHandle(0); wndclass.hIcon = LoadIcon (0, IDI_APPLICATION); wndclass.hIconSm = LoadIcon (0, IDI_APPLICATION); wndclass.hCursor = LoadCursor (0, IDC_ARROW); wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH); RegisterClassEx (&wndclass); {std::stringstream ss; ss<<"done"<<std::endl; LOG::filecout(ss.str());} hwnd= CreateWindow ( szMainWndClass, // Class name "Hello", // Caption WS_OVERLAPPEDWINDOW, // Style CW_USEDEFAULT, // Initial x (use default) CW_USEDEFAULT, // Initial y (use default) CW_USEDEFAULT, // Initial x size (use default) CW_USEDEFAULT, // Initial y size (use default) 0, // No parent window 0, // No menu GetModuleHandle(0), //This program instance 0 //Creation parameters ); HDC dc=GetDC(hwnd); // give our new window a gl context PIXELFORMATDESCRIPTOR pfd;unsigned int selected_pf; pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR ); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_TYPE_RGBA; pfd.cColorBits = 0; pfd.cRedBits = 0; pfd.cGreenBits = 0; pfd.cBlueBits = 0; pfd.cRedShift = 0; pfd.cGreenShift = 0; pfd.cBlueShift = 0; pfd.cAlphaBits = 0; pfd.cAccumAlphaBits = 0; pfd.cAccumBits = 0; pfd.cAccumBlueBits = 0; pfd.cAccumRedBits = 0; pfd.cAccumGreenBits = 0; pfd.cDepthBits = 16; pfd.cStencilBits = 0; pfd.cAuxBuffers = 0; pfd.iLayerType = PFD_MAIN_PLANE; pfd.bReserved = 0; pfd.dwLayerMask = 0; pfd.dwVisibleMask = 0; pfd.dwDamageMask = 0; if(!(selected_pf = ChoosePixelFormat( dc, &pfd )))goto fail; if(!SetPixelFormat(dc,selected_pf,&pfd)) goto fail; hGLRC=wglCreateContext(dc); wglMakeCurrent(dc,hGLRC); //ShowWindow(hwnd, SW_SHOW); hGLDC=wglGetCurrentDC(); // check for extension and then get entry points entry points const char *str; PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB =(PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); if(!wglGetExtensionsStringARB)goto fail; str=wglGetExtensionsStringARB(hGLDC); if(!strstr(str,"WGL_ARB_pixel_format"))goto fail; if(!strstr(str,"WGL_ARB_pbuffer"))goto fail; #define INIT_ENTRY_POINT( funcname, type )\ funcname = (type) wglGetProcAddress(#funcname);\ if ( !funcname )\ LOG::cerr<<"#funcname() not initialized"<<std::endl; // Initialize WGL_ARB_pbuffer entry points. INIT_ENTRY_POINT(wglCreatePbufferARB, PFNWGLCREATEPBUFFERARBPROC); INIT_ENTRY_POINT(wglGetPbufferDCARB, PFNWGLGETPBUFFERDCARBPROC); INIT_ENTRY_POINT(wglReleasePbufferDCARB, PFNWGLRELEASEPBUFFERDCARBPROC); INIT_ENTRY_POINT(wglDestroyPbufferARB, PFNWGLDESTROYPBUFFERARBPROC); INIT_ENTRY_POINT(wglQueryPbufferARB, PFNWGLQUERYPBUFFERARBPROC); // Initialize WGL_ARB_pixel_format entry points. INIT_ENTRY_POINT(wglGetPixelFormatAttribivARB,PFNWGLGETPIXELFORMATATTRIBIVARBPROC); INIT_ENTRY_POINT(wglGetPixelFormatAttribfvARB,PFNWGLGETPIXELFORMATATTRIBFVARBPROC); INIT_ENTRY_POINT(wglChoosePixelFormatARB,PFNWGLCHOOSEPIXELFORMATARBPROC); {std::stringstream ss; ss<<"Made window and render context" << std::endl; LOG::filecout(ss.str());} // Get the pixel format unsigned int count = 0; int pixelFormat; int attr[] = { WGL_SUPPORT_OPENGL_ARB, TRUE, WGL_DRAW_TO_PBUFFER_ARB, TRUE, WGL_RED_BITS_ARB, 8, WGL_GREEN_BITS_ARB, 8, WGL_BLUE_BITS_ARB, 8, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, 24, WGL_DOUBLE_BUFFER_ARB, FALSE, 0 }; wglChoosePixelFormatARB(hGLDC, (const int*)attr, 0, 1, &pixelFormat, &count); if(count==0)goto fail; int pAttrib[] ={0}; // create the pbuffer if(!(hPBuffer = wglCreatePbufferARB(hGLDC, pixelFormat, width, height, pAttrib))) goto post_gl_init_fail; if(!(hPBufferDC=wglGetPbufferDCARB(hPBuffer))) goto post_gl_init_fail; if(!(hPBufferGLRC= wglCreateContext(hPBufferDC))) goto post_gl_init_fail; if(!wglMakeCurrent(hPBufferDC,hPBufferGLRC)) goto post_gl_init_fail; // At this point it worked return true; // otherwise we jumped to failure cases post_gl_init_fail: wglDeleteContext(hGLRC); fail: DestroyWindow(hwnd); return false; } void OPENGL_PBUFFER::Destroy() { wglReleaseTexImageARB(hPBuffer, WGL_FRONT_LEFT_ARB); wglDestroyPbufferARB(hPBuffer); wglDeleteContext(hPBufferGLRC); wglDeleteContext(hGLRC); DestroyWindow(hwnd); } #endif
<filename>2019/08-kosen/cry-kurukuru/solve.py<gh_stars>10-100 f = open('encrypted') enc = f.read().strip() f.close() L = len(enc) for k in range(1, L): for a in range(L): for b in range(L): if a == b: continue flag = list(enc) i = k for _ in range(L): s = (i+a)%L t = (i+b)%L flag[s], flag[t] = flag[t], flag[s] i = (i+k)%L flag = ''.join(flag) if flag.startswith('KosenCTF{'): print(flag) break
def deleteHashTableEntry(key, hashTable): if key in hashTable: del hashTable[key] hashTable = { "abc": [2, 3], "def": [4, 5] } deleteHashTableEntry("abc", hashTable) print(hashTable)
import React, { Component } from 'react'; import axios from 'axios'; class App extends Component { constructor(){ super(); this.state = { orders: [], }; this.onOrderSubmit = this.onOrderSubmit.bind(this); } onOrderSubmit(order) { axios.post('/orders', order) .then(response => { const orders = [...this.state.orders, response.data]; this.setState({ orders }); }) .catch(error => { console.log(error); }); } render(){ return( <OrderForm onOrderSubmit={this.onOrderSubmit} /> <OrderTable orders={this.state.orders} /> ); } } export default App;
import React, { ReactElement } from 'react'; import { Layout, Menu } from 'antd'; import { Link, history } from 'umi'; import styles from './index.less'; // import BreadCrumb from '@/components/BreadCrumb/BreadCrumb'; const { SubMenu, Item } = Menu; const { Header, Footer, Sider, Content } = Layout; interface Props {} export default function index(props: any): ReactElement { const { pathname } = history.location; const menuData = [ { name: '主页', path: '/' }, { name: '管理员', path: '/admin' }, { name: '轮播图管理', path: '/broadcast' }, { name: '菜谱管理', path: '/cookmenu' }, { name: '会员管理', path: '/vip' }, { name: '套餐管理', path: '/meal' }, ]; return ( <Layout className={styles.layout}> <Header>Header</Header> <Layout> <Sider> <Menu mode="inline" selectedKeys={[pathname]}> {menuData.map((item) => { return ( <Item key={item.path}> <Link to={item.path}>{item.name}</Link> </Item> ); })} </Menu> </Sider> <Content className={styles.content}> {/* <BreadCrumb /> */} {props.children} </Content> </Layout> <Footer>Footer</Footer> </Layout> ); }
#!/bin/bash echo "Creating directories and files..." echo "--" mkdir ~/.config/nvim mkdir ~/.config/nvim/general mkdir ~/.config/nvim/lua touch ~/.config/nvim/init.vim touch ~/.config/nvim/init.vim touch ~/.config/nvim/general/settings.vim touch ~/.config/nvim/general/maps.vim touch ~/.config/nvim/general/plugins.vim touch ~/.config/nvim/general/plugins-cfg.vim touch ~/.config/nvim/general/functions.vim touch ~/.config/nvim/general/simple-pairs.vim echo "Done!"
#!/bin/sh set -e [ -z "${GITHUB_PAT}" ] && exit 0 [ "${TRAVIS_BRANCH}" != "master" ] && exit 0 git config --global user.email "alex@brodersen.io" git config --global user.name "Alex Brodersen" git clone -b gh-pages https://${GITHUB_PAT}@github.com/${TRAVIS_REPO_SLUG}.git book-output cd book-output cp -r ../_book/* ./ git add --all * git commit -m "Update the book" || true git push -q origin gh-pages
#!/usr/bin/env bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" OCLDIR=$DIR/gpu-rodinia/opencl bm="backprop bfs cfd gaussian hotspot hotspot3D hybridsort lud \ nn nw pathfinder srad streamcluster" OUTDIR=$DIR/results-cpu mkdir $OUTDIR &>/dev/null cd $OCLDIR exe() { echo "++ $@" |& tee -a $OUTDIR/$b.txt ; \ $@ |& tee -a $OUTDIR/$b.txt ; } for b in $bm; do echo -n > $OUTDIR/$b.txt # clean output file echo "$(date) # running $b" cd $b make clean ; make TYPE=CPU for idx in `seq 1 15`; do exe ./run -p 0 -d 0 exe echo done cd $OCLDIR exe echo echo done
<reponame>yjfnypeu/Router-RePlugin package com.lzh.remote; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.lzh.nonview.router.Router; import com.lzh.nonview.router.anno.RouterRule; @RouterRule("main") public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClick(View view) { Button btn = (Button) view; Router.create(btn.getText().toString()).open(this); } }
<filename>java/ql/src/Likely Bugs/Nullness/NullAlways.java public void createDir(File dir) { if (dir != null || !dir.exists()) // BAD dir.mkdir(); } public void createDir(File dir) { if (dir != null && !dir.exists()) // GOOD dir.mkdir(); }
<reponame>jhonatanlteodoro/Crawler_Infojobs<filename>main.py from get_links_vagas import GetLinksVagas as glv from get_info_vagas import GetInfoVagas as giv links = glv() #Como exemplo vamos passar 3 links vagas = [] for vaga in range(3): vagas.append(giv(links.list_links_vagas[vaga])) print(vagas[0].nome) print(vagas[0].nome_empresa) print(vagas[0].desc_vaga) print(vagas[1].nome) print(vagas[1].nome_empresa) print(vagas[1].desc_vaga) print(vagas[2].nome) print(vagas[2].nome_empresa) print(vagas[2].desc_vaga) """ Este exemplo ainda possuí uma listagem limpa e muito menos exata de cada conteúdo raspado, isso pois foi feito sem usar regex e só com o bs4 e o python fica díficil limpar sem erros o conteúdo raspado """
//Defining map as a global variable to access from other functions var map; // https://kevinchoppin.dev/blog/animating-google-maps-directions-with-multiple-waypoints-in-javascript const directions = [ { lat: 34.7563765 , lng: -92.3318309 }, { lat: 35.1263774 , lng: -89.8045423 }, // { lat: 36.2338313 , lng: -86.703611 }, // { lat: 36.9725552 , lng: -84.1155966 }, // { lat: 38.4339201 , lng: -82.1693237 }, // { lat: 39.6852473 , lng: -79.7732146 }, // { lat: 39.947958 , lng: -79.4542589 }, // { lat: 39.9917291 , lng: -77.9286817 }, // { lat: 39.806433 , lng: -75.2387906 }, // { lat: 41.1968086 , lng: -73.8854128 }, // { lat: 41.317928 , lng: -72.249199 }, // { lat: 41.7098268 , lng: -70.1429758 }, // { lat: 42.1000729 , lng: -71.4700845 }, // { lat: 42.640172 , lng: -70.7019397 }, // { lat: 43.391334 , lng: -70.4909597 }, // { lat: 44.3518204 , lng: -68.9705371 }, // { lat: 44.5069281 , lng: -68.3930336 }, // { lat: 44.8495004 , lng: -67.0033628 }, // { lat: 44.7706603 , lng: -69.6763526 }, // { lat: 44.3876612 , lng: -71.1399709 }, // { lat: 44.5686578 , lng: -72.5335455 }, // { lat: 44.393356 , lng: -73.217636 }, // { lat: 44.9509478 , lng: -73.2673631 }, // { lat: 44.9481562 , lng: -74.4639507 }, // { lat: 44.0791125 , lng: -76.3097677 }, // { lat: 42.9026276 , lng: -76.8803233 }, // { lat: 42.2126316 , lng: -76.9717456 }, // { lat: 40.0449518 , lng: -78.5190902 }, // { lat: 38.6982234 , lng: -80.6634292 }, // { lat: 38.2118703 , lng: -84.7997532 }, // { lat: 37.7881535 , lng: -85.6726533 }, // { lat: 38.2790381 , lng: -85.7542876 }, // { lat: 36.9152794 , lng: -86.4339436 }, // { lat: 36.6036304 , lng: -88.1411703 }, // { lat: 37.0969259 , lng: -88.6949433 }, // { lat: 38.8642035 , lng: -91.3130142 }, // { lat: 39.06418509, lng: -96.17519956 }, // { lat: 39.01265424, lng: -99.88569756 }, // { lat: 39.77702275, lng: -105.1293486} ]; // Break up our coordinates into chunks of 25 to avoid rate limits // the chunks array contains a series of points for use with the // directions api let chunks = []; let chunkSize = 10; directions.forEach((waypoint, i) => { let pi = Math.floor(i / (chunkSize - 1)); chunks[pi] = chunks[pi] || []; if (chunks[pi].length === 0 && pi !== 0) { // make new chunks origin the same as last chunks destination chunks[pi] = [directions[i - 1]]; } chunks[pi].push(waypoint); }); function initMap () { //Enabling new cartography and themes google.maps.visualRefresh = true; //Setting starting options of map var mapOptions = { center: { lat: 37 , lng: -87 }, zoom: 4.5, scrollwheel: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; //Getting map DOM element var mapElement = document.getElementById('mapDiv'); //Creating a map with DOM element which is just obtained map = new google.maps.Map(mapElement, mapOptions); // build requests for api let requests = []; chunks.forEach((chunk) => { let origin = chunk[0]; let destination = chunk[chunk.length - 1]; // build waypoints without origin/destination let waypoints = chunk.slice(1, -1).map(waypoint => { return { location: new google.maps.LatLng(waypoint.lat, waypoint.lng), stopover: false } }); requests.push({ travelMode: 'DRIVING', origin: new google.maps.LatLng(origin.lat, origin.lng), destination: new google.maps.LatLng(destination.lat, destination.lng), waypoints: waypoints }); }); // return promise for each directions request function buildRoute(requests) { let directionsService = new google.maps.DirectionsService(); return Promise.all(requests.map((request) => { return new Promise(function(resolve) { directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { return resolve(result.routes[0].legs[0]); } }); }); })); } // build up a polyline of our route function animatePath(map, pathCoords) { let speed = 1000; // higher = slower/smoother let route = new google.maps.Polyline({ path: [], geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 2, editable: false, map: map }); let past = new google.maps.Polyline({ path: [], geodesic: true, strokeColor: '#00FF00', strokeOpacity: 0.5, strokeWeight: 2, editable: false, map: map }); // break into chunks for animation let chunk = Math.ceil(pathCoords.length / speed); let totalChunks = Math.ceil(pathCoords.length / chunk); let i = 1; let j = 0; let foo = 0; function step() { // redraw polyline with bigger chunk // route.setPath(pathCoords.slice(0, i * chunk)); i++; foo = Math.max(0,(i-100)*chunk); route.setPath(pathCoords.slice(0, i * chunk)); // past.setPath(pathCoords.slice(0, foo)); if (i <= totalChunks) { window.requestAnimationFrame(step); } } window.requestAnimationFrame(step); } // wait for directions to be returned, then animate the route buildRoute(requests).then((results) => { // flatten all paths into one set of coordinates let coords = results.flatMap((result) => { return result.steps.flatMap(step => step.path); }); console.log("coords %o", coords.length); console.log("coords %o", coords[0].lat()); // finally animate path of our route // animatePath(map, coords); }); } google.maps.event.addDomListener(window, 'load', initMap);
package org.datacontract.schemas._2004._07.EEN_Merlin_Backend_Core_BO_PODService; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for profileCooperationStagedev complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="profileCooperationStagedev"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="comment" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="stage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "profileCooperationStagedev", propOrder = { "comment", "stage" }) public class ProfileCooperationStagedevType { @XmlElementRef(name = "comment", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> comment; @XmlElementRef(name = "stage", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> stage; /** * Gets the value of the comment property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setComment(JAXBElement<String> value) { this.comment = value; } /** * Gets the value of the stage property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getStage() { return stage; } /** * Sets the value of the stage property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setStage(JAXBElement<String> value) { this.stage = value; } }
from flask import url_for from app.config import EMAIL_DOMAIN from app.dashboard.views.custom_alias import ( signer, verify_prefix_suffix, available_suffixes, ) from app.extensions import db from app.models import Mailbox, CustomDomain, Alias from app.utils import random_word from tests.utils import login def test_add_alias_success(flask_client): user = login(flask_client) db.session.commit() word = random_word() suffix = f".{word}@{EMAIL_DOMAIN}" suffix = signer.sign(suffix).decode() # create with a single mailbox r = flask_client.post( url_for("dashboard.custom_alias"), data={ "prefix": "prefix", "suffix": suffix, "mailboxes": [user.default_mailbox_id], }, follow_redirects=True, ) assert r.status_code == 200 assert f"Alias prefix.{word}@{EMAIL_DOMAIN} has been created" in str(r.data) alias = Alias.query.order_by(Alias.created_at.desc()).first() assert not alias._mailboxes def test_add_alias_multiple_mailboxes(flask_client): user = login(flask_client) db.session.commit() word = random_word() suffix = f".{word}@{EMAIL_DOMAIN}" suffix = signer.sign(suffix).decode() # create with a multiple mailboxes mb1 = Mailbox.create(user_id=user.id, email="<EMAIL>", verified=True) db.session.commit() r = flask_client.post( url_for("dashboard.custom_alias"), data={ "prefix": "prefix", "suffix": suffix, "mailboxes": [user.default_mailbox_id, mb1.id], }, follow_redirects=True, ) assert r.status_code == 200 assert f"Alias prefix.{word}@{EMAIL_DOMAIN} has been created" in str(r.data) alias = Alias.query.order_by(Alias.created_at.desc()).first() assert alias._mailboxes def test_not_show_unverified_mailbox(flask_client): """make sure user unverified mailbox is not shown to user""" user = login(flask_client) db.session.commit() Mailbox.create(user_id=user.id, email="<EMAIL>", verified=True) Mailbox.create(user_id=user.id, email="<EMAIL>", verified=False) db.session.commit() r = flask_client.get(url_for("dashboard.custom_alias")) assert "<EMAIL>" in str(r.data) assert "<EMAIL>" not in str(r.data) def test_verify_prefix_suffix(flask_client): user = login(flask_client) db.session.commit() CustomDomain.create(user_id=user.id, domain="test.com", verified=True) assert verify_prefix_suffix(user, "prefix", "@test.com") assert not verify_prefix_suffix(user, "prefix", "@abcd.com") word = random_word() suffix = f".{word}@{EMAIL_DOMAIN}" assert verify_prefix_suffix(user, "prefix", suffix) def test_available_suffixes(flask_client): user = login(flask_client) db.session.commit() CustomDomain.create(user_id=user.id, domain="test.com", verified=True) assert len(available_suffixes(user)) > 0 # first suffix is custom domain first_suffix = available_suffixes(user)[0] assert first_suffix[0] assert first_suffix[1] == "@test.com" assert first_suffix[2].startswith("@test.com")
#!/usr/bin/env bash set -e set -o pipefail set -u # dynamic environment variables: # VERSION_TAG={determined automatically}: Version tag in format ios-vX.X.X-pre.X # GITHUB_RELEASE=true: Upload to github # environment variables and dependencies: # - You must run "mbx auth ..." before running # - Set GITHUB_TOKEN to a GitHub API access token in your environment to use GITHUB_RELEASE # - The "github-release" command is required to use GITHUB_RELEASE function step { >&2 echo -e "\033[1m\033[36m* $@\033[0m"; } function finish { >&2 echo -en "\033[0m"; } trap finish EXIT buildPackageStyle() { local package=$1 style="" if [[ ${#} -eq 2 ]]; then style="$2" fi step "Building: make ${package} ${style}" FORMAT=${style} make ${package} step "Publishing ${package} with ${style}" local file_name="" if [ -z ${style} ] then ./platform/ios/scripts/publish.sh "${PUBLISH_VERSION}" file_name=mapbox-ios-sdk-${PUBLISH_VERSION}.zip else ./platform/ios/scripts/publish.sh "${PUBLISH_VERSION}" ${style} file_name=mapbox-ios-sdk-${PUBLISH_VERSION}-${style}.zip fi if [[ "${GITHUB_RELEASE}" == true ]]; then step "Uploading ${file_name} to GitHub" github-release upload \ --tag "ios-v${PUBLISH_VERSION}" \ --name ${file_name} \ --file "${BINARY_DIRECTORY}/${file_name}" > /dev/null else step "CREATED ${file_name} - skipping upload to Github" fi } export GITHUB_USER=maplibre export GITHUB_REPO=maplibre-gl-native export BUILDTYPE=Release export PACKAGE_FORMAT=xcframework VERSION_TAG=${VERSION_TAG:-''} PUBLISH_VERSION= BINARY_DIRECTORY='build/ios' GITHUB_RELEASE=${GITHUB_RELEASE:-false} BUILD_FOR_COCOAPODS=${BUILD_FOR_COCOAPODS:-false} PUBLISH_PRE_FLAG='' if [[ -z `which github-release` ]]; then step "Installing github-release…" brew install github-release if [ -z `which github-release` ]; then echo "Unable to install github-release. See: https://github.com/aktau/github-release" exit 1 fi fi if [[ ${GITHUB_RELEASE} = "true" ]]; then GITHUB_RELEASE=true # Assign bool, not just a string fi if [[ ${GITHUB_RELEASE} = "false" ]]; then GITHUB_RELEASE=false # Assign bool, not just a string fi if [[ ${BUILD_FOR_COCOAPODS} = "false" ]]; then BUILD_FOR_COCOAPODS=false # Assign bool, not just a string fi if [[ ${BUILD_FOR_COCOAPODS} = "true" ]]; then BUILD_FOR_COCOAPODS=true # Assign bool, not just a string fi if [[ -z ${VERSION_TAG} ]]; then step "Determining version number from most recent relevant git tag…" VERSION_TAG=$( git describe --tags --match=ios-v*.*.* --abbrev=0 ) echo "Found tag: ${VERSION_TAG}" fi if [[ $( echo ${VERSION_TAG} | grep --invert-match ios-v ) ]]; then echo "Error: ${VERSION_TAG} is not a valid iOS version tag" echo "VERSION_TAG should be in format: ios-vX.X.X-pre.X" if [[ "${GITHUB_RELEASE}" == true ]]; then exit 1 fi fi if github-release info --tag ${VERSION_TAG} | grep --quiet "draft: ✗"; then echo "Error: ${VERSION_TAG} has already been published on GitHub" echo "See: https://github.com/${GITHUB_USER}/${GITHUB_REPO}/releases/tag/${VERSION_TAG}" if [[ "${GITHUB_RELEASE}" == true ]]; then exit 1 fi fi if [[ "${GITHUB_RELEASE}" == true ]]; then PUBLISH_VERSION=$( echo ${VERSION_TAG} | sed 's/^ios-v//' ) git checkout ${VERSION_TAG} step "Deploying version ${PUBLISH_VERSION}…" else PUBLISH_VERSION=${VERSION_TAG} step "Building packages for version ${PUBLISH_VERSION} (Not deploying to Github)" fi npm install --ignore-scripts mkdir -p ${BINARY_DIRECTORY} if [[ "${GITHUB_RELEASE}" == true ]]; then step "Create GitHub release…" if [[ $( echo ${PUBLISH_VERSION} | awk '/[0-9]-/' ) ]]; then PUBLISH_PRE_FLAG='--pre-release' fi RELEASE_NOTES=$( ./platform/ios/scripts/release-notes.js github ) github-release release \ --tag "ios-v${PUBLISH_VERSION}" \ --name "ios-v${PUBLISH_VERSION}" \ --draft ${PUBLISH_PRE_FLAG} \ --description "${RELEASE_NOTES}" fi # Used for binary release on Github - includes events SDK buildPackageStyle "${PACKAGE_FORMAT}" "dynamic" echo "Binary artifact zip file: ${BINARY_ARTIFACT_ZIP_FILE}" echo "Binary artifact url: ${BINARY_ARTIFACT_URL}" if [[ !-z "${BINARY_ARTIFACT_URL}" ]]; then step "Creating Swift package…" rm -f Package.swift cp swift_package_template.swift Package.swift sed -i "s/__PACKAGE_URL__/${BINARY_ARTIFACT_URL}/g" Package.swift CHECKSUM=$(swift package compute-checksum ${BINARY_ARTIFACT_ZIP_FILE}) echo "Checksum: ${CHECKSUM}" sed -i "s/__PACKAGE_CHECKSUM__/${CHECKSUM}/g" Package.swift cat Package.swift fi if [[ ${BUILD_FOR_COCOAPODS} == true ]]; then # Used for Cocoapods/Carthage buildPackageStyle "${PACKAGE_FORMAT}" "dynamic" buildPackageStyle "${PACKAGE_FORMAT} SYMBOLS=NO" "stripped-dynamic" fi step "Finished deploying ${PUBLISH_VERSION} in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds"
<filename>typedb/stream/response_collector.py # # Copyright (C) 2021 Vaticle # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import queue from threading import Lock from typing import Generic, TypeVar, Dict, Optional, Union from uuid import UUID from grpc import RpcError from typedb.common.exception import TypeDBClientException, TRANSACTION_CLOSED R = TypeVar('R') class ResponseCollector(Generic[R]): def __init__(self): self._collectors: Dict[UUID, ResponseCollector.Queue[R]] = {} self._collectors_lock = Lock() def new_queue(self, request_id: UUID): with self._collectors_lock: collector: ResponseCollector.Queue[R] = ResponseCollector.Queue() self._collectors[request_id] = collector return collector def get(self, request_id: UUID) -> Optional["ResponseCollector.Queue[R]"]: return self._collectors.get(request_id) def close(self, error: Optional[RpcError]): with self._collectors_lock: for collector in self._collectors.values(): collector.close(error) def drain_errors(self) -> [RpcError]: errors = [] with self._collectors_lock: for collector in self._collectors.values(): errors.extend(collector.drain_errors()) return errors class Queue(Generic[R]): def __init__(self): self._response_queue: queue.Queue[Union[Response[R], Done]] = queue.Queue() def get(self, block: bool) -> R: response = self._response_queue.get(block=block) if response.message: return response.message elif response.error: raise TypeDBClientException.of_rpc(response.error) else: raise TypeDBClientException.of(TRANSACTION_CLOSED) def put(self, response: R): self._response_queue.put(Response(response)) def close(self, error: Optional[RpcError]): self._response_queue.put(Done(error)) def drain_errors(self) -> [RpcError]: errors = [] while not self._response_queue.empty(): response = self._response_queue.get(block = False) if response.error: errors.append(response.error) return errors class Response(Generic[R]): def __init__(self, value: R): self.message = value class Done: def __init__(self, error: Optional[RpcError]): self.error = error
#!/usr/bin/env bash set -e # colours YELLOW='\033[1;33m' NC='\033[0m' # no colour - reset console colour DOMAIN='m.thegulocal.com' SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" dev-nginx setup-cert ${DOMAIN} dev-nginx link-config ${SOURCE_DIR}/frontend.conf dev-nginx restart-nginx echo -e "💯 Done! You can now run frontend locally on https://${DOMAIN}" echo -e "👤 To setup Dotcom Identity Frontend please follow identity-platform README." echo -e "👋"
#!/bin/bash echo "Analyzing dart:ui library..." echo "Using analyzer from `which dartanalyzer`" dartanalyzer --version RESULTS=`dartanalyzer \ --options flutter/analysis_options.yaml \ --enable-experiment=non-nullable \ "$1out/host_debug_unopt/gen/sky/bindings/dart_ui/ui.dart" \ 2>&1 \ | grep -Ev "No issues found!" \ | grep -Ev "Analyzing.+out/host_debug_unopt/gen/sky/bindings/dart_ui/ui\.dart"` echo "$RESULTS" if [ -n "$RESULTS" ]; then echo "Failed." exit 1; fi echo "Analyzing flutter_frontend_server..." RESULTS=`dartanalyzer \ --packages=flutter/flutter_frontend_server/.packages \ --options flutter/analysis_options.yaml \ flutter/flutter_frontend_server \ 2>&1 \ | grep -Ev "No issues found!" \ | grep -Ev "Analyzing.+frontend_server"` echo "$RESULTS" if [ -n "$RESULTS" ]; then echo "Failed." exit 1; fi echo "Analyzing tools/licenses..." (cd flutter/tools/licenses && pub get) RESULTS=`dartanalyzer \ --packages=flutter/tools/licenses/.packages \ --options flutter/tools/licenses/analysis_options.yaml \ flutter/tools/licenses \ 2>&1 \ | grep -Ev "No issues found!" \ | grep -Ev "Analyzing.+tools/licenses"` echo "$RESULTS" if [ -n "$RESULTS" ]; then echo "Failed." exit 1; fi echo "Analyzing testing/dart..." flutter/tools/gn --unoptimized ninja -C out/host_debug_unopt sky_engine sky_services (cd flutter/testing/dart && pub get) RESULTS=`dartanalyzer \ --packages=flutter/testing/dart/.packages \ --options flutter/analysis_options.yaml \ flutter/testing/dart \ 2>&1 \ | grep -Ev "No issues found!" \ | grep -Ev "Analyzing.+testing/dart"` echo "$RESULTS" if [ -n "$RESULTS" ]; then echo "Failed." exit 1; fi echo "Analyzing testing/scenario_app..." (cd flutter/testing/scenario_app && pub get) RESULTS=`dartanalyzer \ --packages=flutter/testing/scenario_app/.packages \ --options flutter/analysis_options.yaml \ flutter/testing/scenario_app \ 2>&1 \ | grep -Ev "No issues found!" \ | grep -Ev "Analyzing.+testing/scenario_app"` echo "$RESULTS" if [ -n "$RESULTS" ]; then echo "Failed." exit 1; fi