text
stringlengths
1
1.05M
// https://cses.fi/problemset/task/1196/ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef tuple<ll,ll>ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vii> vvii; typedef priority_queue<ii,vii,greater<ii>> pq; int main() { ios::sync_with_stdio(0); cin.tie(0); int n,m,k; cin>>n>>m>>k; vvii g(n); for(int i=0;i<m;i++){ int u,v,w; cin>>u>>v>>w; u--;v--; g[u].push_back({w,v}); } int c=0; vi b(n,0); pq q; q.push({0,0}); while(true){ ll w,u; tie(w,u)=q.top(); q.pop(); if(b[u]>k)continue; if(u==n-1){ c++; cout<<w<<" \n"[c==k]; if(c==k)break; } b[u]++; for(auto z:g[u]){ ll x,v; tie(x,v)=z; if (b[v]>k)continue; q.push({w+x,v}); } } }
def is_odd_number(num): if num % 2 == 0: return False else: return True result = is_odd_number(37) print(result)
import PropTypes from 'prop-types'; import React from 'react'; export interface MissingComponentProps { rendering?: { componentName?: string; }; } export const MissingComponent: React.SFC<MissingComponentProps> = (props) => { const componentName = props.rendering && props.rendering.componentName ? props.rendering.componentName : 'Unnamed Component'; console.log(`Component props for unimplemented '${componentName}' component`, props); return ( <div style={{ background: 'darkorange', outline: '5px solid orange', padding: '10px', color: 'white', maxWidth: '500px', }} > <h2>{componentName}</h2> <p> JSS component is missing React implementation. See the developer console for more information. </p> </div> ); }; MissingComponent.propTypes = { rendering: PropTypes.shape({ componentName: PropTypes.string, }), }; MissingComponent.displayName = 'MissingComponent';
from io import StringIO import attr from girder.api import access from girder.api.describe import autoDescribeRoute, Description from girder.api.rest import Resource from girder.constants import AccessType from girder.models.folder import Folder from girder_jobs.models import Job from nli_simulation_runner.tasks import GirderConfig, run_simulation from simulation.config import SimulationConfig class NLI(Resource): def __init__(self): super().__init__() self.resourceName = 'nli' @access.user @autoDescribeRoute( Description('Run a simulation as an async task.') .param('folderId', 'The folder store simulation outputs in') # TODO: What are the time units of the simulation .param('targetTime', 'The number of (hours?) to run the simulation', dataType='float') .errorResponse() .errorResponse('Write access was denied on the folder.', 403) ) def execute_simulation(self, folderId, targetTime): user, token = self.getCurrentUser(returnToken=True) folder_model = Folder() job_model = Job() folder = folder_model.load(folderId, user=user, level=AccessType.WRITE, exc=True) girder_config = GirderConfig(token=token['_id'], folder=folder['_id']) simulation_config = SimulationConfig() # TODO: This would be better stored as a dict, but it's easier once we change the # config object format. simulation_config_file = StringIO() simulation_config.write(simulation_config_file) job = job_model.createJob( title='NLI Simulation', type='nli_simulation', kwargs={ 'girder_config': attr.asdict(girder_config), 'simulation_config': simulation_config_file.getvalue(), }, ) job = run_simulation.delay( girder_config=girder_config, simulation_config=simulation_config, target_time=targetTime, job=job, ) return job
#!/bin/bash #################################################################################################################### ##################################################################################################################### ## detect-and-install-new-relic.sh ## ©Copyright IBM Corporation 2016 ## Written by Hans Kristian Moen September 2016 ## ## Script does three things: ## 1. Looks for New Relic license key in bound services and copy them to NEW_RELIC_LICENSE_KEY if exists ## 2. If New Relic license key is present and agent is not installed, run nmp install ## 3. If New Relic license key is present and no agent config file is installed, sets NEW_RELIC_NO_CONFIG_FILE ## ## NOTE: After Cloud Foundry v238, this functionality should be moved from .profile.d/ into .profile ## ## LICENSE: MIT (http://opensource.org/licenses/MIT) ## ##################################################################################################################### ################################################################################################################### agent_file="/agents/newrelic/newrelic.jar" agent_config="/agents/newrelic/newrelic.yaml" # Only check for license key in VCAP_SERVICES if they have not been passed in directly if [[ -z $NEW_RELIC_LICENSE_KEY ]] then echo "Checking for New Relic license key in bound services" ## Check if we have bound to a brokered New Relic service LICENSE_KEY=$(echo "${VCAP_SERVICES}" | jq --raw-output ".newrelic[0].credentials.licenseKey") ## Allow user-provided-services to overwrite brokered services, if they exist UP_LICENSE_KEY=$(echo "${VCAP_SERVICES}" | jq --raw-output '.["user-provided"] | .[] | select(.name == "newrelic") | .credentials.licenseKey' 2>/dev/null ) if [[ "$UP_LICENSE_KEY" != "null" ]] && [[ ! -z $UP_LICENSE_KEY ]] then echo "License Key found in User Provided Service: ${UP_LICENSE_KEY}" LICENSE_KEY=$UP_LICENSE_KEY fi if [[ ! -z $LICENSE_KEY ]] && [[ "${LICENSE_KEY}" != "null" ]] then echo "Found bound New Relic service instance" export NEW_RELIC_LICENSE_KEY=$LICENSE_KEY fi fi # If we have a New Relic License Key, make sure newrelic agent is loaded on Java start if [[ ! -z $NEW_RELIC_LICENSE_KEY ]] then echo "Found New Relic license Key" ## Check if module is supplied if [[ ! -f ${agent_file} ]] then # TODO: Figure out what to do if we can't fint the agent echo "Couldn't find newrelic agent installed in ${agent_file}" else # Enable the newrelic agent export JAVA_OPTS="${JAVA_OPTS} -javaagent:${agent_file}" APP_NAME=${CG_NAME} #APP_NAME=$(echo $VCAP_APPLICATION | jq --raw-output '.name') export NEW_RELIC_APP_NAME=$APP_NAME echo "Setting New Relic appname to ${APP_NAME}" fi if [[ -f ${agent_config} ]] then echo "Found New Relic config in ${agent_config}" export JAVA_OPTS="${JAVA_OPTS} -Dnewrelic.config.file=${agent_config} -Dnewrelic.bootstrap_classpath=true" else echo "Problems finding New Relic config file" echo "Agent may have problems loading" fi else echo "No New Relic license key found" fi
#!/usr/bin/env bash THE_FONTS_DIR_PATH="$HOME/.local/share/fonts" mkdir -p "$THE_FONTS_DIR_PATH" echo echo "cp Demo-Copy.ttf $THE_FONTS_DIR_PATH/Demo-Copy.ttf" cp "Demo-Copy.ttf" "$THE_FONTS_DIR_PATH/Demo-Copy.ttf" echo fc-cache -fv "$THE_FONTS_DIR_PATH" echo fc-list | grep 'DemoCopy' #ls -l "$HOME/.local/share/fonts/Demo-Copy.ttf" file "$HOME/.local/share/fonts/Demo-Copy.ttf" #stat "$HOME/.local/share/fonts/Demo-Copy.ttf"
<filename>test/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "rss.h" #include "rss-item.h" #include "parser.h" #include "fetcher.h" #include "pp.h" void usage(); int main(int argc, const char* argv[]) { if (argc < 2) { usage(); return 1; } fetch_data_t* fetch_data = fetch_document(argv[1]); rss_t* rss = parse_string(fetch_data->data); pp_rss(rss); delete_fetch_data(fetch_data); delete_rss(rss); return 0; } void usage() { printf("usage: tinyrss <URL>\n"); }
#!/usr/bin/env bash docker build \ --tag="lburgazzoli/app-t" \ --build-arg DOCKER_USER=$LOGNAME \ --build-arg DOCKER_USER_GID=$(id $LOGNAME -g) \ --build-arg DOCKER_USER_UID=$(id $LOGNAME -u) \ .
<filename>src/software/webapp/front/components/training/setup/SelectTrailDialog.tsx import * as React from 'react'; import {Trail} from "../../../types/training/Trail"; import Button from "@mui/material/Button"; import Dialog from "@mui/material/Dialog"; import DialogActions from "@mui/material/DialogActions"; import DialogContent from "@mui/material/DialogContent"; import DialogTitle from "@mui/material/DialogTitle"; import FormControl from "@mui/material/FormControl"; import InputLabel from "@mui/material/InputLabel"; import NativeSelect from "@mui/material/NativeSelect"; import Box from "@mui/material/Box"; import CustomInput from "../../common/CustomInput"; /* MyoCoach frontend trail select dialog component =============================================== Authors: Julien & <NAME> - RE-FACTORY SARL Company: ORTHOPUS SAS License: Creative Commons Zero v1.0 Universal Website: orthopus.com Last edited: October 2021 */ const SelectTrailDialog: React.FC<{ title: string, action: string, open: boolean, onClose: () => void, trails: Array<Trail>, onSubmit: (id: number) => Promise<any> }> = ({ title, action, open, onClose, trails, onSubmit }) => { const [selectedId, setSelectedId] = React.useState(-1); React.useEffect(() => { if (trails != undefined && trails.length > 0) { setSelectedId(trails[0].id); } }, [trails]) function handleSelectChange(event: React.ChangeEvent<HTMLSelectElement>) { const id: number = Number.parseInt((event.target as HTMLSelectElement).value); setSelectedId(id); } function handleSubmit() { if (selectedId != -1) { onSubmit(selectedId).then(onClose); } } return ( <Dialog open={open} onClose={onClose} aria-labelledby={"select-trail-dialog-title"}> <form onSubmit={(event: React.ChangeEvent<any>) => event.preventDefault()}> <DialogTitle id={"select-trail-dialog-title"}>{title}</DialogTitle> <DialogContent> <Box my={2}> <FormControl fullWidth> <InputLabel color={"info"} htmlFor={"trail-select"}>Trail selection</InputLabel> <NativeSelect value={selectedId} onChange={handleSelectChange} input={<CustomInput/>} id={"trail-select"} inputProps={{ name: 'trailSelect' }}> { trails.map(t => <option key={t.id} value={t.id}>{t.name}</option>) } </NativeSelect> </FormControl> </Box> </DialogContent> <DialogActions> <Button color={"secondary"} disabled={selectedId == -1} onClick={handleSubmit}>{action}</Button> <Button color={"inherit"} onClick={onClose}>Cancel</Button> </DialogActions> </form> </Dialog> ); } export default SelectTrailDialog;
<reponame>LiuFang07/bk-cmdb /* * Tencent is pleased to support the open source community by making 蓝鲸 available. * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the MIT License (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://opensource.org/licenses/MIT * 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 errors import ( "errors" ) type ErrorsInterface interface { New() func(message string) error } type pkgError struct{} func (pkgError) New() func(message string) error { return errors.New } // ErrNotSuppportedFunctionality returns an error cause the functionality is not supported var ErrNotSuppportedFunctionality = errors.New("not supported functionality") // ErrNotImplementedFunctionality returns an error cause the functionality is not implemented var ErrNotImplementedFunctionality = errors.New("not implemented functionality") // ErrDuplicateDataExisted returns an error cause the functionality is not supported var ErrDuplicateDataExisted = errors.New("duplicated data existed")
#!/bin/bash #Created by : ravinayag@gmail.com | Ravi Vasagam source scripts/.c.env source scripts/.hlc.env echo -e $PCOLOR"Sending invoke transaction on {PEER_NAME0}.{ORG_1} {PEER_NAME0}.{ORG_2}..."$NONE export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}/tls/ca.crt export CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}/tls/server.key export CORE_PEER_LOCALMSPID={ORG_1_C}MSP export CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock export CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}/tls/server.crt export CORE_PEER_TLS_ENABLED=true export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/users/Admin@{ORG_1}.{DOMAIN_NAME}/msp export CORE_PEER_ID={CLI_NAME} export CORE_PEER_ADDRESS={PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}:7051 export CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_2}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_2}.{DOMAIN_NAME}/tls/ca.crt export CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}/tls/server.key export CORE_PEER_LOCALMSPID={ORG_2_C}MSP export CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock export CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}/tls/server.crt export CORE_PEER_TLS_ENABLED=true export CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_2}.{DOMAIN_NAME}/users/Admin@{ORG_2}.{DOMAIN_NAME}/msp export CORE_PEER_ID={CLI_NAME} export CORE_PEER_ADDRESS={PEER_NAME0}.{ORG_2}.{DOMAIN_NAME}:9051 export ORDERER_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/{DOMAIN_NAME}/orderers/{ORD_NAME0}.{DOMAIN_NAME}/msp/tlscacerts/tlsca.{DOMAIN_NAME}-cert.pem export PEER0_ORG1_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}/tls/ca.crt export PEER0_ORG2_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_2}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_2}.{DOMAIN_NAME}/tls/ca.crt if [ $IMAGE_TAG == 2.0.0 ] || [ $IMAGE_TAG == 2.1.0 ] || [ $IMAGE_TAG == 2.2.0 ]; then peer chaincode invoke -o {ORD_NAME0}.{DOMAIN_NAME}:7050 --tls true --cafile $ORDERER_CA -C {CHANNEL_NAME1} -n sacc --peerAddresses {PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses {PEER_NAME0}.{ORG_2}.{DOMAIN_NAME}:9051 --tlsRootCertFiles $PEER0_ORG2_CA -c '{"Args":["set","name","Peter"]}' else peer chaincode invoke -o {ORD_NAME0}.{DOMAIN_NAME}:7050 --tls true --cafile $ORDERER_CA -C {CHANNEL_NAME1} -n sacc --peerAddresses {PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}:7051 --tlsRootCertFiles $PEER0_ORG1_CA --peerAddresses {PEER_NAME0}.{ORG_2}.{DOMAIN_NAME}:9051 --tlsRootCertFiles $PEER0_ORG2_CA -c '{"Args":["set","a","10"]}' fi #peer chaincode invoke -o orderer.{DOMAIN_NAME}:7050 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/{DOMAIN_NAME}/orderers/orderer.{DOMAIN_NAME}/msp/tlscacerts/tlsca.{DOMAIN_NAME}-cert.pem -C mychannel2 -n mycc --peerAddresses {PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_1}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_1}.{DOMAIN_NAME}/tls/ca.crt --peerAddresses {PEER_NAME0}.{ORG_2}.{DOMAIN_NAME}:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/{ORG_2}.{DOMAIN_NAME}/peers/{PEER_NAME0}.{ORG_2}.{DOMAIN_NAME}/tls/ca.crt -c '{"Args":["invoke","a","b","10"]}'
#include "defines.h" #include "lib.h" #include "intr.h" #include "interrupt.h" #include "timer.h" #include "kozos.h" #define TIMER_NUM 4 #define PIC_TIMER2 ((volatile struct pic_timer *)0xBF800800) #define PIC_TIMER3 ((volatile struct pic_timer *)0xBF800A00) #define PIC_TIMER4 ((volatile struct pic_timer *)0xBF800C00) #define PIC_TIMER5 ((volatile struct pic_timer *)0xBF800E00) struct pic_timer { volatile uint32 TxCON; volatile uint32 TxCONCLR; volatile uint32 TxCONSET; volatile uint32 TxCONINV; volatile uint32 TMRx; volatile uint32 TMRxCLR; volatile uint32 TMRxSET; volatile uint32 TMRxINV; volatile uint32 PRx; volatile uint32 PRxCLR; volatile uint32 PRxSET; volatile uint32 PRxINV; }; //Register TxCON value //skip 0bit #define PIC_TIMER_TxCON_USE_TxCS_CLOCK (1<<1) //skip 2bit #define PIC_TIMER_TxCON_T32_USE_32bit_TIMER (1<<3) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_1 (0<<4) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_2 (1<<4) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_4 (2<<4) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_8 (3<<4) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_16 (4<<4) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_32 (5<<4) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_64 (6<<4) #define PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_256 (7<<4) #define PIC_TIMER_TxCON_TGATE (1<<7) //skip 8bit //skip 9bit //skip 10bit //skip 11bit //skip 12bit #define PIC_TIMER_TxCON_SIDL_ENABLE_SLEEP_MODE (1<<13) //skip 14bit #define PIC_TIMER_TxCON_ON (1<<15) #define IEC0 *((volatile unsigned int *)0xBF881060) #define IEC0CLR *((volatile unsigned int *)0xBF881064) #define IEC0SET *((volatile unsigned int *)0xBF881068) #define IFS0 *((volatile unsigned int *)0xBF881030) #define IFS0CLR *((volatile unsigned int *)0xBF881034) #define IFS0SET *((volatile unsigned int *)0xBF881038) #define IFS_TMR2_FLAG (1<<9) #define IFS_TMR3_FLAG (1<<14) #define IFS_TMR4_FLAG (1<<19) #define IFS_TMR5_FLAG (1<<24) #define PIC_IPC2 ((volatile struct pic_ipc *)0xBF8810B0) #define PIC_IPC3 ((volatile struct pic_ipc *)0xBF8810C0) #define PIC_IPC4 ((volatile struct pic_ipc *)0xBF8810D0) #define PIC_IPC5 ((volatile struct pic_ipc *)0xBF8810E0) struct pic_ipc { volatile uint32 IPCx; volatile uint32 IPCxCLR; volatile uint32 IPCxSET; volatile uint32 IPCxINV; }; static struct { volatile struct pic_timer *tmr; volatile struct pic_ipc *ipc; } regs[TIMER_NUM] = { { PIC_TIMER2, PIC_IPC2 }, { PIC_TIMER3, PIC_IPC3 }, { PIC_TIMER4, PIC_IPC4 }, { PIC_TIMER5, PIC_IPC5 }, }; int timer_start(int index){ volatile struct pic_timer *tmr = regs[index].tmr; volatile struct pic_ipc *ipc = regs[index].ipc; tmr->PRx = F_PBCLK/1000/32 - 1; tmr->TxCON = PIC_TIMER_TxCON_ON | PIC_TIMER_TxCON_TCKPS_CLOCK_PRESCALE_32 ; // 割込みの有効化 ipc->IPCxSET = 0b11111; timer_expire(index); return 0; } /* タイマ満了したか? */ int timer_is_expired(int index) { switch(index){ case 0: return IFS0 & IFS_TMR2_FLAG; case 1: return IFS0 & IFS_TMR3_FLAG; case 2: return IFS0 & IFS_TMR4_FLAG; case 3: return IFS0 & IFS_TMR5_FLAG; } } /* タイマ満了処理 */ void timer_expire(int index) { switch(index){ case 0: IFS0CLR = IFS_TMR2_FLAG; break; case 1: IFS0CLR = IFS_TMR3_FLAG; break; case 2: IFS0CLR = IFS_TMR4_FLAG; break; case 3: IFS0CLR = IFS_TMR5_FLAG; break; } } /* タイマキャンセル */ int timer_stop(int index) { volatile struct pic_timer *tmr = regs[index].tmr; tmr->TxCONCLR = PIC_TIMER_TxCON_ON ; timer_expire(index); return 0; } void timer_intr_enable(int index) { switch(index){ case 0: IEC0SET = IFS_TMR2_FLAG; break; case 1: IEC0SET = IFS_TMR3_FLAG; break; case 2: IEC0SET = IFS_TMR4_FLAG; break; case 3: IEC0SET = IFS_TMR5_FLAG; break; } } void timer_intr_disable(int index) { switch(index){ case 0: IEC0CLR = IFS_TMR2_FLAG; break; case 1: IEC0CLR = IFS_TMR3_FLAG; break; case 2: IEC0CLR = IFS_TMR4_FLAG; break; case 3: IEC0CLR = IFS_TMR5_FLAG; break; } }
<reponame>daviz00/react-native /** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ import type {RNTesterNavState, ComponentList} from '../types/RNTesterTypes'; export const RNTesterNavActionsType = { INIT_FROM_STORAGE: 'INIT_FROM_STORAGE', NAVBAR_PRESS: 'NAVBAR_PRESS', BOOKMARK_PRESS: 'BOOKMARK_PRESS', BACK_BUTTON_PRESS: 'BACK_BUTTON_PRESS', MODULE_CARD_PRESS: 'MODULE_CARD_PRESS', EXAMPLE_CARD_PRESS: 'EXAMPLE_CARD_PRESS', }; const getUpdatedBookmarks = ({ exampleType, key, bookmarks, }: { exampleType: string, key: string, bookmarks: ComponentList, }) => { const updatedBookmarks = bookmarks ? {...bookmarks} : {components: [], apis: []}; if (updatedBookmarks[exampleType].includes(key)) { updatedBookmarks[exampleType] = updatedBookmarks[exampleType].filter( k => k !== key, ); } else { updatedBookmarks[exampleType].push(key); } return updatedBookmarks; }; const getUpdatedRecentlyUsed = ({ exampleType, key, recentlyUsed, }: { exampleType: string, key: string, recentlyUsed: ComponentList, }) => { const updatedRecentlyUsed = recentlyUsed ? {...recentlyUsed} : {components: [], apis: []}; let existingKeys = updatedRecentlyUsed[exampleType]; if (existingKeys.includes(key)) { existingKeys = existingKeys.filter(k => k !== key); } existingKeys.unshift(key); updatedRecentlyUsed[exampleType] = existingKeys.slice(0, 5); return updatedRecentlyUsed; }; export const RNTesterNavReducer = ( state: RNTesterNavState, action: {type: string, data: any}, ): RNTesterNavState => { switch (action.type) { case RNTesterNavActionsType.INIT_FROM_STORAGE: return action.data; case RNTesterNavActionsType.NAVBAR_PRESS: return { ...state, activeModuleKey: null, activeModuleTitle: null, activeModuleExampleKey: null, screen: action.data.screen, }; case RNTesterNavActionsType.MODULE_CARD_PRESS: return { ...state, activeModuleKey: action.data.key, activeModuleTitle: action.data.title, activeModuleExampleKey: null, recentlyUsed: getUpdatedRecentlyUsed({ exampleType: action.data.exampleType, key: action.data.key, recentlyUsed: state.recentlyUsed, }), }; case RNTesterNavActionsType.EXAMPLE_CARD_PRESS: return { ...state, activeModuleExampleKey: action.data.key, }; case RNTesterNavActionsType.BOOKMARK_PRESS: return { ...state, bookmarks: getUpdatedBookmarks({ exampleType: action.data.exampleType, key: action.data.key, bookmarks: state.bookmarks, }), }; case RNTesterNavActionsType.BACK_BUTTON_PRESS: // Go back to module or list return { ...state, activeModuleExampleKey: null, activeModuleKey: state.activeModuleExampleKey != null ? state.activeModuleKey : null, activeModuleTitle: state.activeModuleExampleKey != null ? state.activeModuleTitle : null, }; default: throw new Error(`Invalid action type ${action.type}`); } };
#!/bin/bash -e upstream_main() { git clone https://github.com/keycloak/keycloak mvn clean install -Pdistribution -DskipTests -f keycloak -B find keycloak/distribution/server-dist/target -maxdepth 1 -type f -name 'keycloak-[[:digit:]]*.tar.gz' -exec tar xzf {} --strip-components=1 -C keycloak-dist \; } latest_release() { URL="https://repo1.maven.org/maven2/org/keycloak/keycloak-server-dist/${VERSION}/keycloak-server-dist-${VERSION}.tar.gz" echo "Downloading Keycloak from: $URL" curl -o keycloak-dist.tar.gz "$URL" tar xzf keycloak-dist.tar.gz --strip-components=1 -C keycloak-dist } mkdir keycloak-dist if [ -n "$PRODUCT" ] && [ "$PRODUCT" == "true" ]; then echo "Using RHSSO distribution: $PRODUCT_VERSION" "$PRODUCT_DIST/bin/add-user-keycloak.sh" -u admin -p admin exit 0 elif [[ ( -n "$GITHUB_BASE_REF" && "$GITHUB_BASE_REF" == "latest" ) ]] || [[ ( -n "$QUICKSTART_BRANCH" && "$QUICKSTART_BRANCH" != "main" ) ]]; then VERSION=$(grep -oPm1 "(?<=<version>)[^<]+" pom.xml) echo "Using corresponding Keycloak version: $VERSION" latest_release else echo "Building Keycloak from upstream/main" upstream_main fi keycloak-dist/bin/add-user-keycloak.sh -u admin -p admin
# name: Cloudsuite benchmark in cluster # auth: Mohammad Sahihi <msahihi1 at gwdg.de> # vim: ts=4 syntax= bash sw=4 sts=4 sr noet #!/bin/bash # set -x # set -e # # # D I S P L A Y U S A G E F U C N T I O N # # # display_usage() { cat <<EOF Usage: $0 [options] -h | --help Give this help list. -a | --auto Running whole benchmark and setup automatically -R | --remove-all Stop and remove all servers & client -n | --server-no Number of server (default: 4) -tt | --server-threads Number of threads of server (default: 4) -mm | --memory Dedicated memory (default: 4096) -nn | --object-size Object size (default: 550) -w | --client-threats Number of client threads (default: 4) -T | --interval Interval between stats printing (default: 1) -D | --server-memory Size of main memory available to each memcached server in MB (default: 4096) -S | --scaling-factor Dataset scaling factor (default: 2) -t | --duration Runtime of loadtesting in seconds (default: run forever) -g | --fraction Fraction of requests that are gets (default: 0.8) -c | --connections Total TCP connections (default: 200) EOF } # # # R U N N I N G B E N C H M A R K # # # run_benchmark () { echo -e "[+] Warming up the servers. " sleep 2 echo -e "[!] It may takes few minutes." # Scaling the dataset and warming up the server sudo docker -H :4000 exec -d dc-client bash -c 'cd /usr/src/memcached/memcached_client/ && stdbuf -o0 ./loader -a ../twitter_dataset/twitter_dataset_unscaled -o ../twitter_dataset/twitter_dataset_30x -s docker_servers.txt -w '"$w"' -S '"$S"' -D '"$D"' -j -T '"$T"' >> /home/log/warmup.log && stdbuf -o0 ./loader -a ../twitter_dataset/twitter_dataset_30x -s docker_servers.txt -g '"$g"' -T '"$T"' -c '"$c"' -w '"$w"' -t '"$t"' >> /home/log/benchmark.log' } # # # C R E A T E S N A P T A S K # # # create_snap_task() { echo -e "[+] Creating SNAP Task ....." snaptel task create -t asset/snap/datacaching-task.yaml && echo -e "[+] Cloudsuite-datacaching SNAP Task created and is running" } wait_time() { if [ "$t" -eq "0" ]; then echo -e "[!] The benchmark runs forever " echo -e "Pres CTRL+C to stop..." while : do sleep 1 done else echo -e "[!] The benchmark takes $t seconds to be completed" sleep $t; fi } ######################################################################## # # # M A I N # # # ########################################################################I while [[ $# -gt 0 ]] do key="$1" case $key in -h|--help) display_usage exit 0 ;; -a|--auto) auto=1 shift ;; -R|--remove-all) remove_all shift ;; -n|--server-no) n=$2 shift 2 ;; -tt|--server-threats) tt=$2 shift 2 ;; -mm|--memory) mm=$2 shift 2 ;; -nn|--object-size) nn=$2 shift 2 ;; -w|--client-threads) w=$2 shift 2 ;; -T|--interval) T=$2 shift 2 ;; -D|--server-memory) D=$2 shift 2 ;; -S|--scaling-factor) S=$2 shift 2 ;; -t|--duration) t=$2 shift 2 ;; -g|--fraction) g=$2 shift 2 ;; -c|--connections) c=$2 shift 2 ;; --) shift break ;; -*) display_usage exit 1 ;; \?) echo -e "Invalid option" ;; *) display_usage break ;; esac done if [ "$n" = "" ] then n=4 fi if [ "$tt" = "" ] then tt=4 fi if [ "$mm" = "" ] then mm=4096 fi if [ "$nn" = "" ] then nn=550 fi if [ "$w" = "" ] then w=4 fi if [ "$T" = "" ] then T=1 fi if [ "$D" = "" ] then D=4096 fi if [ "$S" = "" ] then S=2 fi if [ "$t" = "" ] then t=0 fi if [ "$g" = "" ] then g=0.8 fi if [ "$c" = "" ] then c=200 fi if [ "$auto" = 1 ] then echo -e "+---------------------------------------+" echo -e " " echo -e " Benchmark Environment " echo -e " " echo -e " ---------- Server --------- " echo -e " " echo -e " Number of Server: $n " echo -e " Server Threads: $tt " echo -e " Dedicated memory: $mm " echo -e " Object Size: $nn " echo -e " " echo -e " --------- Client --------- " echo -e " " echo -e " Client threats: $w " echo -e " Interval: $T " echo -e " Server memory: $D " echo -e " Scaling factor: $S " echo -e " Fraction: $g " echo -e " Connections: $c " echo -e " Duration: $t " echo -e " " echo -e "+---------------------------------------+" run_benchmark while [ ! -f /var/log/benchmark/benchmark.log ]; do sleep 1; done; echo -e "[+] Servers are wamred up" echo -e "[+] Running Benchmark ...\n" echo -e "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" >> /var/log/benchmark/detail.csv nohup stdbuf -o0 tail -f /var/log/benchmark/benchmark.log | nohup stdbuf -o0 awk -f asset/output.awk >> /var/log/benchmark/detail.csv& sleep 10; # to be sure that we get the output in detail.csv create_snap_task # stdbuf -o0 snaptel task watch $(snaptel task list | cut -f 1 | tail -n +2 | tail) echo -e "[+] The Benchmark is running in the background" wait_time fi
<reponame>minuk8932/Algorithm_BaekJoon package math; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author minchoba * 백준 5347번: LCM * * @see https://www.acmicpc.net/problem/5347/ * */ public class Boj5347 { private static final String NEW_LINE = "\n"; public static void main(String[] args) throws Exception{ // 버퍼를 통한 값 입력 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while(n-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); long a = Long.parseLong(st.nextToken()); long b = Long.parseLong(st.nextToken()); long res = a * b / gcd(a, b); // 최대 공약수를 이용한 최소 공배수 도출 sb.append(res).append(NEW_LINE); // 최소 공배수를 각각 버퍼에 담아줌 } System.out.println(sb.toString()); // 결과값 한번에 출력 } /** * 유클리드 호제법을 이용한 최대 공약수 반환 * @param 비교할 숫자 * @return 최대 공약수 */ private static long gcd(long x, long y) { if(y == 0) { return x; } return gcd(y, x % y); } }
number = 123 # find the sum of its digits sum = 0 temp = number while (temp > 0): digit = temp % 10 sum = sum + digit temp = temp // 10 # printing the output print( "The sum of digits in the given number is", sum)
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-N-VB/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-N-VB/1024+0+512-rare-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_rare_words_first_two_thirds_sixth --eval_function last_sixth_eval
<gh_stars>0 // // ___FILENAME___ // Project: ___PROJECTNAME___ // // Module: ___VARIABLE_viperModuleName___ // Description: ___VARIABLE_viperModuleDescription___ // // By ___FULLUSERNAME___ ___DATE___ // ___ORGANIZATIONNAME___ ___YEAR___ // #import <UIKit/UIKit.h> #import "___VARIABLE_viperModuleName:identifier___ViewInput.h" @protocol ___VARIABLE_viperModuleName:identifier___ViewOutput; @interface ___VARIABLE_viperModuleName:identifier___ViewController : UIViewController <___VARIABLE_viperModuleName:identifier___ViewInput> @property (nonatomic, strong) id<___VARIABLE_viperModuleName:identifier___ViewOutput> output; @end
""" Collection of helpers for ivy unit tests """ # global import ast try: import numpy as _np except ImportError: _np = None try: import jax.numpy as _jnp except ImportError: _jnp = None try: import tensorflow as _tf _tf_version = float('.'.join(_tf.__version__.split('.')[0:2])) if _tf_version >= 2.3: # noinspection PyPep8Naming,PyUnresolvedReferences from tensorflow.python.types.core import Tensor as tensor_type else: # noinspection PyPep8Naming # noinspection PyProtectedMember,PyUnresolvedReferences from tensorflow.python.framework.tensor_like import _TensorLike as tensor_type physical_devices = _tf.config.list_physical_devices('GPU') for device in physical_devices: _tf.config.experimental.set_memory_growth(device, True) except ImportError: _tf = None try: import torch as _torch except ImportError: _torch = None try: import mxnet as _mx import mxnet.ndarray as _mx_nd import mxnet.symbol as _mx_sym except ImportError: _mx = None _mx_nd = None _mx_sym = None try: import ivy.mxsym as _ivy_mxsym except ImportError: _ivy_mxsym = None _iterable_types = [list, tuple, dict] def _convert_vars(vars_in, from_type, to_type_callable=None, to_type_attribute_method_str=None, keep_other=True, to_type=None): new_vars = list() for var in vars_in: if type(var) in _iterable_types: return_val = _convert_vars(var, from_type, to_type_callable, to_type_attribute_method_str) new_vars.append(return_val) elif isinstance(var, from_type): if isinstance(var, _np.ndarray): if var.dtype == _np.float64: var = var.astype(_np.float32) if bool(sum([stride < 0 for stride in var.strides])): var = var.copy() if to_type_callable: new_vars.append(to_type_callable(var)) elif to_type_attribute_method_str: new_vars.append(getattr(var, to_type_attribute_method_str)()) else: raise Exception('Invalid. A conversion callable is required.') elif to_type is not None and isinstance(var, to_type): new_vars.append(var) elif keep_other: new_vars.append(var) return new_vars def mx_sym_to_key(mx_sym): return list(mx_sym.attr_dict().keys())[0] def mx_sym_to_val(mx_sym): return _mx.nd.array(ast.literal_eval(list(mx_sym.attr_dict().values())[0]['__init__'])[1]['value']) def _get_mx_sym_args(args_list_in): new_vars = list() for i, arg in enumerate(args_list_in): if type(arg) in _iterable_types: new_vars += _get_mx_sym_args(arg) elif isinstance(arg, _mx_sym.Symbol): new_vars += [arg] return new_vars def np_call(func, *args, **kwargs): return func(*args, **kwargs) def jnp_call(func, *args, **kwargs): new_args = _convert_vars(args, _np.ndarray, _jnp.asarray) new_kw_vals = _convert_vars(kwargs.values(), _np.ndarray, _jnp.asarray) new_kwargs = dict(zip(kwargs.keys(), new_kw_vals)) output = func(*new_args, **new_kwargs) if isinstance(output, tuple): return tuple(_convert_vars(output, _jnp.ndarray, _np.asarray)) else: return _convert_vars([output], _jnp.ndarray, _np.asarray)[0] def tf_call(func, *args, **kwargs): new_args = _convert_vars(args, _np.ndarray, _tf.convert_to_tensor) new_kw_vals = _convert_vars(kwargs.values(), _np.ndarray, _tf.convert_to_tensor) new_kwargs = dict(zip(kwargs.keys(), new_kw_vals)) output = func(*new_args, **new_kwargs) if isinstance(output, tuple): return tuple(_convert_vars(output, tensor_type, _np.asarray)) else: return _convert_vars([output], tensor_type, _np.asarray)[0] def tf_graph_call(func, *args, **kwargs): new_args = _convert_vars(args, _np.ndarray, _tf.convert_to_tensor) new_kw_vals = _convert_vars(kwargs.values(), _np.ndarray, _tf.convert_to_tensor) new_kwargs = dict(zip(kwargs.keys(), new_kw_vals)) @_tf.function def tf_func(*local_args, **local_kwargs): return func(*local_args, **local_kwargs) output = tf_func(*new_args, **new_kwargs) if isinstance(output, tuple): return tuple(_convert_vars(output, tensor_type, _np.asarray)) else: return _convert_vars([output], tensor_type, _np.asarray)[0] def torch_call(func, *args, **kwargs): new_args = _convert_vars(args, _np.ndarray, _torch.from_numpy) new_kw_vals = _convert_vars(kwargs.values(), _np.ndarray, _torch.from_numpy) new_kwargs = dict(zip(kwargs.keys(), new_kw_vals)) output = func(*new_args, **new_kwargs) if isinstance(output, tuple): return tuple(_convert_vars(output, _torch.Tensor, _np.asarray)) else: return _convert_vars([output], _torch.Tensor, _np.asarray)[0] def mx_call(func, *args, **kwargs): new_args = _convert_vars(args, _np.ndarray, _mx_nd.array) new_kw_items = _convert_vars(kwargs.values(), _np.ndarray, _mx_nd.array) new_kwargs = dict(zip(kwargs.keys(), new_kw_items)) output = func(*new_args, **new_kwargs) if isinstance(output, tuple): return tuple(_convert_vars(output, _mx_nd.ndarray.NDArray, to_type_attribute_method_str='asnumpy')) else: return _convert_vars([output], _mx_nd.ndarray.NDArray, to_type_attribute_method_str='asnumpy')[0] def mx_graph_call(func, *args, **kwargs): new_args = _convert_vars(args, _np.ndarray, _ivy_mxsym.array) new_kw_vals = _convert_vars(kwargs.values(), _np.ndarray, _ivy_mxsym.array) new_kwargs = dict(zip(kwargs.keys(), new_kw_vals)) output_sym = func(*new_args, **new_kwargs) if output_sym is None: return mx_nd_args = _get_mx_sym_args(args) mx_nd_args += _get_mx_sym_args(list(kwargs.values())) mx_nd_keys = [mx_sym_to_key(item) for item in mx_nd_args] mx_nd_vals = [mx_sym_to_val(item) for item in mx_nd_args] mx_nd_dict = dict(zip(mx_nd_keys, mx_nd_vals)) if len(mx_nd_dict) == 0: try: mx_nd_dict =\ {list(output_sym.attr_dict().keys())[0]: _mx.nd.array(ast.literal_eval(list(output_sym.attr_dict().values())[0]['__init__'])[1]['value'])} except KeyError: mx_nd_dict = dict() if isinstance(output_sym, tuple): output = [item.bind(_mx.cpu(), mx_nd_dict).forward() for item in output_sym] else: output = output_sym.bind(_mx.cpu(), mx_nd_dict).forward() if len(output) > 1: return tuple(_convert_vars(output, _mx_nd.ndarray.NDArray, to_type_attribute_method_str='asnumpy')) else: return _convert_vars(output, _mx_nd.ndarray.NDArray, to_type_attribute_method_str='asnumpy')[0] from ivy import torch as _ivy_torch, tensorflow as _ivy_tf, mxnd as _ivy_mxnd, jax as _ivy_jnp, mxsym as _ivy_mxsym, \ numpy as _ivy_np _keys = [ivy_lib for ivy_lib, lib in zip([_ivy_np, _ivy_jnp, _ivy_tf, _ivy_tf, _ivy_torch, _ivy_mxnd, _ivy_mxsym], [_np, _jnp, _tf, _tf, _torch, _mx_nd, _mx_sym]) if lib is not None] _values = [call for call, lib in zip([np_call, jnp_call, tf_call, tf_graph_call, torch_call, mx_call, mx_graph_call], [_np, _jnp, _tf, _tf, _torch, _mx_nd, _mx_sym]) if lib is not None] calls = list(zip(_keys, _values))
#!/usr/bin/env bash if [ "$#" -ne 1 ]; then echo "Please specify indy-sdk version tag" echo "e.g ./setup-dev-dependencies.sh 1.6.7" exit 1 fi indy_sdk_version=$1 brew update echo 'Installing libsodium...' brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/65effd2b617bade68a8a2c5b39e1c3089cc0e945/Formula/libsodium.rb echo 'Installed libsodium' echo 'Installing RocksDB 5.8.8...' brew install https://gist.githubusercontent.com/faisal00813/4059a5b41c10aa87270351c4795af752/raw/551d4de01a83f884c798ec5c2cb28a1b15d04db8/rocksdb.rb echo 'Installing RocksDB...' echo 'Installing libindy...' brew install pkg-config brew install automake brew install autoconf brew install cmake brew install openssl brew install zeromq brew install zmq export PKG_CONFIG_ALLOW_CROSS=1 export CARGO_INCREMENTAL=1 export RUST_LOG=indy=trace export RUST_TEST_THREADS=1 export OPENSSL_DIR=$(brew --prefix openssl) pushd /tmp git clone https://github.com/hyperledger/indy-sdk.git pushd indy-sdk/libindy git fetch --all --tags --prune git checkout tags/v"${indy_sdk_version}" cargo build --release cp target/release/libindy.dylib /usr/local/lib/ popd rm -rf indy-sdk popd echo 'Installed libindy'
#!/bin/bash gsed -i -e 's/ff1717/ABRACADABRA/g' season{12,13,14,15,16,17,18,19,20,21,22,23}/*.json gsed -i -e 's/bb0000/ff1717/g' season{12,13,14,15,16,17,18,19,20,21,22,23}/*.json gsed -i -e 's/ABRACADABRA/bb0000/g' season{12,13,14,15,16,17,18,19,20,21,22,23}/*.json
#!/bin/bash echo -e "\n\xF0\x9F\x9B\x91 Stopping the development site.\n" docker-compose stop
const path = require('path'); const express = require('express'); const passport = require('passport'); const { Strategy } = require('passport-facebook'); const session = require('express-session'); const { ensureLoggedIn } = require('connect-ensure-login'); const bodyParser = require('body-parser'); const logger = require('./src/backend/logger'); const users = require('./src/backend/users'); users.runMigrations() .then(() => logger.log('info', 'Migrations ready')) .catch(e => logger.log('info', 'Migrations error', e)); const app = express(); const PORT = process.env.PORT || 3000; const FB_CALLBACK_LOCAL = process.env.FB_LOGIN_CALLBACK || 'http://localhost:3000/api/loginSuccess'; const FB_CALLBACK_PRODUCTION = 'https://uvb18.herokuapp.com/api/loginSuccess'; passport.use(new Strategy({ clientID: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, callbackURL: process.env.NODE_ENV === 'production' ? FB_CALLBACK_PRODUCTION : FB_CALLBACK_LOCAL }, async (accessToken, refreshToken, profile, cb) => { const userId = await users.getOrCreateUser(profile); return cb(null, userId); })); passport.serializeUser((user, cb) => cb(null, user)); passport.deserializeUser(async (id, cb) => { const user = await users.getUserById(id); cb(null, user); }); const sessionSettings = { secret: 'vaasankatu', resave: true, saveUninitialized: true, cookie: { maxAge: 86400000 } }; app.use(bodyParser.json()); app.use(session(sessionSettings)); app.use(passport.initialize()); app.use(passport.session()); app.use(express.static(path.join(__dirname, 'dist'))); app.get('/', (req, res) => res.sendFile(path.resolve('dist/index.html'))); app.get('/failure', (req, res) => res.sendFile(path.resolve('dist/failure.txt'))); app.get('/api/user', ensureLoggedIn(), (req, res) => res.send(req.user)); app.get('/api/login', passport.authenticate('facebook')); app.get( '/api/loginSuccess', passport.authenticate('facebook', { failureRedirect: '/failure' }), (req, res) => res.redirect('/') ); app.post('/api/points', ensureLoggedIn(), async (req, res) => { try { await users.addPoints(req.user.id, req.body.venue, req.body.points); res.sendStatus(200); logger.log('info', 'Points saved', { user: req.user.id, venue: req.body.venue, points: req.body.points }); } catch (err) { logger.log('error', err); res.sendStatus(500); } }); app.get('/api/points', ensureLoggedIn(), async (req, res) => { try { const points = await users.getUserPoints(req.user.id); res.send(points); } catch (err) { logger.log('error', err); res.sendStatus(500); } }); app.get('/api/pointsData', ensureLoggedIn(), async (req, res) => { try { const points = await users.getUserPointsWithData(req.user.id); res.send(points); } catch (err) { logger.log('error', err); res.sendStatus(500); } }); app.get('/api/scores', ensureLoggedIn(), async (req, res) => { try { const scores = await users.getScores(); res.send(scores); } catch (err) { logger.log('error', err); res.sendStatus(500); } }); app.get('/api/venues', (req, res) => users.getVenues() .then(data => res.send(data))); app.get('/api/stats/:year', ensureLoggedIn(), (req, res) => users.getStatistics(req.params.year) .then(data => res.send(data))); app.listen(PORT, (error) => { if (error) { logger.log('error', error); } else { logger.log('info', `Listening on port ${PORT}. Visit http://localhost:${PORT}/ in your browser.`); } });
<gh_stars>0 package io.stargate.grpc.service; import io.grpc.stub.StreamObserver; import io.stargate.db.Persistence; import io.stargate.proto.QueryOuterClass; public class SingleBatchHandler extends BatchHandler { private final StreamObserver<QueryOuterClass.Response> responseObserver; SingleBatchHandler( QueryOuterClass.Batch batch, Persistence.Connection connection, Persistence persistence, StreamObserver<QueryOuterClass.Response> responseObserver, ExceptionHandler exceptionHandler) { super(batch, connection, persistence, exceptionHandler); this.responseObserver = responseObserver; } @Override protected void setSuccess(QueryOuterClass.Response response) { responseObserver.onNext(response); responseObserver.onCompleted(); } }
words_starting_with_s = [word for word in sentence.split() if word.startswith('S')]
<!doctype html> <html> <head> <title>Products</title> </head> <body> <h1>Products</h1> <ul> <li> <h2>Laptop</h2> <p>Price: $799</p> <img src="laptop.jpg" alt="Laptop" /> </li> <li> <h2>Watch</h2> <p>Price: $199</p> <img src="watch.jpg" alt="Watch" /> </li> <li> <h2>Bag</h2> <p>Price: $399</p> <img src="bag.jpg" alt="Bag" /> </li> </ul> </body> </html>
json.extract! room_category, :id, :name, :description, :price, :created_at, :updated_at json.url room_category_url(room_category, format: :json)
# frozen_string_literal: true # Responsible for the relationship between identities and permissions retrieved # from SSO, and the internal Users and Estates. Also for additional information # returned from the SSO application which is stored in the user's session. class SignonIdentity class InvalidSessionData < RuntimeError; end ADMIN_ROLE = 'ROLE_PVB_ADMIN' class << self def from_omniauth(omniauth_auth) info = omniauth_auth.fetch('info') # Disallow login unless user has access to at least one estate if accessible_estates(info.fetch('organisations'), info.fetch('roles')).empty? Rails.logger.info "User has no valid permissions: #{info}" return end user = find_or_create_authorized_user(info) additional_data = extract_additional_data(info) new(user, additional_data) end def from_session_data(data) new( User.find(data.fetch('user_id')), full_name: data.fetch('full_name'), logout_url: data.fetch('logout_url'), organisations: data.fetch('organisations'), roles: data.fetch('roles') ) rescue KeyError raise InvalidSessionData end private # Determines which estates a user can access based on their permissions def accessible_estates(orgs, roles) mapper = EstateSSOMapper.new(orgs, roles.include?(ADMIN_ROLE)) mapper.accessible_estates end def find_or_create_authorized_user(info) email = user_email(info) User.find_or_create_by!(email: email) end def user_email(info) Nomis::Api.instance.fetch_email_addresses(info.fetch('user_id')).first end def extract_additional_data(info) { full_name: full_name_from_additional_data(info), logout_url: "#{Rails.configuration.nomis_oauth_host}/auth/logout", organisations: info.fetch('organisations'), roles: info.fetch('roles') } end def full_name_from_additional_data(info) first_name = info.fetch('first_name') last_name = info.fetch('last_name') [first_name, last_name].reject(&:empty?).join(' ') end end attr_reader :user, :full_name def initialize(user, full_name:, logout_url:, organisations:, roles:) @user = user @full_name = full_name @logout_url = logout_url @organisations = organisations @roles = roles end def logout_url(redirect_to: nil) url = URI.parse(@logout_url) if redirect_to url.query = { redirect_uri: redirect_to, client_id: Rails.configuration.nomis_user_oauth_client_id }.to_query end url.to_s end def accessible_estates @accessible_estates ||= estate_sso_mapper.accessible_estates.order(:nomis_id).to_a end def accessible_estates?(estates) estates.all? { |estate| accessible_estates.include?(estate) } end def default_estates # Prevent loading data from all prisons by default if estate_sso_mapper.admin? accessible_estates.take(1) else accessible_estates || fail('Should never be nil') end end # Export SSO data for storing in session between requests def to_session { 'full_name' => @full_name, 'user_id' => @user.id, 'logout_url' => @logout_url, 'organisations' => @organisations, 'roles' => @roles } end def admin? @roles.include?(ADMIN_ROLE) end private def estate_sso_mapper @estate_sso_mapper ||= begin EstateSSOMapper.new(@organisations, admin?) end end end
# vim: ft=sh dot_list() { _dot_list() { echo $1,$2 } parse_linkfiles _dot_list unset -f _dot_list $0 }
#!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" echo "Check Azure CLI login..." if ! az group list >/dev/null 2>&1; then echo "Login Azure CLI required" >&2 exit 1 fi resource_group=aks-test location=eastus aks_name=kube-test dns_name_suffix=<your-dns-name-suffix> companion_rg="MC_${resource_group}_${aks_name}_${location}" echo "Checking resource group $resource_group..." if [[ "$(az group exists --name "$resource_group")" == "false" ]]; then echo "Create resource group $resource_group" az group create -n "$resource_group" -l "$location" fi echo "Checking AKS $aks_name..." if ! az aks show -g "$resource_group" -n "$aks_name" >/dev/null 2>&1; then echo "Create AKS $aks_name" az aks create -g "$resource_group" -n "$aks_name" --node-count 2 fi kubeconfig="$(mktemp)" echo "Fetch AKS credentials to $kubeconfig" az aks get-credentials -g "$resource_group" -n "$aks_name" --admin --file "$kubeconfig" SAVEIFS="$IFS" IFS=$(echo -en "\n\b") for config in "$DIR"/*.yml; do echo "Apply $config" kubectl apply -f "$config" --kubeconfig "$kubeconfig" done IFS="$SAVEIFS" function assign_dns { service="$1" dns_name="$2" IP= while true; do echo "Waiting external IP for $service..." IP="$(kubectl get service "$service" --kubeconfig "$kubeconfig" | tail -n +2 | awk '{print $4}' | grep -v '<')" if [[ "$?" == 0 && -n "$IP" ]]; then echo "Service $service public IP: $IP" break fi sleep 10 done public_ip="$(az network public-ip list -g "$companion_rg" --query "[?ipAddress==\`$IP\`] | [0].id" -o tsv)" if [[ -z "$public_ip" ]]; then echo "Cannot find public IP resource ID for '$service' in companion resource group '$companion_rg'" >&2 exit 1 fi echo "Assign DNS name '$dns_name' for '$service'" az network public-ip update --dns-name "$dns_name" --ids "$public_ip" [[ $? != 0 ]] && exit 1 } assign_dns todoapp-service "aks-todoapp$dns_name_suffix" assign_dns todoapp-test-blue "aks-todoapp-blue$dns_name_suffix" assign_dns todoapp-test-green "aks-todoapp-green$dns_name_suffix" rm -f "$kubeconfig"
<filename>src/main/java/com/softhale/utils/UndirectedGraph.java<gh_stars>0 package com.softhale.utils; import java.util.*; public class UndirectedGraph<T> { private final Map<T, LinkedList<T>> nodes = new HashMap<>(); public Map<T, LinkedList<T>> getNodes() { return nodes; } public void addEdge(T from, T to) { var fromEdges = nodes.getOrDefault(from, new LinkedList<>()); var toEdges = nodes.getOrDefault(to, new LinkedList<>()); if (!fromEdges.contains(to)) fromEdges.add(to); if (!toEdges.contains(from)) toEdges.add(from); nodes.put(from, fromEdges); nodes.put(to, toEdges); } }
#include <stdio.h> #include <string.h> // function to swap two strings void swapStrings(char *str1, char *str2) { char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char)); strcpy(temp, str1); strcpy(str1, str2); strcpy(str2, temp); free(temp); } // function to sort an array of strings // using Selection Sort technique void selectionSort(char **arr, int start, int end) { int i, j; for (i = start; i < end; i++) { int minIndex = i; for (j = i + 1; j < end; j++) if (strcmp(arr[j], arr[minIndex]) < 0) minIndex = j; swapStrings(arr[minIndex], arr[i]); } } // Driver Code int main() { char *arr[] = {"A", "B", "C", "D"}; int size = sizeof(arr) / sizeof(arr[0]); // sorts the array selectionSort(arr, 0, size); int i; printf("Sorted Array:\n"); for (i = 0; i < size; i++) printf("%s ", arr[i]); return 0; }
# Function to calculate the highest tip generated by waiter in a given month def find_max_tip(tips): max_tip = 0 waiter = '' # Iterate over all the employees in the list for tip in tips: # Check if current employee's tip is greater than the maximum tip if tip[1] > max_tip: max_tip = tip[1] waiter = tip[0] # return the name of the waiter and the maximum tip return waiter, max_tip # List of tuples containing employee name and the tips # Format is (name, tip) tips = [ ("John",12.50), ("Mary",22.25), ("David",
export declare function assertHardhatNetworkInvariant(invariant: boolean, description: string): asserts invariant; //# sourceMappingURL=assertions.d.ts.map
#! /bin/sh # Created Time: 2016-04-23 14:26:54 # cscope -Rbkq
<gh_stars>0 /* * Number.sql * Chapter 3, Oracle10g PL/SQL Programming * by <NAME>, <NAME>, <NAME> * * This script demonstrates the NUMBER datatype */ exec clean_schema.trigs exec clean_schema.procs exec clean_schema.tables CREATE TABLE precision ( value NUMBER(38,5), scale NUMBER(10)); INSERT INTO precision (value, scale) VALUES (12345, 0); INSERT INTO precision (value, scale) VALUES (123456, 0); INSERT INTO precision (value, scale) VALUES (123.45, 0); INSERT INTO precision (value, scale) VALUES (12345, 2); INSERT INTO precision (value, scale) VALUES (123.45, 2); INSERT INTO precision (value, scale) VALUES (12.345, 2); INSERT INTO precision (value, scale) VALUES (1234.5, 2); commit; SET SERVEROUTPUT ON DECLARE v_integer NUMBER(5); v_scale_2 NUMBER(5,2); v_real NUMBER; CURSOR scale_0_cur IS SELECT value FROM precision WHERE scale = 0; CURSOR scale_2_cur IS SELECT value FROM precision WHERE scale = 2; BEGIN DBMS_OUTPUT.PUT_LINE('====== PRECISION 5 SCALE 0 ====='); OPEN scale_0_cur; -- Loop thorugh all records that have a scale of zero LOOP FETCH scale_0_cur INTO v_real; EXIT WHEN scale_0_cur%NOTFOUND; -- Assign different values to the v_integer variable -- to see how it handles it BEGIN DBMS_OUTPUT.PUT_LINE(' '); DBMS_OUTPUT.PUT_LINE('Assigned: '||v_real); v_integer := v_real; DBMS_OUTPUT.PUT_LINE('Stored: '||v_integer); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Exception: '||sqlerrm); END; END LOOP; CLOSE scale_0_cur; DBMS_OUTPUT.PUT_LINE(' '); DBMS_OUTPUT.PUT_LINE('====== PRECISION 5 SCALE 2 ====='); OPEN scale_2_cur; -- Loop through all records that have a scale of 2 LOOP FETCH scale_2_cur INTO v_real; EXIT WHEN scale_2_cur%NOTFOUND; -- Assign different values to the v_scale_2 variable -- to see how it handles it BEGIN DBMS_OUTPUT.PUT_LINE(' '); DBMS_OUTPUT.PUT_LINE('Assigned: '||v_real); v_scale_2 := v_real; DBMS_OUTPUT.PUT_LINE('Stored: '||v_scale_2); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Exception: '||sqlerrm); END; END LOOP; CLOSE scale_2_cur; END; /
<reponame>mevlanaayas/miye-behance-collector import sendgrid import os from sendgrid.helpers.mail import * USER_SIDE_ERROR_REPORT_MAIL_LIST = os.environ.get('USER_SIDE_ERROR_REPORT_MAIL_LIST') PROGRAM_SIDE_ERROR_REPORT_MAIL_LIST = os.environ.get('PROGRAM_SIDE_ERROR_REPORT_MAIL_LIST') def report(subj, cont, report_code): sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY')) from_email = Email("<EMAIL>") to_email = Email("<EMAIL>") subject = subj content = cont sg_mail = Mail(from_email, subject, to_email, content) sg.client.mail.send.post(request_body=sg_mail.get())
const { pool } = require('../database') /** * * @param {*} param0 * @param {String} param0.username * @param {Number} param0.limit * @return {Promise} * */ function getCreatorNotifications({ username, limit }) { return new Promise((resolve, reject) => { pool.query( `SELECT id,heading,description,created_at FROM notifications WHERE creator=? ORDER BY created_at DESC LIMIT ${limit}`, [username], (error, results) => { if (error) { return reject(error) } return resolve(results) } ) }) } module.exports = getCreatorNotifications
#!/bin/bash set -e set -o xtrace if [ -z "${on_exit_hooks:-}" ]; then on_exit_hooks=() fi on_exit() { for i in $(seq $((${#on_exit_hooks[*]} - 1)) -1 0); do eval "${on_exit_hooks[$i]}" done } add_on_exit() { local n=${#on_exit_hooks[*]} on_exit_hooks[$n]="$*" if [[ $n -eq 0 ]]; then trap on_exit EXIT fi }
<gh_stars>1-10 // Code generated by entc, DO NOT EDIT. package ent import ( "context" "fmt" "time" "github.com/blushft/strana/modules/sink/reporter/store/ent/alias" "github.com/blushft/strana/modules/sink/reporter/store/ent/event" "github.com/blushft/strana/modules/sink/reporter/store/ent/group" "github.com/blushft/strana/modules/sink/reporter/store/ent/predicate" "github.com/blushft/strana/modules/sink/reporter/store/ent/user" "github.com/facebook/ent/dialect/sql" "github.com/facebook/ent/dialect/sql/sqlgraph" "github.com/facebook/ent/schema/field" "github.com/google/uuid" ) // UserUpdate is the builder for updating User entities. type UserUpdate struct { config hooks []Hook mutation *UserMutation predicates []predicate.User } // Where adds a new predicate for the builder. func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate { uu.predicates = append(uu.predicates, ps...) return uu } // SetIsAnonymous sets the is_anonymous field. func (uu *UserUpdate) SetIsAnonymous(b bool) *UserUpdate { uu.mutation.SetIsAnonymous(b) return uu } // SetName sets the name field. func (uu *UserUpdate) SetName(s string) *UserUpdate { uu.mutation.SetName(s) return uu } // SetNillableName sets the name field if the given value is not nil. func (uu *UserUpdate) SetNillableName(s *string) *UserUpdate { if s != nil { uu.SetName(*s) } return uu } // ClearName clears the value of name. func (uu *UserUpdate) ClearName() *UserUpdate { uu.mutation.ClearName() return uu } // SetTitle sets the title field. func (uu *UserUpdate) SetTitle(s string) *UserUpdate { uu.mutation.SetTitle(s) return uu } // SetNillableTitle sets the title field if the given value is not nil. func (uu *UserUpdate) SetNillableTitle(s *string) *UserUpdate { if s != nil { uu.SetTitle(*s) } return uu } // ClearTitle clears the value of title. func (uu *UserUpdate) ClearTitle() *UserUpdate { uu.mutation.ClearTitle() return uu } // SetFirstName sets the first_name field. func (uu *UserUpdate) SetFirstName(s string) *UserUpdate { uu.mutation.SetFirstName(s) return uu } // SetNillableFirstName sets the first_name field if the given value is not nil. func (uu *UserUpdate) SetNillableFirstName(s *string) *UserUpdate { if s != nil { uu.SetFirstName(*s) } return uu } // ClearFirstName clears the value of first_name. func (uu *UserUpdate) ClearFirstName() *UserUpdate { uu.mutation.ClearFirstName() return uu } // SetLastName sets the last_name field. func (uu *UserUpdate) SetLastName(s string) *UserUpdate { uu.mutation.SetLastName(s) return uu } // SetNillableLastName sets the last_name field if the given value is not nil. func (uu *UserUpdate) SetNillableLastName(s *string) *UserUpdate { if s != nil { uu.SetLastName(*s) } return uu } // ClearLastName clears the value of last_name. func (uu *UserUpdate) ClearLastName() *UserUpdate { uu.mutation.ClearLastName() return uu } // SetEmail sets the email field. func (uu *UserUpdate) SetEmail(s string) *UserUpdate { uu.mutation.SetEmail(s) return uu } // SetNillableEmail sets the email field if the given value is not nil. func (uu *UserUpdate) SetNillableEmail(s *string) *UserUpdate { if s != nil { uu.SetEmail(*s) } return uu } // ClearEmail clears the value of email. func (uu *UserUpdate) ClearEmail() *UserUpdate { uu.mutation.ClearEmail() return uu } // SetUsername sets the username field. func (uu *UserUpdate) SetUsername(s string) *UserUpdate { uu.mutation.SetUsername(s) return uu } // SetNillableUsername sets the username field if the given value is not nil. func (uu *UserUpdate) SetNillableUsername(s *string) *UserUpdate { if s != nil { uu.SetUsername(*s) } return uu } // ClearUsername clears the value of username. func (uu *UserUpdate) ClearUsername() *UserUpdate { uu.mutation.ClearUsername() return uu } // SetAge sets the age field. func (uu *UserUpdate) SetAge(i int) *UserUpdate { uu.mutation.ResetAge() uu.mutation.SetAge(i) return uu } // SetNillableAge sets the age field if the given value is not nil. func (uu *UserUpdate) SetNillableAge(i *int) *UserUpdate { if i != nil { uu.SetAge(*i) } return uu } // AddAge adds i to age. func (uu *UserUpdate) AddAge(i int) *UserUpdate { uu.mutation.AddAge(i) return uu } // ClearAge clears the value of age. func (uu *UserUpdate) ClearAge() *UserUpdate { uu.mutation.ClearAge() return uu } // SetBirthday sets the birthday field. func (uu *UserUpdate) SetBirthday(t time.Time) *UserUpdate { uu.mutation.SetBirthday(t) return uu } // SetNillableBirthday sets the birthday field if the given value is not nil. func (uu *UserUpdate) SetNillableBirthday(t *time.Time) *UserUpdate { if t != nil { uu.SetBirthday(*t) } return uu } // ClearBirthday clears the value of birthday. func (uu *UserUpdate) ClearBirthday() *UserUpdate { uu.mutation.ClearBirthday() return uu } // SetGender sets the gender field. func (uu *UserUpdate) SetGender(u user.Gender) *UserUpdate { uu.mutation.SetGender(u) return uu } // SetNillableGender sets the gender field if the given value is not nil. func (uu *UserUpdate) SetNillableGender(u *user.Gender) *UserUpdate { if u != nil { uu.SetGender(*u) } return uu } // ClearGender clears the value of gender. func (uu *UserUpdate) ClearGender() *UserUpdate { uu.mutation.ClearGender() return uu } // SetPhone sets the phone field. func (uu *UserUpdate) SetPhone(s string) *UserUpdate { uu.mutation.SetPhone(s) return uu } // SetNillablePhone sets the phone field if the given value is not nil. func (uu *UserUpdate) SetNillablePhone(s *string) *UserUpdate { if s != nil { uu.SetPhone(*s) } return uu } // ClearPhone clears the value of phone. func (uu *UserUpdate) ClearPhone() *UserUpdate { uu.mutation.ClearPhone() return uu } // SetWebsite sets the website field. func (uu *UserUpdate) SetWebsite(s string) *UserUpdate { uu.mutation.SetWebsite(s) return uu } // SetNillableWebsite sets the website field if the given value is not nil. func (uu *UserUpdate) SetNillableWebsite(s *string) *UserUpdate { if s != nil { uu.SetWebsite(*s) } return uu } // ClearWebsite clears the value of website. func (uu *UserUpdate) ClearWebsite() *UserUpdate { uu.mutation.ClearWebsite() return uu } // SetExtra sets the extra field. func (uu *UserUpdate) SetExtra(m map[string]interface{}) *UserUpdate { uu.mutation.SetExtra(m) return uu } // ClearExtra clears the value of extra. func (uu *UserUpdate) ClearExtra() *UserUpdate { uu.mutation.ClearExtra() return uu } // AddAliasIDs adds the aliases edge to Alias by ids. func (uu *UserUpdate) AddAliasIDs(ids ...int) *UserUpdate { uu.mutation.AddAliasIDs(ids...) return uu } // AddAliases adds the aliases edges to Alias. func (uu *UserUpdate) AddAliases(a ...*Alias) *UserUpdate { ids := make([]int, len(a)) for i := range a { ids[i] = a[i].ID } return uu.AddAliasIDs(ids...) } // AddEventIDs adds the events edge to Event by ids. func (uu *UserUpdate) AddEventIDs(ids ...uuid.UUID) *UserUpdate { uu.mutation.AddEventIDs(ids...) return uu } // AddEvents adds the events edges to Event. func (uu *UserUpdate) AddEvents(e ...*Event) *UserUpdate { ids := make([]uuid.UUID, len(e)) for i := range e { ids[i] = e[i].ID } return uu.AddEventIDs(ids...) } // AddGroupIDs adds the groups edge to Group by ids. func (uu *UserUpdate) AddGroupIDs(ids ...int) *UserUpdate { uu.mutation.AddGroupIDs(ids...) return uu } // AddGroups adds the groups edges to Group. func (uu *UserUpdate) AddGroups(g ...*Group) *UserUpdate { ids := make([]int, len(g)) for i := range g { ids[i] = g[i].ID } return uu.AddGroupIDs(ids...) } // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation } // RemoveAliasIDs removes the aliases edge to Alias by ids. func (uu *UserUpdate) RemoveAliasIDs(ids ...int) *UserUpdate { uu.mutation.RemoveAliasIDs(ids...) return uu } // RemoveAliases removes aliases edges to Alias. func (uu *UserUpdate) RemoveAliases(a ...*Alias) *UserUpdate { ids := make([]int, len(a)) for i := range a { ids[i] = a[i].ID } return uu.RemoveAliasIDs(ids...) } // RemoveEventIDs removes the events edge to Event by ids. func (uu *UserUpdate) RemoveEventIDs(ids ...uuid.UUID) *UserUpdate { uu.mutation.RemoveEventIDs(ids...) return uu } // RemoveEvents removes events edges to Event. func (uu *UserUpdate) RemoveEvents(e ...*Event) *UserUpdate { ids := make([]uuid.UUID, len(e)) for i := range e { ids[i] = e[i].ID } return uu.RemoveEventIDs(ids...) } // RemoveGroupIDs removes the groups edge to Group by ids. func (uu *UserUpdate) RemoveGroupIDs(ids ...int) *UserUpdate { uu.mutation.RemoveGroupIDs(ids...) return uu } // RemoveGroups removes groups edges to Group. func (uu *UserUpdate) RemoveGroups(g ...*Group) *UserUpdate { ids := make([]int, len(g)) for i := range g { ids[i] = g[i].ID } return uu.RemoveGroupIDs(ids...) } // Save executes the query and returns the number of rows/vertices matched by this operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { if v, ok := uu.mutation.Gender(); ok { if err := user.GenderValidator(v); err != nil { return 0, &ValidationError{Name: "gender", err: fmt.Errorf("ent: validator failed for field \"gender\": %w", err)} } } var ( err error affected int ) if len(uu.hooks) == 0 { affected, err = uu.sqlSave(ctx) } else { var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*UserMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } uu.mutation = mutation affected, err = uu.sqlSave(ctx) mutation.done = true return affected, err }) for i := len(uu.hooks) - 1; i >= 0; i-- { mut = uu.hooks[i](mut) } if _, err := mut.Mutate(ctx, uu.mutation); err != nil { return 0, err } } return affected, err } // SaveX is like Save, but panics if an error occurs. func (uu *UserUpdate) SaveX(ctx context.Context) int { affected, err := uu.Save(ctx) if err != nil { panic(err) } return affected } // Exec executes the query. func (uu *UserUpdate) Exec(ctx context.Context) error { _, err := uu.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. func (uu *UserUpdate) ExecX(ctx context.Context) { if err := uu.Exec(ctx); err != nil { panic(err) } } func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ Table: user.Table, Columns: user.Columns, ID: &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldID, }, }, } if ps := uu.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } if value, ok := uu.mutation.IsAnonymous(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeBool, Value: value, Column: user.FieldIsAnonymous, }) } if value, ok := uu.mutation.Name(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldName, }) } if uu.mutation.NameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldName, }) } if value, ok := uu.mutation.Title(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldTitle, }) } if uu.mutation.TitleCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldTitle, }) } if value, ok := uu.mutation.FirstName(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldFirstName, }) } if uu.mutation.FirstNameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldFirstName, }) } if value, ok := uu.mutation.LastName(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldLastName, }) } if uu.mutation.LastNameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldLastName, }) } if value, ok := uu.mutation.Email(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldEmail, }) } if uu.mutation.EmailCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldEmail, }) } if value, ok := uu.mutation.Username(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldUsername, }) } if uu.mutation.UsernameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldUsername, }) } if value, ok := uu.mutation.Age(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt, Value: value, Column: user.FieldAge, }) } if value, ok := uu.mutation.AddedAge(); ok { _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ Type: field.TypeInt, Value: value, Column: user.FieldAge, }) } if uu.mutation.AgeCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: user.FieldAge, }) } if value, ok := uu.mutation.Birthday(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeTime, Value: value, Column: user.FieldBirthday, }) } if uu.mutation.BirthdayCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeTime, Column: user.FieldBirthday, }) } if value, ok := uu.mutation.Gender(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeEnum, Value: value, Column: user.FieldGender, }) } if uu.mutation.GenderCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeEnum, Column: user.FieldGender, }) } if value, ok := uu.mutation.Phone(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldPhone, }) } if uu.mutation.PhoneCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldPhone, }) } if value, ok := uu.mutation.Website(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldWebsite, }) } if uu.mutation.WebsiteCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldWebsite, }) } if value, ok := uu.mutation.Extra(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeJSON, Value: value, Column: user.FieldExtra, }) } if uu.mutation.ExtraCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeJSON, Column: user.FieldExtra, }) } if nodes := uu.mutation.RemovedAliasesIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, Table: user.AliasesTable, Columns: []string{user.AliasesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: alias.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } if nodes := uu.mutation.AliasesIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, Table: user.AliasesTable, Columns: []string{user.AliasesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: alias.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } if nodes := uu.mutation.RemovedEventsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: true, Table: user.EventsTable, Columns: []string{user.EventsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeUUID, Column: event.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } if nodes := uu.mutation.EventsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: true, Table: user.EventsTable, Columns: []string{user.EventsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeUUID, Column: event.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } if nodes := uu.mutation.RemovedGroupsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2M, Inverse: true, Table: user.GroupsTable, Columns: user.GroupsPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: group.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } if nodes := uu.mutation.GroupsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2M, Inverse: true, Table: user.GroupsTable, Columns: user.GroupsPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: group.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} } else if cerr, ok := isSQLConstraintError(err); ok { err = cerr } return 0, err } return n, nil } // UserUpdateOne is the builder for updating a single User entity. type UserUpdateOne struct { config hooks []Hook mutation *UserMutation } // SetIsAnonymous sets the is_anonymous field. func (uuo *UserUpdateOne) SetIsAnonymous(b bool) *UserUpdateOne { uuo.mutation.SetIsAnonymous(b) return uuo } // SetName sets the name field. func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne { uuo.mutation.SetName(s) return uuo } // SetNillableName sets the name field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableName(s *string) *UserUpdateOne { if s != nil { uuo.SetName(*s) } return uuo } // ClearName clears the value of name. func (uuo *UserUpdateOne) ClearName() *UserUpdateOne { uuo.mutation.ClearName() return uuo } // SetTitle sets the title field. func (uuo *UserUpdateOne) SetTitle(s string) *UserUpdateOne { uuo.mutation.SetTitle(s) return uuo } // SetNillableTitle sets the title field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableTitle(s *string) *UserUpdateOne { if s != nil { uuo.SetTitle(*s) } return uuo } // ClearTitle clears the value of title. func (uuo *UserUpdateOne) ClearTitle() *UserUpdateOne { uuo.mutation.ClearTitle() return uuo } // SetFirstName sets the first_name field. func (uuo *UserUpdateOne) SetFirstName(s string) *UserUpdateOne { uuo.mutation.SetFirstName(s) return uuo } // SetNillableFirstName sets the first_name field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableFirstName(s *string) *UserUpdateOne { if s != nil { uuo.SetFirstName(*s) } return uuo } // ClearFirstName clears the value of first_name. func (uuo *UserUpdateOne) ClearFirstName() *UserUpdateOne { uuo.mutation.ClearFirstName() return uuo } // SetLastName sets the last_name field. func (uuo *UserUpdateOne) SetLastName(s string) *UserUpdateOne { uuo.mutation.SetLastName(s) return uuo } // SetNillableLastName sets the last_name field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableLastName(s *string) *UserUpdateOne { if s != nil { uuo.SetLastName(*s) } return uuo } // ClearLastName clears the value of last_name. func (uuo *UserUpdateOne) ClearLastName() *UserUpdateOne { uuo.mutation.ClearLastName() return uuo } // SetEmail sets the email field. func (uuo *UserUpdateOne) SetEmail(s string) *UserUpdateOne { uuo.mutation.SetEmail(s) return uuo } // SetNillableEmail sets the email field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableEmail(s *string) *UserUpdateOne { if s != nil { uuo.SetEmail(*s) } return uuo } // ClearEmail clears the value of email. func (uuo *UserUpdateOne) ClearEmail() *UserUpdateOne { uuo.mutation.ClearEmail() return uuo } // SetUsername sets the username field. func (uuo *UserUpdateOne) SetUsername(s string) *UserUpdateOne { uuo.mutation.SetUsername(s) return uuo } // SetNillableUsername sets the username field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableUsername(s *string) *UserUpdateOne { if s != nil { uuo.SetUsername(*s) } return uuo } // ClearUsername clears the value of username. func (uuo *UserUpdateOne) ClearUsername() *UserUpdateOne { uuo.mutation.ClearUsername() return uuo } // SetAge sets the age field. func (uuo *UserUpdateOne) SetAge(i int) *UserUpdateOne { uuo.mutation.ResetAge() uuo.mutation.SetAge(i) return uuo } // SetNillableAge sets the age field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableAge(i *int) *UserUpdateOne { if i != nil { uuo.SetAge(*i) } return uuo } // AddAge adds i to age. func (uuo *UserUpdateOne) AddAge(i int) *UserUpdateOne { uuo.mutation.AddAge(i) return uuo } // ClearAge clears the value of age. func (uuo *UserUpdateOne) ClearAge() *UserUpdateOne { uuo.mutation.ClearAge() return uuo } // SetBirthday sets the birthday field. func (uuo *UserUpdateOne) SetBirthday(t time.Time) *UserUpdateOne { uuo.mutation.SetBirthday(t) return uuo } // SetNillableBirthday sets the birthday field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableBirthday(t *time.Time) *UserUpdateOne { if t != nil { uuo.SetBirthday(*t) } return uuo } // ClearBirthday clears the value of birthday. func (uuo *UserUpdateOne) ClearBirthday() *UserUpdateOne { uuo.mutation.ClearBirthday() return uuo } // SetGender sets the gender field. func (uuo *UserUpdateOne) SetGender(u user.Gender) *UserUpdateOne { uuo.mutation.SetGender(u) return uuo } // SetNillableGender sets the gender field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableGender(u *user.Gender) *UserUpdateOne { if u != nil { uuo.SetGender(*u) } return uuo } // ClearGender clears the value of gender. func (uuo *UserUpdateOne) ClearGender() *UserUpdateOne { uuo.mutation.ClearGender() return uuo } // SetPhone sets the phone field. func (uuo *UserUpdateOne) SetPhone(s string) *UserUpdateOne { uuo.mutation.SetPhone(s) return uuo } // SetNillablePhone sets the phone field if the given value is not nil. func (uuo *UserUpdateOne) SetNillablePhone(s *string) *UserUpdateOne { if s != nil { uuo.SetPhone(*s) } return uuo } // ClearPhone clears the value of phone. func (uuo *UserUpdateOne) ClearPhone() *UserUpdateOne { uuo.mutation.ClearPhone() return uuo } // SetWebsite sets the website field. func (uuo *UserUpdateOne) SetWebsite(s string) *UserUpdateOne { uuo.mutation.SetWebsite(s) return uuo } // SetNillableWebsite sets the website field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableWebsite(s *string) *UserUpdateOne { if s != nil { uuo.SetWebsite(*s) } return uuo } // ClearWebsite clears the value of website. func (uuo *UserUpdateOne) ClearWebsite() *UserUpdateOne { uuo.mutation.ClearWebsite() return uuo } // SetExtra sets the extra field. func (uuo *UserUpdateOne) SetExtra(m map[string]interface{}) *UserUpdateOne { uuo.mutation.SetExtra(m) return uuo } // ClearExtra clears the value of extra. func (uuo *UserUpdateOne) ClearExtra() *UserUpdateOne { uuo.mutation.ClearExtra() return uuo } // AddAliasIDs adds the aliases edge to Alias by ids. func (uuo *UserUpdateOne) AddAliasIDs(ids ...int) *UserUpdateOne { uuo.mutation.AddAliasIDs(ids...) return uuo } // AddAliases adds the aliases edges to Alias. func (uuo *UserUpdateOne) AddAliases(a ...*Alias) *UserUpdateOne { ids := make([]int, len(a)) for i := range a { ids[i] = a[i].ID } return uuo.AddAliasIDs(ids...) } // AddEventIDs adds the events edge to Event by ids. func (uuo *UserUpdateOne) AddEventIDs(ids ...uuid.UUID) *UserUpdateOne { uuo.mutation.AddEventIDs(ids...) return uuo } // AddEvents adds the events edges to Event. func (uuo *UserUpdateOne) AddEvents(e ...*Event) *UserUpdateOne { ids := make([]uuid.UUID, len(e)) for i := range e { ids[i] = e[i].ID } return uuo.AddEventIDs(ids...) } // AddGroupIDs adds the groups edge to Group by ids. func (uuo *UserUpdateOne) AddGroupIDs(ids ...int) *UserUpdateOne { uuo.mutation.AddGroupIDs(ids...) return uuo } // AddGroups adds the groups edges to Group. func (uuo *UserUpdateOne) AddGroups(g ...*Group) *UserUpdateOne { ids := make([]int, len(g)) for i := range g { ids[i] = g[i].ID } return uuo.AddGroupIDs(ids...) } // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation } // RemoveAliasIDs removes the aliases edge to Alias by ids. func (uuo *UserUpdateOne) RemoveAliasIDs(ids ...int) *UserUpdateOne { uuo.mutation.RemoveAliasIDs(ids...) return uuo } // RemoveAliases removes aliases edges to Alias. func (uuo *UserUpdateOne) RemoveAliases(a ...*Alias) *UserUpdateOne { ids := make([]int, len(a)) for i := range a { ids[i] = a[i].ID } return uuo.RemoveAliasIDs(ids...) } // RemoveEventIDs removes the events edge to Event by ids. func (uuo *UserUpdateOne) RemoveEventIDs(ids ...uuid.UUID) *UserUpdateOne { uuo.mutation.RemoveEventIDs(ids...) return uuo } // RemoveEvents removes events edges to Event. func (uuo *UserUpdateOne) RemoveEvents(e ...*Event) *UserUpdateOne { ids := make([]uuid.UUID, len(e)) for i := range e { ids[i] = e[i].ID } return uuo.RemoveEventIDs(ids...) } // RemoveGroupIDs removes the groups edge to Group by ids. func (uuo *UserUpdateOne) RemoveGroupIDs(ids ...int) *UserUpdateOne { uuo.mutation.RemoveGroupIDs(ids...) return uuo } // RemoveGroups removes groups edges to Group. func (uuo *UserUpdateOne) RemoveGroups(g ...*Group) *UserUpdateOne { ids := make([]int, len(g)) for i := range g { ids[i] = g[i].ID } return uuo.RemoveGroupIDs(ids...) } // Save executes the query and returns the updated entity. func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { if v, ok := uuo.mutation.Gender(); ok { if err := user.GenderValidator(v); err != nil { return nil, &ValidationError{Name: "gender", err: fmt.Errorf("ent: validator failed for field \"gender\": %w", err)} } } var ( err error node *User ) if len(uuo.hooks) == 0 { node, err = uuo.sqlSave(ctx) } else { var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*UserMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } uuo.mutation = mutation node, err = uuo.sqlSave(ctx) mutation.done = true return node, err }) for i := len(uuo.hooks) - 1; i >= 0; i-- { mut = uuo.hooks[i](mut) } if _, err := mut.Mutate(ctx, uuo.mutation); err != nil { return nil, err } } return node, err } // SaveX is like Save, but panics if an error occurs. func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User { u, err := uuo.Save(ctx) if err != nil { panic(err) } return u } // Exec executes the query on the entity. func (uuo *UserUpdateOne) Exec(ctx context.Context) error { _, err := uuo.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. func (uuo *UserUpdateOne) ExecX(ctx context.Context) { if err := uuo.Exec(ctx); err != nil { panic(err) } } func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (u *User, err error) { _spec := &sqlgraph.UpdateSpec{ Node: &sqlgraph.NodeSpec{ Table: user.Table, Columns: user.Columns, ID: &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldID, }, }, } id, ok := uuo.mutation.ID() if !ok { return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing User.ID for update")} } _spec.Node.ID.Value = id if value, ok := uuo.mutation.IsAnonymous(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeBool, Value: value, Column: user.FieldIsAnonymous, }) } if value, ok := uuo.mutation.Name(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldName, }) } if uuo.mutation.NameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldName, }) } if value, ok := uuo.mutation.Title(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldTitle, }) } if uuo.mutation.TitleCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldTitle, }) } if value, ok := uuo.mutation.FirstName(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldFirstName, }) } if uuo.mutation.FirstNameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldFirstName, }) } if value, ok := uuo.mutation.LastName(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldLastName, }) } if uuo.mutation.LastNameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldLastName, }) } if value, ok := uuo.mutation.Email(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldEmail, }) } if uuo.mutation.EmailCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldEmail, }) } if value, ok := uuo.mutation.Username(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldUsername, }) } if uuo.mutation.UsernameCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldUsername, }) } if value, ok := uuo.mutation.Age(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeInt, Value: value, Column: user.FieldAge, }) } if value, ok := uuo.mutation.AddedAge(); ok { _spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{ Type: field.TypeInt, Value: value, Column: user.FieldAge, }) } if uuo.mutation.AgeCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: user.FieldAge, }) } if value, ok := uuo.mutation.Birthday(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeTime, Value: value, Column: user.FieldBirthday, }) } if uuo.mutation.BirthdayCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeTime, Column: user.FieldBirthday, }) } if value, ok := uuo.mutation.Gender(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeEnum, Value: value, Column: user.FieldGender, }) } if uuo.mutation.GenderCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeEnum, Column: user.FieldGender, }) } if value, ok := uuo.mutation.Phone(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldPhone, }) } if uuo.mutation.PhoneCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldPhone, }) } if value, ok := uuo.mutation.Website(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeString, Value: value, Column: user.FieldWebsite, }) } if uuo.mutation.WebsiteCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeString, Column: user.FieldWebsite, }) } if value, ok := uuo.mutation.Extra(); ok { _spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{ Type: field.TypeJSON, Value: value, Column: user.FieldExtra, }) } if uuo.mutation.ExtraCleared() { _spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{ Type: field.TypeJSON, Column: user.FieldExtra, }) } if nodes := uuo.mutation.RemovedAliasesIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, Table: user.AliasesTable, Columns: []string{user.AliasesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: alias.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } if nodes := uuo.mutation.AliasesIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: false, Table: user.AliasesTable, Columns: []string{user.AliasesColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: alias.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } if nodes := uuo.mutation.RemovedEventsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: true, Table: user.EventsTable, Columns: []string{user.EventsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeUUID, Column: event.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } if nodes := uuo.mutation.EventsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, Inverse: true, Table: user.EventsTable, Columns: []string{user.EventsColumn}, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeUUID, Column: event.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } if nodes := uuo.mutation.RemovedGroupsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2M, Inverse: true, Table: user.GroupsTable, Columns: user.GroupsPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: group.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Clear = append(_spec.Edges.Clear, edge) } if nodes := uuo.mutation.GroupsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.M2M, Inverse: true, Table: user.GroupsTable, Columns: user.GroupsPrimaryKey, Bidi: false, Target: &sqlgraph.EdgeTarget{ IDSpec: &sqlgraph.FieldSpec{ Type: field.TypeInt, Column: group.FieldID, }, }, } for _, k := range nodes { edge.Target.Nodes = append(edge.Target.Nodes, k) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } u = &User{config: uuo.config} _spec.Assign = u.assignValues _spec.ScanValues = u.scanValues() if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} } else if cerr, ok := isSQLConstraintError(err); ok { err = cerr } return nil, err } return u, nil }
#!/bin/bash ## Script from https://github.com/deepguider/dg_cart_ros ## Git clone sensor ros file git clone https://github.com/deepguider/dg_cart_ros.git src/dg_cart_ros # symbolic link for door detect weight file cd src/dg_cart_ros/src/door_detect ln -sf ../../../../data_door_detect/checkpoints . cd ../../../.. ## Build and install dg_cart_ros source /opt/ros/melodic/setup.bash catkin_make install ## Add udev rules for accessing and mounting sensor devices sudo cp src/dg_cart_ros/udev.rules /etc/udev/rules.d/99-dg-device.rules ## Run sensor node with following command, bagfile will be saved at home directory # roslaunch dg_cart_ros dg_record_sensor.launch
/* **** Notes Count words. Remarks: Refer at fn. cv_wo. */ # define CAR # include "./../../../incl/config.h" signed(__cdecl ct_wo(signed char(*sym),signed char(*argp))) { auto signed i,r; // if(!sym) return(0x00); if(!argp) return(0x00); if(!(*argp)) return(0x00); r = cue(sym,argp); if(!r) return(0x00); argp = (r+(argp)); return(0x01+(ct_wo(sym,argp))); }
#include "simulator.hpp" #include <chrono> #include <iostream> #include <random> #include <vector> void Simulator::_register_methods() { // Exposes internal methods to be called from GDScript godot::register_method("setHamiltonian", &Simulator::_setHamiltonian); godot::register_method("setPsi0", &Simulator::_setPsi0); godot::register_method("getHamiltonian", &Simulator::_getHamiltonian); godot::register_method("getPsi0", &Simulator::_getPsi0); godot::register_method("getPropagator", &Simulator::_getPropagator); godot::register_method("getCurrentStateSize", &Simulator::_getCurrentStateSize); godot::register_method("getCurrentState", &Simulator::_getCurrentState); godot::register_method("getProbabilityDensity", &Simulator::_getProbabilityDensity); godot::register_method("getErrorMessage", &Simulator::_getErrorMessage); godot::register_method("measure", &Simulator::_measure); godot::register_method("setSize", &Simulator::_setSize); godot::register_method("step", &Simulator::_runOneStep); } Simulator::Simulator() { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); _gen = std::default_random_engine(seed); } void Simulator::_setSize(const int size){ // Sets the size of the system _size = size; } void Simulator::_setHamiltonian(godot::PoolVector2Array arr){ // Sets the hamiltonian _hamiltonian = Eigen::MatrixXcd(_size,_size); for(int x = 0; x < arr.size(); ++x){ godot::Vector2 v = arr[x]; _hamiltonian(x) = std::complex<double>(v.x,v.y); } } void Simulator::_setPsi0(godot::PoolVector2Array arr){ // Sets the initial wavefunction _psi0 = Eigen::VectorXcd(_size); for(int x = 0; x < arr.size(); ++x){ godot::Vector2 v = arr[x]; _psi0(x) = std::complex<double>(v.x,v.y); } _currentState = Eigen::Vector3cd(_psi0); } godot::PoolVector2Array Simulator::_getHamiltonian(){ // Returns the hamiltonian godot::PoolVector2Array value; for(int x = 0; x < _hamiltonian.size(); ++x){ auto c = _hamiltonian(x); godot::Vector2 v = godot::Vector2(c.real(),c.imag()); value.append(v); } return value; } godot::PoolVector2Array Simulator::_getPsi0(){ // Returns the initial wavefunction godot::PoolVector2Array value; for(int x = 0; x < _psi0.size(); ++x){ auto c = _psi0(x); godot::Vector2 v = godot::Vector2(c.real(),c.imag()); value.append(v); } return value; } godot::PoolVector2Array Simulator::_getCurrentState(){ // Returns the current wavefunction godot::PoolVector2Array value; for(int x = 0; x < _currentState.size(); ++x){ auto c = _currentState(x); godot::Vector2 v = godot::Vector2(c.real(),c.imag()); value.append(v); } return value; } godot::PoolVector2Array Simulator::_getPropagator(){ // Returns the current propagator--translates to row major? godot::PoolVector2Array value; for(int x = 0; x < _propagator.size(); ++x){ auto c = _propagator(x); godot::Vector2 v = godot::Vector2(c.real(),c.imag()); value.append(v); } return value; } godot::PoolRealArray Simulator::_getProbabilityDensity() { // Returns mod ** 2 of the current state // There is some funkiness in this method--Eigen should handle // // v * v.conjugate() // // just fine, but running in GUT is causing crashes. I resorted // to manually running the elementwise vector product instead godot::PoolRealArray density; std::complex<double> temp; _probabilityDensity = std::vector<double>(_size); for (int x = 0; x < _size; ++x) { temp = _currentState[x] * std::conj(_currentState[x]); float c = temp.real(); _probabilityDensity[x] = c; density.append(c); } return density; } int Simulator::_sampleProbabilityDensity() { std::discrete_distribution<int> dist(_probabilityDensity.begin(), _probabilityDensity.end()); return dist(_gen); } int Simulator::_measure() { _getProbabilityDensity(); return _sampleProbabilityDensity(); } int factorial(int n) { // Simple factorial implementation -- not needed anymore? if (n == 0) { return 1; } else { return n * factorial(n - 1); } } int Simulator::_getCurrentStateSize() { return _currentState.size(); } int Simulator::_getPropagatorRows() { // Rename to _getNumPropagatorRows() return _propagator.rows(); } int Simulator::_getPropagatorCols() { // Redundant? cols == rows == _size? return _propagator.cols(); } void Simulator::_setPropagator(Eigen::MatrixXcd temp){ _propagator = temp.exp(); } void Simulator::_runOneStep(float delta){ // Applies the propagator once; called each clock cycle _time += delta; Eigen::MatrixXcd temp = _hamiltonian * delta * std::complex<double>(0,-1); _setPropagator(temp); _currentState = _propagator * _currentState; } float Simulator::_getTime(){ return _time; } void Simulator::_init() { } godot::String Simulator::_getErrorMessage() { return godot::String("HELLO"); }
import * as util from "../util.js"; import type { Request, Warnings } from "../util.js"; import jsesc from "jsesc"; const supportedArgs = new Set([ "url", "request", "user-agent", "cookie", "data", "data-raw", "data-ascii", "data-binary", "data-urlencode", "json", "referer", "form", "form-string", "get", "header", "head", "no-head", "user", "proxy-user", "proxy", "max-time", ]); const quote = (str: string): string => { return jsesc(str, { quotes: "single" }).replace(/"/g, '""'); }; export const _toCFML = (request: Request, warnings: Warnings = []): string => { let cfmlCode = ""; cfmlCode += "httpService = new http();\n"; cfmlCode += 'httpService.setUrl("' + quote(request.url as string) + '");\n'; cfmlCode += 'httpService.setMethod("' + quote(request.method) + '");\n'; if (request.cookies) { for (const [headerName, headerValue] of request.cookies) { cfmlCode += 'httpService.addParam(type="cookie", name="' + quote(headerName) + '", value="' + quote(headerValue) + '");\n'; } util.deleteHeader(request, "Cookie"); } if (request.headers && request.headers.length) { for (const [headerName, headerValue] of request.headers) { cfmlCode += 'httpService.addParam(type="header", name="' + quote(headerName) + '", value="' + quote(headerValue as string) + '");\n'; } } if (request.timeout) { cfmlCode += "httpService.setTimeout(" + (parseInt(request.timeout) || 0) + ");\n"; } if (request.auth) { const [authUser, authPassword] = request.auth; cfmlCode += 'httpService.setUsername("' + quote(authUser) + '");\n'; cfmlCode += 'httpService.setPassword("' + quote(authPassword || "") + '");\n'; } if (request.proxy) { let proxy = request.proxy; let proxyPort = "1080"; const proxyPart = (request.proxy as string).match(/:([0-9]+)/); if (proxyPart) { proxy = request.proxy.slice(0, proxyPart.index); proxyPort = proxyPart[1]; } cfmlCode += 'httpService.setProxyServer("' + quote(proxy) + '");\n'; cfmlCode += "httpService.setProxyPort(" + quote(proxyPort) + ");\n"; if (request.proxyAuth) { const [proxyUser, proxyPassword] = request.proxyAuth.split(/:(.*)/s, 2); cfmlCode += 'httpService.setProxyUser("' + quote(proxyUser) + '");\n'; cfmlCode += 'httpService.setProxyPassword("' + quote(proxyPassword || "") + '");\n'; } } if (request.data || request.multipartUploads) { if (request.multipartUploads) { for (const m of request.multipartUploads) { if ("contentFile" in m) { cfmlCode += 'httpService.addParam(type="file", name="' + quote(m.name) + '", file="#expandPath("' + quote(m.contentFile) + '")#");\n'; } else { cfmlCode += 'httpService.addParam(type="formfield", name="' + quote(m.name) + '", value="' + quote(m.content) + '");\n'; } } } else if ( !request.isDataRaw && (request.data as string).charAt(0) === "@" ) { cfmlCode += 'httpService.addParam(type="body", value="#' + (request.isDataBinary ? "fileReadBinary" : "fileRead") + '(expandPath("' + quote((request.data as string).substring(1)) + '"))#");\n'; } else { cfmlCode += 'httpService.addParam(type="body", value="' + quote(request.data as string) + '");\n'; } } cfmlCode += "\nresult = httpService.send().getPrefix();\n"; cfmlCode += "writeDump(result);\n"; return cfmlCode; }; export const toCFMLWarn = ( curlCommand: string | string[], warnings: Warnings = [] ): [string, Warnings] => { const request = util.parseCurlCommand(curlCommand, supportedArgs, warnings); const cfml = _toCFML(request, warnings); return [cfml, warnings]; }; export const toCFML = (curlCommand: string | string[]): string => { return toCFMLWarn(curlCommand)[0]; };
const squares = []; for (let i = 1; i <= 10; i++) { squares.push(i * i); }
package implementation; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author minchoba * 백준 2740번: 행렬 곱셈 * * @see https://www.acmicpc.net/problem/2740/ * */ public class Boj2740 { private static final String NEW_LINE = "\n", SPACE = " "; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[][] matrix1 = new int[N][M]; for(int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for(int j = 0; j < M; j++) { matrix1[i][j] = Integer.parseInt(st.nextToken()); } } st = new StringTokenizer(br.readLine()); st.nextToken(); int K = Integer.parseInt(st.nextToken()); int[][] matrix2 = new int[M][K]; for(int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine()); for(int j = 0; j < K; j++) { matrix2[i][j] = Integer.parseInt(st.nextToken()); } } System.out.println(cartesian(N, M, K, matrix1, matrix2)); } private static StringBuilder cartesian(int n, int m, int k, int[][] arr1, int[][] arr2) { StringBuilder sb = new StringBuilder(); for(int x = 0; x < n; x++) { for(int y = 0; y < k; y++) { int tmp = 0; for(int i = 0; i < m; i++) { // 행렬 곱 N x M, M x K tmp += arr1[x][i] * arr2[i][y]; } sb.append(tmp).append(SPACE); } sb.append(NEW_LINE); } return sb; } }
package com.cgfy.mybatis.bussApi.domain.model; import com.cgfy.mybatis.base.domain.model.BaseModel; import java.io.Serializable; import javax.persistence.*; /** * cgfy * * @author cgfy_web */ @Table(name = "test_gen") public class TestGen implements BaseModel, Serializable { /** * 主键 */ @Id private String id; /** * 姓名 */ private String name; /** * 性别 */ private String sex; /** * 年龄 */ private Integer age; /** * 电话 */ @Column(name = "mobile_phone") private String mobilePhone; /** * 家庭住址 */ @Column(name = "home_add_test") private String homeAddTest; private static final long serialVersionUID = 1L; /** * 获取主键 * * @return id - 主键 */ public String getId() { return id; } /** * 设置主键 * * @param id 主键 */ public void setId(String id) { this.id = id; } /** * 获取姓名 * * @return name - 姓名 */ public String getName() { return name; } /** * 设置姓名 * * @param name 姓名 */ public void setName(String name) { this.name = name; } /** * 获取性别 * * @return sex - 性别 */ public String getSex() { return sex; } /** * 设置性别 * * @param sex 性别 */ public void setSex(String sex) { this.sex = sex; } /** * 获取年龄 * * @return age - 年龄 */ public Integer getAge() { return age; } /** * 设置年龄 * * @param age 年龄 */ public void setAge(Integer age) { this.age = age; } /** * 获取电话 * * @return mobile_phone - 电话 */ public String getMobilePhone() { return mobilePhone; } /** * 设置电话 * * @param mobilePhone 电话 */ public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } /** * 获取家庭住址 * * @return home_add_test - 家庭住址 */ public String getHomeAddTest() { return homeAddTest; } /** * 设置家庭住址 * * @param homeAddTest 家庭住址 */ public void setHomeAddTest(String homeAddTest) { this.homeAddTest = homeAddTest; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.fuseki.mgt; import static org.apache.jena.fuseki.Fuseki.serverLog ; import java.util.List ; import javax.servlet.http.HttpServlet ; import org.apache.jena.fuseki.Fuseki ; import org.apache.jena.fuseki.server.FusekiErrorHandler ; import org.apache.jena.fuseki.servlets.DumpServlet ; import org.eclipse.jetty.server.Connector ; import org.eclipse.jetty.server.Server ; import org.eclipse.jetty.server.nio.SelectChannelConnector ; import org.eclipse.jetty.servlet.ServletContextHandler ; import org.eclipse.jetty.servlet.ServletHolder ; public class ManagementServer { public static Server createManagementServer(int mgtPort) { Fuseki.serverLog.info("Adding management functions") ; // Separate Jetty server Server server = new Server() ; // BlockingChannelConnector bcConnector = new BlockingChannelConnector() ; // bcConnector.setUseDirectBuffers(false) ; // Connector connector = bcConnector ; Connector connector = new SelectChannelConnector() ; // Ignore idle time. // If set, then if this goes off, it keeps going off and you get a lot of log messages. connector.setMaxIdleTime(0) ; // Jetty outputs a lot of messages if this goes off. connector.setPort(mgtPort); server.addConnector(connector) ; ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setErrorHandler(new FusekiErrorHandler()) ; server.setHandler(context); // Add the server control servlet addServlet(context, new MgtCmdServlet(), "/mgt") ; addServlet(context, new DumpServlet(), "/dump") ; addServlet(context, new StatsServlet(), "/stats") ; addServlet(context, new PingServlet(), "/ping") ; return server ; // Old plan // // Development : server control panel. // addServlet(context, new ServerServlet(), "/server") ; // addServlet(context, new ActionBackup(), "/backup") ; } // SHARE private static void addServlet(ServletContextHandler context, String datasetPath, HttpServlet servlet, List<String> pathSpecs) { for ( String pathSpec : pathSpecs ) { if ( pathSpec.endsWith("/") ) pathSpec = pathSpec.substring(0, pathSpec.length()-1) ; if ( pathSpec.startsWith("/") ) pathSpec = pathSpec.substring(1, pathSpec.length()) ; addServlet(context, servlet, datasetPath+"/"+pathSpec) ; } } private static void addServlet(ServletContextHandler context, HttpServlet servlet, String pathSpec) { ServletHolder holder = new ServletHolder(servlet) ; addServlet(context, holder, pathSpec) ; } private static void addServlet(ServletContextHandler context, ServletHolder holder, String pathSpec) { serverLog.debug("Add servlet @ "+pathSpec) ; context.addServlet(holder, pathSpec) ; } }
function isDestinationOccupied(creep, destinationRoomName) { if ( Game.rooms[destinationRoomName] && Game.rooms[destinationRoomName].lookForAt( LOOK_CREEPS, creep.memory.destination.x, creep.memory.destination.y ).length > 0 ) { return true; // Destination is occupied } else { return false; // Destination is not occupied } }
# python3 finetune_v2.py --data=./data/TrainVal/ --mode=train_then_finetune --net=densenet_169 --workers=2 \ # --train_lr=0.0004 --train_epochs=4 --train_steps_per_epoch=640 \ # --finetune_lr1=0.0002 --finetune_epochs1=10 --finetune_steps_per_epoch1=1280 \ # --finetune_lr2=0.0002 --finetune_epochs2=40 --finetune_steps_per_epoch2=1280 \ # --freeze=139 --dropout=0.5 --l2=0.1 \ # --batch=64 # python3 finetune_v2.py --data=./data/TrainVal/ --mode=train_then_finetune --net=densenet_169 --workers=2 \ # --train_lr=0.0004 --train_epochs=4 --train_steps_per_epoch=640 \ # --finetune_lr1=0.0002 --finetune_epochs1=10 --finetune_steps_per_epoch1=1280 \ # --finetune_lr2=0.0002 --finetune_epochs2=40 --finetune_steps_per_epoch2=1280 \ # --freeze=139 --dropout=0.5 --l2=0.01 \ # --batch=64 python3 finetune_v2.py --data=./data/TrainVal/ --mode=train_then_finetune --net=nasnetmobile --workers=2 \ --train_lr=0.0004 --train_epochs=4 --train_steps_per_epoch=160 \ --finetune_lr1=0.0001 --finetune_epochs1=0 --finetune_steps_per_epoch1=320 \ --finetune_lr2=0.0001 --finetune_epochs2=60 --finetune_steps_per_epoch2=320 \ --freeze=532 --dropout=0 --l2=0 \ --batch=256 python3 finetune_v2.py --data=./data/TrainVal/ --mode=train_then_finetune --net=nasnetmobile --workers=2 \ --train_lr=0.0004 --train_epochs=4 --train_steps_per_epoch=320 \ --finetune_lr1=0.0001 --finetune_epochs1=0 --finetune_steps_per_epoch1=640 \ --finetune_lr2=0.0001 --finetune_epochs2=60 --finetune_steps_per_epoch2=640 \ --freeze=532 --dropout=0 --l2=0 \ --batch=128 python3 finetune_v2.py --data=./data/TrainVal/ --mode=train_then_finetune --net=nasnetmobile --workers=2 \ --train_lr=0.0004 --train_epochs=4 --train_steps_per_epoch=320 \ --finetune_lr1=0.0001 --finetune_epochs1=0 --finetune_steps_per_epoch1=640 \ --finetune_lr2=0.0001 --finetune_epochs2=60 --finetune_steps_per_epoch2=640 \ --freeze=532 --dropout=0.5 --l2=0 \ --batch=128
#! /bin/sh set -e # Smoke-test timestamp-abort as part of running "make check". Use the -s option # to add a stress timing in checkpoint prepare. default_test_args="-t 10 -T 5" while getopts ":sb:" opt; do case $opt in s) default_test_args="$default_test_args -s" ;; b) test_bin=$OPTARG ;; esac done if [ -z "$test_bin" ] then # If $binary_dir isn't set, default to using the build directory # this script resides under. Our CMake build will sync a copy of this # script to the build directory. Note this assumes we are executing a # copy of the script that lives under the build directory. Otherwise # passing the binary path is required. binary_dir=${binary_dir:-`dirname $0`} test_bin=$binary_dir/test_timestamp_abort fi $TEST_WRAPPER $test_bin $default_test_args $TEST_WRAPPER $test_bin $default_test_args -c #$TEST_WRAPPER $test_bin $default_test_args -L $TEST_WRAPPER $test_bin -m $default_test_args $TEST_WRAPPER $test_bin -m $default_test_args -c #$TEST_WRAPPER $test_bin -m $default_test_args -L $TEST_WRAPPER $test_bin -C $default_test_args $TEST_WRAPPER $test_bin -C $default_test_args -c $TEST_WRAPPER $test_bin -C -m $default_test_args $TEST_WRAPPER $test_bin -C -m $default_test_args -c
import os import shutil def organize_files(source_dir: str) -> None: if not os.path.exists(source_dir): raise FileNotFoundError("Source directory does not exist") organized_dir = os.path.join(source_dir, "organized_files") os.makedirs(organized_dir, exist_ok=True) for root, _, files in os.walk(source_dir): for file in files: file_path = os.path.join(root, file) if os.path.isfile(file_path): file_extension = file.split(".")[-1] extension_dir = os.path.join(organized_dir, file_extension) os.makedirs(extension_dir, exist_ok=True) shutil.move(file_path, os.path.join(extension_dir, file)) # Example usage organize_files("source_dir")
^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9])$
<?php namespace Drupal\avoindata_events\Controller; use Symfony\Component\HttpFoundation\Request; use Drupal\Core\Datetime\DrupalDateTime; /** * Adds event controller. * * Class EventsController * Implements event controller. * * @package Drupal\avoindata_events\Controller */ class EventsController { /** * Handles incoming HTTP requests. * * @param Request $request The incoming HTTP request. */ public function handleRequest(Request $request) { // Your implementation to handle the incoming HTTP request goes here } /** * Manipulates date and time information using DrupalDateTime. * * @param string $dateTimeString The date and time string to manipulate. * @return string The manipulated date and time string. */ public function manipulateDateTime($dateTimeString) { $dateTime = new DrupalDateTime($dateTimeString); // Your implementation to manipulate the date and time using DrupalDateTime goes here return $dateTime->format('Y-m-d H:i:s'); } } ?>
# ipython --pylab # two joint arm in a horizontal plane, no gravity # compute a min-jerk trajectory def minjerk(H1,H2,t,n): """ Given hand initial position H1=(x1,y1), final position H2=(x2,y2) and movement duration t, and the total number of desired sampled points n, Calculates the hand path H over time T that satisfies minimum-jerk. Also returns derivatives Hd and Hdd Flash, Tamar, and <NAME>. "The coordination of arm movements: an experimentally confirmed mathematical model." The journal of Neuroscience 5, no. 7 (1985): 1688-1703. """ T = linspace(0,t,n) H = zeros((n,2)) Hd = zeros((n,2)) Hdd = zeros((n,2)) for i in range(n): tau = T[i]/t H[i,0] = H1[0] + ((H1[0]-H2[0])*(15*(tau**4) - (6*tau**5) - (10*tau**3))) H[i,1] = H1[1] + ((H1[1]-H2[1])*(15*(tau**4) - (6*tau**5) - (10*tau**3))) Hd[i,0] = (H1[0] - H2[0])*(-30*T[i]**4/t**5 + 60*T[i]**3/t**4 - 30*T[i]**2/t**3) Hd[i,1] = (H1[1] - H2[1])*(-30*T[i]**4/t**5 + 60*T[i]**3/t**4 - 30*T[i]**2/t**3) Hdd[i,0] = (H1[0] - H2[0])*(-120*T[i]**3/t**5 + 180*T[i]**2/t**4 - 60*T[i]/t**3) Hdd[i,1] = (H1[1] - H2[1])*(-120*T[i]**3/t**5 + 180*T[i]**2/t**4 - 60*T[i]/t**3) return T,H,Hd,Hdd # forward kinematics def joints_to_hand(A,aparams): """ Given joint angles A=(a1,a2) and anthropometric params aparams, returns hand position H=(hx,hy) and elbow position E=(ex,ey) Note: A must be type matrix """ l1 = aparams['l1'] l2 = aparams['l2'] n = shape(A)[0] E = zeros((n,2)) H = zeros((n,2)) for i in range(n): E[i,0] = l1 * cos(A[i,0]) E[i,1] = l1 * sin(A[i,0]) H[i,0] = E[i,0] + (l2 * cos(A[i,0]+A[i,1])) H[i,1] = E[i,1] + (l2 * sin(A[i,0]+A[i,1])) return H,E # inverse kinematics def hand_to_joints(H,aparams): """ Given hand position H=(hx,hy) and anthropometric params aparams, returns joint angles A=(a1,a2) Note: H must be type matrix """ l1 = aparams['l1'] l2 = aparams['l2'] n = shape(H)[0] A = zeros((n,2)) for i in range(n): A[i,1] = arccos(((H[i,0]*H[i,0])+(H[i,1]*H[i,1])-(l1*l1)-(l2*l2))/(2.0*l1*l2)) A[i,0] = arctan(H[i,1]/H[i,0]) - arctan((l2*sin(A[i,1]))/(l1+(l2*cos(A[i,1])))) if A[i,0] < 0: A[i,0] = A[i,0] + pi elif A[i,0] > pi: A[i,0] = A[i,0] - pi return A # jacobian matrix J(q) = dx/da def jacobian(A,aparams): """ Given joint angles A=(a1,a2) returns the Jacobian matrix J(q) = dx/dA """ l1 = aparams['l1'] l2 = aparams['l2'] dx1dA1 = -l1*sin(A[0]) - l2*sin(A[0]+A[1]) dx1dA2 = -l2*sin(A[0]+A[1]) dx2dA1 = l1*cos(A[0]) + l2*cos(A[0]+A[1]) dx2dA2 = l2*cos(A[0]+A[1]) J = matrix([[dx1dA1,dx1dA2],[dx2dA1,dx2dA2]]) return J # jacobian matrix Jd(q) def jacobiand(A,Ad,aparams): """ Given joint angles A=(a1,a2) and velocities Ad=(a1d,a2d) returns the time derivative of the Jacobian matrix d/dt (J) """ l1 = aparams['l1'] l2 = aparams['l2'] Jd11 = -l1*cos(A[0])*Ad[0] - l2*(Ad[0] + Ad[1])*cos(A[0] + A[1]) Jd12 = -l2*(Ad[0] + Ad[1])*cos(A[0] + A[1]) Jd21 = -l1*sin(A[0])*Ad[0] - l2*(Ad[0] + Ad[1])*sin(A[0] + A[1]) Jd22 = -l2*(Ad[0] + Ad[1])*sin(A[0] + A[1]) Jd = matrix([[Jd11, Jd12],[Jd21, Jd22]]) return Jd # utility function for interpolating torque inputs def getTorque(TorquesIN, TorquesTIME, ti): """ Given a desired torque command (TorquesIN) defined over a time vector (TorquesTIME), returns an interpolated torque command at an intermediate time point ti Note: TorquesIN and TorquesTIME must be type matrix """ t1 = interp(ti, TorquesTIME, TorquesIN[:,0]) t2 = interp(ti, TorquesTIME, TorquesIN[:,1]) return matrix([[t1],[t2]]) # utility function for computing some limb dynamics terms def compute_dynamics_terms(A,Ad,aparams): """ Given a desired set of joint angles A=(a1,a2) and joint velocities Ad=(a1d,a2d), returns M and C matrices associated with inertial and centrifugal/coriolis terms """ a1,a2,a1d,a2d = A[0],A[1],Ad[0],Ad[1] l1,l2 = aparams['l1'], aparams['l2'] m1,m2 = aparams['m1'], aparams['m2'] i1,i2 = aparams['i1'], aparams['i2'] r1,r2 = aparams['r1'], aparams['r2'] M11 = i1 + i2 + (m1*r1*r1) + (m2*((l1*l1) + (r2*r2) + (2*l1*r2*cos(a2)))) M12 = i2 + (m2*((r2*r2) + (l1*r2*cos(a2)))) M21 = M12 M22 = i2 + (m2*r2*r2) M = matrix([[M11,M12],[M21,M22]]) C1 = -(m2*l1*a2d*a2d*r2*sin(a2)) - (2*m2*l1*a1d*a2d*r2*sin(a2)) C2 = m2*l1*a1d*a1d*r2*sin(a2) C = matrix([[C1],[C2]]) return M,C # inverse dynamics def inverse_dynamics(A,Ad,Add,aparams): """ inverse dynamics of a two-link planar arm Given joint angles A=(a1,a2), velocities Ad=(a1d,a2d) and accelerations Add=(a1dd,a2dd), returns joint torques Q required to generate that movement Note: A, Ad and Add must be type matrix """ n = shape(A)[0] T = zeros((n,2)) for i in range(n): M,C = compute_dynamics_terms(A[i,:],Ad[i,:],aparams) ACC = matrix([[Add[i,0]],[Add[i,1]]]) Qi = M*ACC + C T[i,0],T[i,1] = Qi[0,0],Qi[1,0] return T # forward dynamics def forward_dynamics(state, t, aparams, TorquesIN, TorquesTIME): """ forward dynamics of a two-link planar arm note: TorquesIN and TorquesTIME must be type matrix """ a1, a2, a1d, a2d = state # unpack the four state variables Q = getTorque(TorquesIN, TorquesTIME, t) M,C = compute_dynamics_terms(state[0:2],state[2:4],aparams) # Q = M*ACC + C ACC = inv(M) * (Q-C) return [a1d, a2d, ACC[0,0], ACC[1,0]] # Utility function to return hand+joint kinematics for # a min-jerk trajectory between H1 and H2 in movtime with # time padding padtime at beginning and end of movement def get_min_jerk_movement(H1,H2,movtime,padtime=0.2): # create a desired min-jerk hand trajectory t,H,Hd,Hdd = minjerk(H1,H2,movtime,100) # pad it with some hold time on each end t = append(append(0.0, t+padtime), t[-1]+padtime+padtime) H = vstack((H[0,:],H,H[-1,:])) Hd = vstack((Hd[0,:],Hd,Hd[-1,:])) Hdd = vstack((Hdd[0,:],Hdd,Hdd[-1,:])) # interpolate to get equal spacing over time ti = linspace(t[0],t[-1],100) hxi = interp(ti, t, H[:,0]) hyi = interp(ti, t, H[:,1]) H = zeros((len(ti),2)) H[:,0],H[:,1] = hxi,hyi hxdi = interp(ti, t, Hd[:,0]) hydi = interp(ti, t, Hd[:,1]) Hd = zeros((len(ti),2)) Hd[:,0],Hd[:,1] = hxdi,hydi hxddi = interp(ti, t, Hdd[:,0]) hyddi = interp(ti, t, Hdd[:,1]) Hdd = zeros((len(ti),2)) Hdd[:,0],Hdd[:,1] = hxddi,hyddi t = ti A = zeros((len(t),2)) Ad = zeros((len(t),2)) Add = zeros((len(t),2)) # use inverse kinematics to compute desired joint angles A = hand_to_joints(H,aparams) # use jacobian to transform hand vels & accels to joint vels & accels for i in range(len(t)): J = jacobian(A[i,:],aparams) Ad[i,:] = transpose(inv(J) * matrix([[Hd[i,0]],[Hd[i,1]]])) Jd = jacobiand(A[i,:],Ad[i,:],aparams) b = matrix([[Hdd[i,0]],[Hdd[i,1]]]) - Jd*matrix([[Ad[i,0]],[Ad[i,1]]]) Add[i,:] = transpose(inv(J) * b) return t,H,A,Ad,Add # utility function to plot a trajectory def plot_trajectory(t,H,A): """ Note: H and A must be of type matrix """ hx,hy = H[:,0],H[:,1] a1,a2 = A[:,0],A[:,1] figure() subplot(2,2,1) plot(t,hx,t,hy) ylim(min(min(hx),min(hy))-0.03, max(max(hx),max(hy))+0.03) xlabel('TIME (sec)') ylabel('HAND POS (m)') legend(('Hx','Hy')) subplot(2,2,2) plot(hx,hy,'.') axis('equal') plot(hx[0],hy[0],'go',markersize=8) plot(hx[-1],hy[-1],'ro',markersize=8) xlabel('HAND X POS (m)') ylabel('HAND Y POS (m)') subplot(2,2,3) plot(t,a1*180/pi,t,a2*180/pi) ylim(min(min(a1),min(a1))*180/pi - 5, max(max(a2),max(a2))*180/pi + 5) xlabel('TIME (sec)') ylabel('JOINT ANGLE (deg)') legend(('a1','a2')) subplot(2,2,4) plot(a1*180/pi,a2*180/pi,'.') plot(a1[0]*180/pi,a2[0]*180/pi,'go',markersize=8) plot(a1[-1]*180/pi,a2[-1]*180/pi,'ro',markersize=8) axis('equal') xlabel('SHOULDER ANGLE (deg)') ylabel('ELBOW ANGLE (deg)') def animatearm(state,t,aparams,step=3,crumbs=0): """ animate the twojointarm """ A = state[:,[0,1]] A[:,0] = A[:,0] H,E = joints_to_hand(A,aparams) l1,l2 = aparams['l1'], aparams['l2'] figure() plot(0,0,'b.') p1, = plot(E[0,0],E[0,1],'b.') p2, = plot(H[0,0],H[0,1],'b.') p3, = plot((0,E[0,0],H[0,0]),(0,E[0,1],H[0,1]),'b-') xlim([-l1-l2, l1+l2]) ylim([-l1-l2, l1+l2]) dt = t[1]-t[0] tt = title("Click on this plot to continue...") ginput(1) for i in xrange(0,shape(state)[0]-step,step): p1.set_xdata((E[i,0])) p1.set_ydata((E[i,1])) p2.set_xdata((H[i,0])) p2.set_ydata((H[i,1])) p3.set_xdata((0,E[i,0],H[i,0])) p3.set_ydata((0,E[i,1],H[i,1])) if crumbs==1: plot(H[i,0],H[i,1],'b.') tt.set_text("%4.2f sec" % (i*dt)) draw() ############################################################################## ############################# THE FUN PART ################################# ############################################################################## # anthropometric parameters of the arm aparams = { 'l1' : 0.3384, # metres 'l2' : 0.4554, 'r1' : 0.1692, 'r2' : 0.2277, 'm1' : 2.10, # kg 'm2' : 1.65, 'i1' : 0.025, # kg*m*m 'i2' : 0.075, } # Get a desired trajectory between two arm positions defined by # a min-jerk trajectory in Hand-space H1 = [-0.2, 0.4] # hand initial position H2 = [-0.2, 0.6] # hand final target mt = 0.500 # 500 milliseconds movement time # get min-jerk desired kinematic trajectory t,H,A,Ad,Add = get_min_jerk_movement(H1,H2,mt) plot_trajectory(t,H,A) # now compute required joint torques using inverse dynamics equations of motion TorquesIN = inverse_dynamics(A,Ad,Add,aparams) figure() plot(t,TorquesIN) legend(('torque1','torque2')) # now do a forward simulation using forward dynamics equations of motion # just to demonstrate that indeed the TorquesIN do in fact generate # the desired arm movement from scipy.integrate import odeint from scipy.interpolate import interp1d state0 = [A[0,0], A[0,1], Ad[0,0], Ad[0,1]] tt = linspace(t[0],t[-1],100) state = odeint(forward_dynamics, state0, tt, args=(aparams, TorquesIN, t,)) # run through forward kinematics equations to get hand trajectory and plot Hsim,Esim = joints_to_hand(state,aparams) plot_trajectory(tt,Hsim,state[:,[0,1]]) animatearm(state,tt,aparams)
package datapath import ( "encoding/binary" "fmt" "net" "regexp" "strconv" "syscall" "github.com/AliyunContainerService/terway/plugin/driver/ipvlan" "github.com/AliyunContainerService/terway/plugin/driver/nic" "github.com/AliyunContainerService/terway/plugin/driver/types" "github.com/AliyunContainerService/terway/plugin/driver/utils" terwayTypes "github.com/AliyunContainerService/terway/types" "github.com/containernetworking/plugins/pkg/ns" "github.com/pkg/errors" "github.com/vishvananda/netlink" "github.com/vishvananda/netlink/nl" "golang.org/x/sys/unix" ) const ( ipVlanRequirementMajor = 4 ipVlanRequirementMinor = 19 ) var ( regexKernelVersion = regexp.MustCompile(`^(\d+)\.(\d+)`) ) type IPvlanDriver struct{} func NewIPVlanDriver() *IPvlanDriver { return &IPvlanDriver{} } func generateContCfgForIPVlan(cfg *types.SetupConfig, link netlink.Link) *nic.Conf { var addrs []*netlink.Addr var routes []*netlink.Route var rules []*netlink.Rule var neighs []*netlink.Neigh var sysctl map[string][]string if cfg.MultiNetwork { table := utils.GetRouteTableID(link.Attrs().Index) ruleIf := netlink.NewRule() ruleIf.OifName = cfg.ContainerIfName ruleIf.Table = table ruleIf.Priority = toContainerPriority rules = append(rules, ruleIf) } if cfg.ContainerIPNet.IPv4 != nil { addrs = append(addrs, &netlink.Addr{IPNet: cfg.ContainerIPNet.IPv4}) // add default route if cfg.DefaultRoute { routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_UNIVERSE, Dst: defaultRoute, Gw: cfg.GatewayIP.IPv4, Flags: int(netlink.FLAG_ONLINK), }) } routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_LINK, Dst: utils.NewIPNetWithMaxMask(cfg.HostIPSet.IPv4), }) neighs = append(neighs, &netlink.Neigh{ LinkIndex: link.Attrs().Index, IP: cfg.HostIPSet.IPv4.IP, HardwareAddr: link.Attrs().HardwareAddr, State: netlink.NUD_PERMANENT, }) if cfg.MultiNetwork { table := utils.GetRouteTableID(link.Attrs().Index) v4 := utils.NewIPNetWithMaxMask(cfg.ContainerIPNet.IPv4) ruleSrc := netlink.NewRule() ruleSrc.Src = v4 ruleSrc.Table = table ruleSrc.Priority = toContainerPriority rules = append(rules, ruleSrc) routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_UNIVERSE, Dst: defaultRoute, Gw: cfg.GatewayIP.IPv4, Flags: int(netlink.FLAG_ONLINK), Table: table, }) } } if cfg.ContainerIPNet.IPv6 != nil { addrs = append(addrs, &netlink.Addr{IPNet: cfg.ContainerIPNet.IPv6}) // add default route if cfg.DefaultRoute { routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_UNIVERSE, Dst: defaultRouteIPv6, Gw: cfg.GatewayIP.IPv6, Flags: int(netlink.FLAG_ONLINK), }) } routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_LINK, Dst: utils.NewIPNetWithMaxMask(cfg.HostIPSet.IPv6), }) neighs = append(neighs, &netlink.Neigh{ LinkIndex: link.Attrs().Index, IP: cfg.HostIPSet.IPv6.IP, HardwareAddr: link.Attrs().HardwareAddr, State: netlink.NUD_PERMANENT, }) if cfg.MultiNetwork { table := utils.GetRouteTableID(link.Attrs().Index) v6 := utils.NewIPNetWithMaxMask(cfg.ContainerIPNet.IPv6) ruleSrc := netlink.NewRule() ruleSrc.Src = v6 ruleSrc.Table = table ruleSrc.Priority = toContainerPriority rules = append(rules, ruleSrc) routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_UNIVERSE, Dst: defaultRouteIPv6, Gw: cfg.GatewayIP.IPv6, Flags: int(netlink.FLAG_ONLINK), Table: table, }) } sysctl = utils.GenerateIPv6Sysctl(cfg.ContainerIfName, true, false) } contCfg := &nic.Conf{ IfName: cfg.ContainerIfName, MTU: cfg.MTU, Addrs: addrs, Routes: routes, Rules: rules, Neighs: neighs, SysCtl: sysctl, StripVlan: false, } return contCfg } func generateENICfgForIPVlan(cfg *types.SetupConfig, link netlink.Link) *nic.Conf { var routes []*netlink.Route var sysctl map[string][]string if cfg.ContainerIPNet.IPv6 != nil { sysctl = utils.GenerateIPv6Sysctl(link.Attrs().Name, true, true) } contCfg := &nic.Conf{ MTU: cfg.MTU, Routes: routes, SysCtl: sysctl, StripVlan: cfg.StripVlan, // if trunk enabled, will remote vlan tag } return contCfg } // for ipvl_x func generateSlaveLinkCfgForIPVlan(cfg *types.SetupConfig, link netlink.Link) *nic.Conf { var addrs []*netlink.Addr var routes []*netlink.Route var sysctl map[string][]string if cfg.ContainerIPNet.IPv4 != nil { addrs = append(addrs, &netlink.Addr{IPNet: utils.NewIPNetWithMaxMask(cfg.HostIPSet.IPv4), Scope: int(netlink.SCOPE_HOST)}) // add route to container routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_LINK, Dst: utils.NewIPNetWithMaxMask(cfg.ContainerIPNet.IPv4), }) } if cfg.ContainerIPNet.IPv6 != nil { addrs = append(addrs, &netlink.Addr{IPNet: utils.NewIPNetWithMaxMask(cfg.HostIPSet.IPv6), Flags: unix.IFA_F_NODAD}) // add route to container routes = append(routes, &netlink.Route{ LinkIndex: link.Attrs().Index, Scope: netlink.SCOPE_LINK, Dst: utils.NewIPNetWithMaxMask(cfg.ContainerIPNet.IPv6), }) } contCfg := &nic.Conf{ MTU: cfg.MTU, Addrs: addrs, Routes: routes, SysCtl: sysctl, } return contCfg } func (d *IPvlanDriver) Setup(cfg *types.SetupConfig, netNS ns.NetNS) error { var err error parentLink, err := netlink.LinkByIndex(cfg.ENIIndex) if err != nil { return fmt.Errorf("error get eni by index %d, %w", cfg.ENIIndex, err) } eniCfg := generateENICfgForIPVlan(cfg, parentLink) err = nic.Setup(parentLink, eniCfg) if err != nil { return err } err = ipvlan.Setup(&ipvlan.IPVlan{ Parent: parentLink.Attrs().Name, PreName: cfg.HostVETHName, IfName: cfg.ContainerIfName, MTU: cfg.MTU, }, netNS) if err != nil { return err } // 2. setup addr and default route err = netNS.Do(func(netNS ns.NetNS) error { contLink, err := netlink.LinkByName(cfg.ContainerIfName) if err != nil { return fmt.Errorf("error find link %s in container, %w", cfg.ContainerIfName, err) } contCfg := generateContCfgForIPVlan(cfg, contLink) return nic.Setup(contLink, contCfg) }) if err != nil { return fmt.Errorf("error set container link/address/route, %w", err) } if err := d.setupInitNamespace(parentLink, cfg); err != nil { return fmt.Errorf("error set init namespace, %w", err) } return nil } func (d *IPvlanDriver) Teardown(cfg *types.TeardownCfg, netNS ns.NetNS) error { err := utils.DelLinkByName(cfg.HostVETHName) if err != nil { return err } // del route to container return d.teardownInitNamespace(cfg.ContainerIPNet) } func (d *IPvlanDriver) Check(cfg *types.CheckConfig) error { parentLinkIndex := 0 // 1. check addr and default route err := cfg.NetNS.Do(func(netNS ns.NetNS) error { link, err := netlink.LinkByName(cfg.ContainerIfName) if err != nil { return err } parentLinkIndex = link.Attrs().ParentIndex changed, err := utils.EnsureLinkUp(link) if err != nil { return err } if changed { cfg.RecordPodEvent(fmt.Sprintf("link %s set to up", cfg.ContainerIfName)) } changed, err = utils.EnsureLinkMTU(link, cfg.MTU) if err != nil { return err } if changed { cfg.RecordPodEvent(fmt.Sprintf("link %s set mtu to %v", cfg.ContainerIfName, cfg.MTU)) } return utils.EnsureNetConfSet(true, false) }) if err != nil { if _, ok := err.(ns.NSPathNotExistErr); ok { return nil } return err } // 2. check parent link ( this is called in every setup it is safe) utils.Log.Debugf("parent link is %d", parentLinkIndex) parentLink, err := netlink.LinkByIndex(parentLinkIndex) if err != nil { return fmt.Errorf("error get parent link, %w", err) } changed, err := utils.EnsureLinkUp(parentLink) if err != nil { return err } if changed { cfg.RecordPodEvent(fmt.Sprintf("parent link id %d set to up", int(cfg.ENIIndex))) } changed, err = utils.EnsureLinkMTU(parentLink, cfg.MTU) if err != nil { return err } if changed { cfg.RecordPodEvent(fmt.Sprintf("link %s set mtu to %v", parentLink.Attrs().Name, cfg.MTU)) } return nil } func (d *IPvlanDriver) createSlaveIfNotExist(parentLink netlink.Link, slaveName string, mtu int) (netlink.Link, error) { slaveLink, err := netlink.LinkByName(slaveName) if err != nil { if _, ok := err.(netlink.LinkNotFoundError); !ok { return nil, fmt.Errorf("get device %s error, %w", slaveName, err) } } else { _, err = utils.EnsureLinkMTU(slaveLink, mtu) if err != nil { return nil, err } return slaveLink, nil } err = utils.LinkAdd(&netlink.IPVlan{ LinkAttrs: netlink.LinkAttrs{ Name: slaveName, ParentIndex: parentLink.Attrs().Index, MTU: mtu, }, Mode: netlink.IPVLAN_MODE_L2, }) if err != nil { return nil, err } link, err := netlink.LinkByName(slaveName) if err != nil { return nil, fmt.Errorf("error get ipvlan link %s", slaveName) } return link, nil } func (d *IPvlanDriver) setupFilters(link netlink.Link, cidrs []*net.IPNet, dstIndex int) error { parent := uint32(netlink.HANDLE_CLSACT&0xffff0000 | netlink.HANDLE_MIN_EGRESS&0x0000ffff) filters, err := netlink.FilterList(link, parent) if err != nil { return fmt.Errorf("list egress filter for %s error, %w", link.Attrs().Name, err) } ruleInFilter := make(map[*redirectRule]bool) for _, v := range cidrs { rule, err := dstIPRule(link.Attrs().Index, v, dstIndex, netlink.TCA_INGRESS_REDIR) if err != nil { return fmt.Errorf("create redirect rule error, %w", err) } ruleInFilter[rule] = false } for _, filter := range filters { matchAny := false for rule := range ruleInFilter { if rule.isMatch(filter) { ruleInFilter[rule] = true matchAny = true break } } if matchAny { continue } if err := netlink.FilterDel(filter); err != nil { return fmt.Errorf("delete filter of %s error, %w", link.Attrs().Name, err) } } for rule, in := range ruleInFilter { if !in { u32 := rule.toU32Filter() u32.Parent = parent if err := netlink.FilterAdd(u32); err != nil { return fmt.Errorf("add filter for %s error, %w", link.Attrs().Name, err) } } } return nil } func (d *IPvlanDriver) setupInitNamespace(parentLink netlink.Link, cfg *types.SetupConfig) error { // setup slave nic slaveName := d.initSlaveName(parentLink.Attrs().Index) slaveLink, err := d.createSlaveIfNotExist(parentLink, slaveName, cfg.MTU) if err != nil { return err } if slaveLink.Attrs().Flags&unix.IFF_NOARP == 0 { if err := netlink.LinkSetARPOff(slaveLink); err != nil { return fmt.Errorf("set device %s noarp error, %w", slaveLink.Attrs().Name, err) } } slaveCfg := generateSlaveLinkCfgForIPVlan(cfg, slaveLink) err = nic.Setup(slaveLink, slaveCfg) if err != nil { return err } // check tc rule err = utils.EnsureClsActQdsic(parentLink) if err != nil { return err } redirectCIDRs := append(cfg.HostStackCIDRs, cfg.ServiceCIDR.IPv4) err = d.setupFilters(parentLink, redirectCIDRs, slaveLink.Attrs().Index) if err != nil { return err } return nil } func (d *IPvlanDriver) teardownInitNamespace(containerIP *terwayTypes.IPNetSet) error { if containerIP == nil { return nil } exec := func(ipNet *net.IPNet) error { routes, err := utils.FoundRoutes(&netlink.Route{ Dst: ipNet, }) if err != nil { return err } for _, route := range routes { err = utils.RouteDel(&route) if err != nil { return err } } return nil } if containerIP.IPv4 != nil { err := exec(utils.NewIPNetWithMaxMask(containerIP.IPv4)) if err != nil { return err } } if containerIP.IPv6 != nil { err := exec(utils.NewIPNetWithMaxMask(containerIP.IPv6)) if err != nil { return err } } return nil } func (d *IPvlanDriver) initSlaveName(parentIndex int) string { return fmt.Sprintf("ipvl_%d", parentIndex) } type redirectRule struct { index int proto uint16 offset int32 value uint32 mask uint32 redir netlink.MirredAct dstIndex int } func dstIPRule(index int, ip *net.IPNet, dstIndex int, redir netlink.MirredAct) (*redirectRule, error) { v4 := ip.IP.Mask(ip.Mask).To4() if v4 == nil { return nil, fmt.Errorf("only support ipv4") } v4Mask := net.IP(ip.Mask).To4() if v4Mask == nil { return nil, fmt.Errorf("only support ipv4") } return &redirectRule{ index: index, proto: unix.ETH_P_IP, offset: 16, value: binary.BigEndian.Uint32(v4), mask: binary.BigEndian.Uint32(v4Mask), redir: redir, dstIndex: dstIndex, }, nil } func (rule *redirectRule) isMatch(filter netlink.Filter) bool { u32, ok := filter.(*netlink.U32) if !ok { return false } if u32.Attrs().LinkIndex != rule.index || u32.Attrs().Protocol != rule.proto { return false } if len(u32.Sel.Keys) != 1 { return false } key := u32.Sel.Keys[0] if key.Mask != rule.mask || key.Off != rule.offset || key.Val != rule.value { return false } return rule.isMatchActions(u32.Actions) } func (rule *redirectRule) isMatchActions(acts []netlink.Action) bool { if len(acts) != 3 { return false } tun, ok := acts[0].(*netlink.TunnelKeyAction) if !ok { return false } if tun.Attrs().Action != netlink.TC_ACT_PIPE { return false } if tun.Action != netlink.TCA_TUNNEL_KEY_UNSET { return false } skbedit, ok := acts[1].(*netlink.SkbEditAction) if !ok { return false } if skbedit.Attrs().Action != netlink.TC_ACT_PIPE { return false } if skbedit.PType == nil || *skbedit.PType != uint16(unix.PACKET_HOST) { return false } mirred, ok := acts[2].(*netlink.MirredAction) if !ok { return false } if mirred.Attrs().Action != netlink.TC_ACT_STOLEN { return false } if mirred.MirredAction != rule.redir { return false } if mirred.Ifindex != rule.dstIndex { return false } return true } func (rule *redirectRule) toActions() []netlink.Action { mirredAct := netlink.NewMirredAction(rule.dstIndex) mirredAct.MirredAction = netlink.TCA_INGRESS_REDIR tunAct := netlink.NewTunnelKeyAction() tunAct.Action = netlink.TCA_TUNNEL_KEY_UNSET skbedit := netlink.NewSkbEditAction() ptype := uint16(unix.PACKET_HOST) skbedit.PType = &ptype return []netlink.Action{tunAct, skbedit, mirredAct} } func (rule *redirectRule) toU32Filter() *netlink.U32 { return &netlink.U32{ FilterAttrs: netlink.FilterAttrs{ LinkIndex: rule.index, Priority: 40000, Protocol: rule.proto, }, Sel: &netlink.TcU32Sel{ Nkeys: 1, Flags: nl.TC_U32_TERMINAL, Keys: []netlink.TcU32Key{ { Mask: rule.mask, Val: rule.value, Off: rule.offset, }, }, }, Actions: rule.toActions(), } } func int8ToString(arr []int8) string { var bytes []byte for _, v := range arr { if v == 0 { break } bytes = append(bytes, byte(v)) } return string(bytes) } // CheckIPVLanAvailable checks if current kernel version meet the requirement (>= 4.19) func CheckIPVLanAvailable() (bool, error) { var uts syscall.Utsname err := syscall.Uname(&uts) if err != nil { return false, err } result := regexKernelVersion.FindStringSubmatch(int8ToString(uts.Release[:])) if len(result) != 3 { return false, errors.New("can't determine linux kernel version") } major, err := strconv.Atoi(result[1]) if err != nil { return false, err } minor, err := strconv.Atoi(result[2]) if err != nil { return false, err } return (major == ipVlanRequirementMajor && minor >= ipVlanRequirementMinor) || major > ipVlanRequirementMajor, nil }
<reponame>ninga6b/leaflet-maps-with-google-sheets<filename>google-doc-url.js var googleDocURL = 'https://docs.google.com/spreadsheets/d/1a-GNN5cpPK0fuOd1Z1eX-b7uDDoKT7W33uBU8QxGMIw/edit#gid=0';
#!/bin/bash # Copyright 2019 dfuse Platform Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Protobuf definitions PROTO=${PROTO:-"$ROOT/../proto"} function main() { checks current_dir="`pwd`" trap "cd \"$current_dir\"" EXIT pushd "$ROOT/pb" &> /dev/null generate "dfuse/blockmeta/v1/blockmeta.proto" generate "dfuse/bstream/v1/bstream.proto" generate "dfuse/fluxdb/v1/fluxdb.proto" generate "dfuse/graphql/v1/graphql.proto" generate "dfuse/headinfo/v1/headinfo.proto" generate "dfuse/merger/v1/merger.proto" generate "dfuse/search/v1/search.proto" generate "grpc/health/v1/health.proto" echo "generate.sh - `date` - `whoami`" > $ROOT/last_generate.txt echo "streamingfast/proto revision: `GIT_DIR=$PROTO/.git git rev-parse HEAD`" >> $ROOT/last_generate.txt } function generate() { protoc -I$PROTO $1 --go_out=plugins=grpc,paths=source_relative:. } function checks() { result_1_4_0_and_later=`printf "" | protoc-gen-go --version 2>&1 | grep -Eo 'unknown argument'` if [[ $result_1_4_0_and_later == "unknown argument" ]]; then # We are using github.com/golang/protobuf/protoc-gen-go@v1.4.0+ it's the correct version we want here return fi # The old `protoc-gen-go` did not accept any flags. Just using `protoc-gen-go --version` in this # version waits forever. So we pipe some wrong input to make it exit fast. This in the new version # which supports `--version` correctly print the version anyway and discard the standard input # so it's good with both version. result_1_3_5_and_older=`printf "" | protoc-gen-go --version 2>&1 | grep -Eo v[0-9\.]+` if [[ "$result_1_3_5_and_older" == "" ]]; then echo "Your version of 'protoc-gen-go' (at `which protoc-gen-go`) is not recent enough." echo "" echo "To fix your problem, perform those commands:" echo "" echo " pushd /tmp" echo " go install github.com/golang/protobuf/protoc-gen-go@v1.5.2" echo " popd" echo "" echo "If everything is working as expetcted, the command:" echo "" echo " protoc-gen-go --version" echo "" echo "Should print 'protoc-gen-go: unknown argument "--version" (this program should be run by protoc, not directly)'" exit 1 fi if [[ "$result_1_3_5_and_older" != "" ]]; then echo "Your version of 'protoc-gen-go' is **too** recent!" echo "" echo "This repository requires a strict gRPC version not higher than v1.29.1 however" echo "the newer protoc-gen-go versions generates code compatible with v1.32 at the minimum." echo "" echo "To keep the compatibility until the transitive dependency TiKV is updated (through streamingfast/kvdb)" echo "you must ue the older package which is hosted at 'github.com/golang/protobuf/protoc-gen-go' (you most" echo "probably have 'google.golang.org/protobuf/cmd/protoc-gen-go')." echo "" echo "To fix your problem, perform those commands:" echo "" echo " pushd /tmp" echo " go install github.com/golang/protobuf/protoc-gen-go@v1.5.2" echo " popd" echo "" echo "If everything is working as expected, the command:" echo "" echo " protoc-gen-go --version" echo "" echo "Should print 'protoc-gen-go: unknown argument "--version" (this program should be run by protoc, not directly)'" exit 1 fi } main "$@"
#!/bin/sh #. /opt/pgi/linux86-64/13.10/pgi.sh gdvroot=/home/shiva/software/gdv-h21 GAUSS_MEMDEF=67108864 GAUSS_SCRDIR=/tmp export PATH /opt/pgi/linux86-64/13.3/bin:$PATH export gdvroot GAUSS_MEMDEF GAUSS_SCRDIR . $gdvroot/gdv/bsd/gdv.profile
<reponame>stefli/sentinl import template from './dd_watcher_agg_type.html'; class DdWatcherAggType { constructor($scope) { this.$scope = $scope; this.aggTypeSelected = this.aggTypeSelected || this.$scope.aggTypeSelected; this.aggTypeOnSelect = this.aggTypeOnSelect || this.$scope.aggTypeOnSelect; this.textLimit = this.textLimit || this.$scope.textLimit; this.title = 'WHEN'; this.options = ['count', 'average', 'sum', 'min', 'max']; this.selected = this.aggTypeSelected || 'count'; } handleChange() { this.aggTypeOnSelect({type: this.selected}); } } function ddWatcherAggType() { return { template, restrict: 'E', scope: { aggTypeSelected: '=', aggTypeOnSelect: '&', textLimit: '=', }, controller: DdWatcherAggType, controllerAs: 'ddWatcherAggType', bindToController: { aggTypeSelected: '=', aggTypeOnSelect: '&', textLimit: '=', }, }; } export default ddWatcherAggType;
/* Primitive data types is pass by value */ /* Primitive data types: string, number, bigint, boolean, undefined, symbol, and null. */ /* https://developer.mozilla.org/en-US/docs/Glossary/Primitive */ /* Pass by value vs Pass by reference: https://blog.penjee.com/wp-content/uploads/2015/02/pass-by-reference-vs-pass-by-value-animation.gif */ let primitive = "string is primitive"; const passByValue = primitive; console.log("primitive:", primitive); console.log("passByValue:", passByValue); primitive = "no effect on passByValue"; console.log("primitive:", primitive); console.log("passByValue:", passByValue); /* Everything except primitive data types is `Object` in JavaScript. So it's pass by reference */ /* Every key/property on an object has reference on the memory */ const human1 = { name: "Wahyu", age: 22 }; const human2 = human1; human2.name = "Dipa"; if (human1.name !== human2.name) { console.log("Wahyu bukan dipa"); } else { console.log("Wahyu adalah dipa"); } // console.log("Is it a different name?", human1.name !== human2.name); if (human1 !== human2) { console.log("Ya tentu saja mereka berbeda"); } else { console.log("Loh kok sama?"); } // console.log("Is it a different human?", human1 !== human2); console.log("human1:", human1); console.log("human2:", human2);
<gh_stars>0 /* * Copyright (c) 2008 Princeton University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: <NAME> */ #ifndef __MEM_RUBY_NETWORK_GARNET_FIXED_PIPELINE_INPUT_UNIT_D_HH__ #define __MEM_RUBY_NETWORK_GARNET_FIXED_PIPELINE_INPUT_UNIT_D_HH__ #include <iostream> #include <vector> #include <map> #include <algorithm> #include <cassert> #include <list> #include <queue> #include "mem/ruby/common/Consumer.hh" #include "mem/ruby/network/garnet/fixed-pipeline/CreditLink_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/NetworkLink_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/VirtualChannel_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/flitBuffer_d.hh" #include "mem/ruby/network/garnet/NetworkHeader.hh" #include "config/use_speculative_va_sa.hh" #include "config/use_lrc.hh" #define DEBUG_REMAP 0 #define DEBUG_REMAP_R 5 // router to check #define DEBUG_REMAP_I 1 // input port to check class Router_d; class InputUnit_d : public Consumer { public: InputUnit_d(int id, Router_d *router); ~InputUnit_d(); std::pair<VC_state_type, Time> get_vc_state(int invc){ return m_vcs[invc]->get_vc_state(); /* I/R/V/A/C*/} void wakeup(); flitBuffer_d* getCreditQueue() { return creditQueue; } void print(std::ostream& out) const {}; inline int get_inlink_id() { return m_in_link->get_id(); } NetworkLink_d* getInLink_d() { return m_in_link; } inline void set_vc_state(VC_state_type state, int vc, Time curTime) { m_vcs[vc]->set_state(state, curTime); } inline void set_enqueue_time(int invc, Time time) { m_vcs[invc]->set_enqueue_time(time); } inline Time get_enqueue_time(int invc) { return m_vcs[invc]->get_enqueue_time(); } inline void update_credit(int in_vc, int credit) { m_vcs[in_vc]->update_credit(credit); } inline bool has_credits(int vc) { return m_vcs[vc]->has_credits(); } void increment_credit(int in_vc, bool free_signal, bool free_signal_fast, Time curTime); inline int get_outvc(int invc) { return m_vcs.at(invc)->get_outvc(); } inline void updateRoute(int vc, int outport, Time curTime) { m_vcs[vc]->set_outport(outport); #if USE_SPECULATIVE_VA_SA==1 m_vcs[vc]->set_state(VC_SP_, curTime); #else m_vcs[vc]->set_state(VC_AB_, curTime); #endif } // this is for VOQ inline void updateNextRoute(int vc, int outport) { m_vcs[vc]->set_next_outport(outport); } inline void grant_vc(int in_vc, int out_vc, Time curTime) { m_vcs[in_vc]->grant_vc(out_vc, curTime); } inline flit_d* peekTopFlit(int vc) { return m_vcs[vc]->peekTopFlit(); } inline flit_d* getTopFlit(int vc) { return m_vcs[vc]->getTopFlit(); } inline bool need_stage(int vc, VC_state_type state, flit_stage stage, Time curTime) { return m_vcs[vc]->need_stage(state, stage, curTime); } inline bool need_stage_nextcycle(int vc, VC_state_type state, flit_stage stage, Time curTime) { return m_vcs[vc]->need_stage_nextcycle(state, stage, curTime); } inline bool isReady(int invc, Time curTime) { return m_vcs[invc]->isReady(curTime); } inline int get_route(int vc) { return m_vcs[vc]->get_route(); } inline int get_next_route(int vc) { return m_vcs[vc]->get_next_route(); } inline void set_in_link(NetworkLink_d *link) { m_in_link = link; } inline void set_credit_link(CreditLink_d *credit_link) { m_credit_link = credit_link; } inline double get_buf_read_count_resettable(int vnet) { return m_num_buffer_reads_resettable[vnet]; } inline double get_buf_write_count_resettable(int vnet) { return m_num_buffer_writes_resettable[vnet]; } inline double get_buf_read_count(int vnet) { return m_num_buffer_reads[vnet]; } inline double get_buf_write_count(int vnet) { return m_num_buffer_writes[vnet]; } inline double get_resettable_buf_read_count(int vnet) { return m_num_buffer_reads_resettable[vnet]; } inline double get_resettable_buf_write_count(int vnet) { return m_num_buffer_writes_resettable[vnet]; } inline void reset_buf_count() { //for(auto& i : m_num_buffer_reads_resettable) i=0; //for(auto& i : m_num_buffer_writes_resettable) i=0; for(int i=0;i<m_num_buffer_reads_resettable.size();i++) m_num_buffer_reads_resettable.at(i)=0; for(int i=0;i<m_num_buffer_writes_resettable.size();i++) m_num_buffer_writes_resettable.at(i)=0; } int getCongestion() const; inline int getCongestion(int invc) const { return m_vcs.at(invc)->getCongestion(); } inline flit_d* peek2ndTopFlit(int invc) const { return m_vcs.at(invc)->peek2ndTopFlit(); } inline bool isFirstTailLastFlit(int invc) { return m_vcs[invc]->isFirstTailLastFlit(); } int getBufferSize(int invc) { int bufsize=-1; if (m_router->get_net_ptr()->get_vnet_type(invc) == DATA_VNET_) bufsize = m_router->get_net_ptr()->getBuffersPerDataVC(); else bufsize = m_router->get_net_ptr()->getBuffersPerCtrlVC(); assert(bufsize!=-1); return bufsize; } CreditLink_d * getCreditLink_d(){return m_credit_link;} int get_num_vcs() const { return m_num_vcs; } int get_num_vc_per_vnet() const { return m_vc_per_vnet;} //for vnet reuse inline int get_real_vnet_used(int invc){return m_vcs[invc]->get_real_vnet_used(); } inline void set_real_vnet_used(int invc,int vnet){return m_vcs[invc]->set_real_vnet_used(vnet); } // adaptive routing///////////////////////////// void setIsAdaptive(int vc,int isAdaptive) { m_vcs[vc]->set_is_adaptive(isAdaptive); } int getIsAdaptive(int vc) { return m_vcs[vc]->get_is_adaptive(); } ///////////////////////////////////////////////// int getID(){return m_id;} Router_d* get_router(){return m_router;} private: int m_id; int m_num_vcs; int m_vc_per_vnet; std::vector<double> m_num_buffer_writes; std::vector<double> m_num_buffer_reads; std::vector<double> m_num_buffer_writes_resettable; std::vector<double> m_num_buffer_reads_resettable; Router_d *m_router; NetworkLink_d *m_in_link; CreditLink_d *m_credit_link; flitBuffer_d *creditQueue; // Virtual channels std::vector<VirtualChannel_d *> m_vcs; /////////////////////////////////////////////////////////// ////// virtual channels remap logic and structures /////// /////////////////////////////////////////////////////////// /* * NOTE: the SA reset a remap indirectly when it signal free the vc using * the modified input_unit->increment_credit() function. */ public: std::vector<bool>& get_reused_remap_vc_usable(){return m_reused_remap_vc_usable;}; std::vector<bool>& get_reused_remap_vc_used(){return m_reused_remap_vc_used;}; std::vector<int>& get_reused_remap_vc_outport(){return m_reused_remap_vc_outport;}; std::vector<int>& get_reused_remap_vc_outvc(){return m_reused_remap_vc_outvc;}; std::vector<Cycles>& get_reused_remap_vc_outport_rc_cycle(){return m_reused_remap_vc_outport_rc_cycle;}; std::vector<Cycles>& get_reused_remap_vc_outvc_va_cycle(){return m_reused_remap_vc_outvc_va_cycle;}; std::vector<Time>& get_reused_remap_vc_fake_free_sig(){return m_reused_remap_vc_fake_free_sig;}; private: // structures for buf reuse std::vector<bool> m_reused_remap_vc_usable; std::vector<bool> m_reused_remap_vc_used; std::vector<int> m_reused_remap_vc_outport; std::vector<int> m_reused_remap_vc_outvc; std::vector<Cycles> m_reused_remap_vc_outport_rc_cycle; std::vector<Cycles> m_reused_remap_vc_outvc_va_cycle; std::vector<Time> m_reused_remap_vc_fake_free_sig; std::vector<bool> m_buf_is_on; //Buffer Reuse statistics public: inline void setReuseCycleVc(int vc, Time curTime) { m_vcs[vc]->setReuseCycle(curTime); } inline Time getReuseCycleVc(int vc) { return m_vcs[vc]->getReuseCycle(); } //////////////////////////////////////// std::map<int,int> m_vc_remap; std::map<int,std::list<int>> m_vc_remap_inverse; // for perf reasons when update credit int vcRemapPolicy(int vc); int vcRemapPolicyReuseVnet(int vc,flit_d*); void activeRemap(std::ostream& out) { out<<"\t@"<<curTick()<<"\tACTIVE REMAP"<<std::endl; for(int i=0;i<m_num_vcs;i++) { if(m_vc_remap[i]!=-1) out<<"\t"<<i<<"->"<<m_vc_remap[i]<<std::endl; } for(int i=0;i<m_vc_remap_inverse.size();i++) { out<<"\t\tclonedVC "<<i<<":\t"; for(auto it=m_vc_remap_inverse[i].begin();it!=m_vc_remap_inverse[i].end();it++) out<<*it<<" "; out<<std::endl; } }; std::vector<Tick> timestamp_last_used_buf; public: std::vector<Tick>& getTimestampLastUsedBuf(){return timestamp_last_used_buf;}; ///////////////////////////////////// // NON_ATOMIC_VC_ALLOC private: // used to test if a pkt is totally received in the inbuf, // then a non atomic allocation can happen. UPDATED for each received flit std::vector<bool> m_isLastFlitTail; std::vector<int> m_vnetIdLastFlitTail; std::vector<std::queue<int>* > m_outportTempQueue; // one queue per inVC to store the int m_last_max_priority_vc; // outport for the non_atomic allocated pkts public: int get_vc_priority(int vc); //added by panc for routing prioritization. int get_max_priority_vc() { return m_last_max_priority_vc; } void set_max_priority_vc(int invc) { m_last_max_priority_vc = invc; } int get_vnetIdLastFlitTail(int invc) { assert(invc>=0&&invc<m_num_vcs); return m_vnetIdLastFlitTail[invc]; } void set_vnetIdLastFlitTail(int invc,int vnet_id/*-1 is invalid, empty*/) { assert(invc>=0&&invc<m_num_vcs); //assert(vnet_id==-1 || (vnet_id>=0&&vnet_id<m_); m_vnetIdLastFlitTail[invc]=vnet_id; } std::queue<int>* getOutportTempQueue(int invc) { assert(invc>=0&&invc<m_num_vcs); return m_outportTempQueue.at(invc); } #if USE_VICHAR==1 private: ///////////////////////////////////// ///// VICHAR SUPPORT //////////////// //NOTE: vichar bufdepth is max pkt len since it does not matter, as the //number of VCs since it stops floding flits when no flit slots are //available downstream. Thus the only interesting value is the available //slots per vnet and the usedSlots per vnet passed by the router. std::vector<int> usedSlotPerVnet; public: int getUsedSlotPerVnet(int vnet) { assert(vnet>=0 && vnet<usedSlotPerVnet.size()); return usedSlotPerVnet.at(vnet); } void incrUsedSlotPerVnet(int vnet) { assert(vnet>=0 && vnet<usedSlotPerVnet.size()); usedSlotPerVnet.at(vnet)++; assert(usedSlotPerVnet.at(vnet)<=m_router->getTotVicharSlotPerVnet()); } void decrUsedSlotPerVnet(int vnet) { assert(vnet>=0 && vnet<usedSlotPerVnet.size()); usedSlotPerVnet.at(vnet)--; assert(usedSlotPerVnet.at(vnet)>=0); } ///////////////////////////////////// #endif #if USE_LRC == 1 public: void wakeup_LRC_BW(); //similar to wakeup but called in SA only #endif }; #endif // __MEM_RUBY_NETWORK_GARNET_FIXED_PIPELINE_INPUT_UNIT_D_HH__
import subprocess kraken_out = "path_to_kraken_output_file" output_file = "path_to_output_file" cmd = "cat {} | cut -f1-4".format(kraken_out) kraken_result = subprocess.check_output(cmd, shell=True) kraken_result = kraken_result.strip() kraken_result = kraken_result.split("\n") contigs_bin_dict = {} with open(output_file, "w") as fp: for item in kraken_result: tax_id = item.split("\t")[2] contig = item.split("\t")[1] contigs_bin_dict[contig] = tax_id fp.write("{}: {}\n".format(contig, tax_id))
#!/bin/bash if [[ $EUID -ne 0 ]]; then echo "This script must be run as root" exit 1 fi loc=/mnt/hugetlbfs mount | grep $loc if [ $? -eq 0 ]; then echo "$loc already mounted" exit 1 fi mkdir -p $loc mount -t hugetlbfs none $loc mkdir -p $loc/craildata/datanode/ mkdir -p $loc/craildata/cache/ chown -R $SUDO_USER $loc echo "mounted at : $loc for user $SUDO_USER"
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.math.minimization; import com.opengamma.analytics.math.function.Function1D; import com.opengamma.analytics.math.matrix.DoubleMatrix1D; import com.opengamma.analytics.math.matrix.DoubleMatrix2D; import com.opengamma.analytics.math.matrix.MatrixAlgebra; import com.opengamma.analytics.math.matrix.OGMatrixAlgebra; /** * */ public class NonLinearTransformFunction { private static final MatrixAlgebra MA = new OGMatrixAlgebra(); private final NonLinearParameterTransforms _transform; private final Function1D<DoubleMatrix1D, DoubleMatrix1D> _func; private final Function1D<DoubleMatrix1D, DoubleMatrix2D> _jac; public NonLinearTransformFunction(final Function1D<DoubleMatrix1D, DoubleMatrix1D> func, final Function1D<DoubleMatrix1D, DoubleMatrix2D> jac, final NonLinearParameterTransforms transform) { _transform = transform; _func = new Function1D<DoubleMatrix1D, DoubleMatrix1D>() { @SuppressWarnings("synthetic-access") @Override public DoubleMatrix1D evaluate(final DoubleMatrix1D yStar) { final DoubleMatrix1D y = _transform.inverseTransform(yStar); return func.evaluate(y); } }; _jac = new Function1D<DoubleMatrix1D, DoubleMatrix2D>() { @SuppressWarnings("synthetic-access") @Override public DoubleMatrix2D evaluate(final DoubleMatrix1D yStar) { final DoubleMatrix1D y = _transform.inverseTransform(yStar); final DoubleMatrix2D h = jac.evaluate(y); final DoubleMatrix2D invJ = _transform.inverseJacobian(yStar); return (DoubleMatrix2D) MA.multiply(h, invJ); } }; } public Function1D<DoubleMatrix1D, DoubleMatrix1D> getFittingFunction() { return _func; } public Function1D<DoubleMatrix1D, DoubleMatrix2D> getFittingJacobian() { return _jac; } }
/* This file is part of the JitCat library. Copyright (C) <NAME> 2019 Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ #include "jitcat/CatOwnershipSemanticsNode.h" #include "jitcat/CatLog.h" using namespace jitcat; using namespace jitcat::AST; using namespace jitcat::Reflection; using namespace jitcat::Tools; CatOwnershipSemanticsNode::CatOwnershipSemanticsNode(Reflection::TypeOwnershipSemantics ownershipSemantics, const Tokenizer::Lexeme& lexeme): CatASTNode(lexeme), ownershipSemantics(ownershipSemantics) { } CatOwnershipSemanticsNode::CatOwnershipSemanticsNode(const CatOwnershipSemanticsNode& other): CatASTNode(other), ownershipSemantics(other.ownershipSemantics) { } CatOwnershipSemanticsNode::~CatOwnershipSemanticsNode() { } CatASTNode* CatOwnershipSemanticsNode::copy() const { return new CatOwnershipSemanticsNode(*this); } void CatOwnershipSemanticsNode::print() const { switch (ownershipSemantics) { default: case TypeOwnershipSemantics::Owned: break; case TypeOwnershipSemantics::Shared: break; case TypeOwnershipSemantics::Weak: CatLog::log("&"); break; case TypeOwnershipSemantics::Value: CatLog::log("@"); break; } } CatASTNodeType CatOwnershipSemanticsNode::getNodeType() const { return CatASTNodeType::OwnershipSemantics; } Reflection::TypeOwnershipSemantics jitcat::AST::CatOwnershipSemanticsNode::getOwnershipSemantics(bool valueOwnershipIfNoneSpecified) const { if (valueOwnershipIfNoneSpecified && ownershipSemantics == TypeOwnershipSemantics::None) { return TypeOwnershipSemantics::Value; } return ownershipSemantics; }
<reponame>0lixiz/assettomc /** * Paladium Launcher - https://github.com/Chaika9/paladiumlauncher * Copyright (C) 2019 Paladium */ const $launcherHomePlayButton = $('#launcher-home-play-button'); function initLauncherHomePanel() { refreshServer(); } $("#launcher-home-options-button").click(function() { switchView(getCurrentView(), VIEWS.settings); initSettings(); }); $launcherHomePlayButton.click(function() { gameUpdate(); }); document.addEventListener('keydown', (e) => { if(getCurrentView() === VIEWS.launcher && currentLauncherPanel === LAUNCHER_PANELS.home) { if(e.key === 'Enter' && $launcherHomePlayButton.attr("disabled") != "disabled") { gameUpdate(); } } }); function refreshServer() { var paladium_server = require('./assets/js/minecraftserver'); paladium_server.init('funcraft.net', 25565, function(result) { if(paladium_server.online) { $("#server-paladium-players").html(paladium_server.current_players); $("#server-paladium-latency").html(paladium_server.latency); $("#server-total-players").html(paladium_server.current_players + " <i class=\"online\"></i>"); } else { $("#server-total-players").html("0 <i class=\"offline\"></i>"); } }); } // Game update Functions // #region let gameAssetEx; function gameUpdate() { let proc; let isValideDistro = false; const loggerGameAssetEx = LoggerUtil('%c[AssetManagerEx]', 'color: #000668; font-weight: bold'); loggerGameAssetEx.log('Initialization..'); setGameUpdateOverlayContent(); setGameTaskProgress(); setGameUpdateOverlayDownloadProgress(0); setGameUpdateOverlayDownload("Recherche de mise à jour.."); gameAssetEx = cp.fork(path.join(__dirname, 'assets', 'js', 'assetmanagerexec.js'), [ 'AssetManager', ConfigManager.getCommonDirectory(), ConfigManager.getJavaExecutable() ], { stdio: 'pipe' }); // Stdout gameAssetEx.stdio[1].setEncoding('utf8'); gameAssetEx.stdio[1].on('data', (data) => { loggerGameAssetEx.log(data); }); // Stderr gameAssetEx.stdio[2].setEncoding('utf8'); gameAssetEx.stdio[2].on('data', (data) => { loggerGameAssetEx.log(data); }); gameAssetEx.on('error', (err) => { loggerLaunchSuite.error('Error during launch', err); }) gameAssetEx.on('close', (code, signal) => { if(code !== 0) { loggerLaunchSuite.error(`AssetExec exited with code ${code}, assuming error.`); } }) gameAssetEx.on('message', (m) => { if(m.context === 'validate') { switch(m.data) { case 'distribution': { loggerGameAssetEx.log('Validated distibution index.'); isValideDistro = true; break; } case 'version': { loggerGameAssetEx.log('Version data loaded.'); setGameUpdateOverlayDownload("Vérification de la version.."); break; } case 'assets': { loggerGameAssetEx.log('Asset Validation Complete.'); setGameUpdateOverlayDownload("Vérification des assets.."); break; } case 'libraries': { loggerGameAssetEx.log('Library validation complete.'); setGameUpdateOverlayDownload("Vérification des libraries.."); break; } case 'files': { loggerGameAssetEx.log('File validation complete.'); setGameUpdateOverlayDownload("Vérification des fichiers.."); break; } } } else if(m.context === 'progress') { setGameUpdateOverlayDownload("Téléchargement des fichiers en cours.."); switch(m.data) { case 'assets': { const perc = (m.value / m.total) * 100; setGameUpdateOverlayDownloadProgress(Math.round(perc)); break; } case 'download': { setDownloadPercentage(m.value, m.total, m.percent); break; } } } else if(m.context === 'complete') { switch(m.data) { case 'download': { setGameUpdateOverlayDownload("Chargement en cours.."); break; } } } else if(m.context === 'error') { toggleGameUpdateOverlay(false); setOverlayContent('Mise à jour échouée 😭', 'Une erreur s\'est produite lors de la mise à jour du jeu.' + '<br>Nous vous conseillons de réessayer la mise à jour avec le bouton ci-dessous.', 'Annuler', 'Réessayer'); toggleOverlay(true); setCloseHandler(); setActionHandler(() => { toggleOverlay(false); gameUpdate(); }); } else if(m.context === 'validateEverything') { if(!isValideDistro) { gameAssetEx.disconnect(); $(VIEWS.launcher).fadeIn(1000); toggleGameUpdateOverlay(false); if(ConfigManager.getDistroCustom() == 'true') { setOverlayContent('Mise à jour échouée 😭', 'Une erreur s\'est produite lors de la récupération des distributions.' + '<br><i class="fas fa-angle-right"></i> Nous vous conseillons de vérifier l\'url de distribution dans les options du launcher.', 'Annuler'); toggleOverlay(true); setCloseHandler(); } else { setOverlayContent('Mise à jour échouée 😭', 'Une erreur s\'est produite lors de la mise à jour du jeu.' + '<br><i class="fas fa-angle-right"></i> Nous vous conseillons de réessayer la mise à jour avec le bouton ci-dessous.', 'Annuler', 'Réessayer'); toggleOverlay(true); setCloseHandler(); setActionHandler(() => { toggleOverlay(false); gameUpdate(); }); } return; } setGameUpdateOverlayDownload("Lancement du jeu en cours.."); setGameUpdateOverlayTitle("Lancement du jeu"); setGameUpdateOverlayDownloadProgress(0, 'yellow'); const tempListener = function(data) { if(data.trim().match(/Loading tweak class name cpw.mods.fml.common.launcher.FMLTweaker/i)) { setGameUpdateOverlayDownload("Chargement de Forge en cours.."); setGameUpdateOverlayDownloadProgress(10, 'yellow'); } else if(data.trim().match(/Using primary tweak class name cpw.mods.fml.common.launcher.FMLTweaker/i)) { setGameUpdateOverlayDownloadProgress(20, 'yellow'); } else if(data.trim().match(/Calling tweak class cpw.mods.fml.common.launcher.FMLTweaker/i)) { setGameUpdateOverlayDownloadProgress(30, 'yellow'); } else if(data.trim().match(/Forge Mod Loader version/i)) { setGameUpdateOverlayDownloadProgress(40, 'yellow'); } else if(data.trim().match(/Launching wrapped minecraft/i)) { setGameUpdateOverlayDownload("Chargement de Minecraft en cours.."); setGameUpdateOverlayDownloadProgress(50, 'yellow'); } else if(data.trim().match(/Attempting early MinecraftForge initialization/i)) { setGameUpdateOverlayDownload("Chargement des Mods.."); setGameUpdateOverlayDownloadProgress(60, 'green'); } else if(data.trim().match(/Entering preinitialization phase../i)) { setGameUpdateOverlayDownload("Chargement des Mods (1/3).."); setGameUpdateOverlayDownloadProgress(70, 'green'); } else if(data.trim().match(/Entering initialization phase../i)) { setGameUpdateOverlayDownload("Chargement des Mods (2/3).."); setGameUpdateOverlayDownloadProgress(80, 'green'); } else if(data.trim().match(/Entering postinitialization phase../i)) { setGameUpdateOverlayDownload("Chargement des Mods (3/3).."); setGameUpdateOverlayDownloadProgress(90, 'green'); } else if(data.trim().match(/Created: 1024x512 textures/i)) { setGameUpdateOverlayDownload("Chargement en cours.."); setGameUpdateOverlayDownloadProgress(100, 'green'); proc.stdout.on('data', gameStateChange); proc.stdout.removeListener('data', tempListener); proc.stderr.removeListener('data', gameErrorListener); const window = remote.getCurrentWindow(); window.hide(); /*if(ConfigManager.getLauncherConfigKeepOpen() == 'false'){ const window = remote.getCurrentWindow(); window.hide(); console.log('Fenêtre du launcher fermée pendant l\'execution du jeu.'); } else{ gameCloseListener(0, 0); $("#launcher-home-play-button").attr("disabled", true); }*/ } } const gameStateChange = function(data) { // TODO : Ajouter d'autre event d'erreur. data = data.trim(); /*if(data.trim().match(/Error in class 'LibraryLWJGLOpenAL'/i)) { proc.kill(); setOverlayContent('Erreur de lancement', 'Nous avons détecté une erreur lors du lancement de votre jeu.' + '<br>Nous vous conseillons de relancer votre jeu avec le bouton ci-dessous.', 'Annuler', 'Relancer'); toggleOverlay(true); setCloseHandler(); setActionHandler(() => { toggleOverlay(false); gameUpdate(); }); }*/ } const gameErrorListener = function(data) { // TODO : Ajouter d'autre event d'erreur. data = data.trim(); if(data.indexOf('Could not find or load main class net.minecraft.launchwrapper.Launch') > -1) { console.error('Game launch failed, LaunchWrapper was not downloaded properly.'); } } const gameCloseListener = function(code, signal) { const window = remote.getCurrentWindow(); window.show(); window.focus(); setGameTaskProgress(false); if(code != 0) { setOverlayContent('Crash du jeu 😭', 'Une erreur s\'est produite pendant l\'exécution du jeu.', 'Fermer'); toggleOverlay(true); setCloseHandler(); } } forgeData = m.result.forgeData; versionData = m.result.versionData; const instance = DistroManager.getDistribution().getInstance(ConfigManager.getSelectedInstance()); const authUser = ConfigManager.getSelectedAccount(); console.log(`Sending selected account (${authUser.displayName}) to ProcessBuilder.`) let pb = new ProcessBuilder(instance, versionData, forgeData, authUser); try { proc = pb.build(); // Build Minecraft process. proc.stdout.on('data', tempListener); proc.stderr.on('data', gameErrorListener); proc.on('close', gameCloseListener); } catch(err) { console.error('Error during launch', err); setGameTaskProgress(false); } gameAssetEx.disconnect(); } }); gameAssetEx.send({task: 'execute', function: 'validateEverything', argsArr: [ConfigManager.getSelectedInstance()]}); } function setGameTaskProgress(value = true) { if(value) { toggleGameUpdateOverlay(true); $(VIEWS.launcher).fadeOut(1000); $("#launcher-home-play-button").attr("disabled", true); } else { $(VIEWS.launcher).fadeIn(1000); toggleGameUpdateOverlay(false); $("#launcher-home-play-button").attr("disabled", false); } } function setDownloadPercentage(value, max, percent = ((value / max) * 100)) { setGameUpdateOverlayDownloadProgress(percent); } // #endregion
module.exports = { plugin: true, data: function () { return { helper: this.$parent.$options.utils['lightbox-helper'].methods }; }, created: function () { var vm = this, editor = this.$parent.editor; if (!editor || !editor.htmleditor) { return; } this.lightboxes = []; editor.addButton ('lightbox', { title: 'Lightbox', label: '<i class="uk-icon-th-large"></i>' }); editor.options.toolbar.push ('lightbox'); editor .on ('action.lightbox', function (e, editor) { vm.openModal (_.find (vm.lightboxes, function (lightbox) { return lightbox.inRange (editor.getCursor ()); })); }) .on ('render', function () { vm.lightboxes = editor.replaceInPreview (/\(lightbox\)(\{.+\})/gi, vm.replaceInPreview); }) .on ('renderLate', function () { while (vm.$children.length) { vm.$children[0].$destroy (); } Vue.nextTick (function () { editor.preview.find ('lightbox-preview').each (function () { vm.$compile (this); }); }); }); editor.debouncedRedraw (); }, methods: { openModal: function (lightbox) { var vm = this, editor = this.$parent.editor, cursor = editor.editor.getCursor (); if (!lightbox) { lightbox = { replace: function (value) { editor.editor.replaceRange (value, cursor); } }; } new this.$parent.$options.utils['input-image-lightbox'] ({ parent: this, data: { lightbox: lightbox } }) .$mount () .$appendTo ('body') .$on ('select', function (lightbox) { var content, lightboxInfo; lightboxInfo = vm.helper.lightboxInfoFromPickerSelection (lightbox); content = '(lightbox)' + JSON.stringify (lightboxInfo); lightbox.replace (content); }); }, replaceInPreview: function replaceInPreview(data, index) { var lightbox, parsed = {}; try { parsed = JSON.parse(data.matches[1]); } catch (e) { } lightbox = this.helper.flatToNestedItemInfo(parsed); if (lightbox.data.data) { data.data = lightbox.data.data; } if (lightbox.data.images) { data.images = lightbox.data.images; } return '<lightbox-preview index="' + index + '"></lightbox-preview>'; } }, components: { 'lightbox-preview': require ('./lightbox-preview.vue') } }; window.Editor.components['editor-lightbox'] = module.exports; window.Editor.utils['input-image-lightbox'] = Vue.extend (require ('./input-image-lightbox.vue')); window.Editor.utils['lightbox-helper'] = require ('./lightbox-helper.js');
def sum_products_engineer_tech(engineers, technicians): total_costs = sum([x.cost for x in engineers] + [x.cost for x in technicians]) return total_costs
#!/bin/bash #SBATCH --time=90:55:00 #SBATCH --account=vhs #SBATCH --job-name=lustre_5n_32t_6d_1000f_617m_5i #SBATCH --nodes=5 #SBATCH --nodelist=comp02,comp03,comp04,comp06,comp07 #SBATCH --output=./results/exp_threads/run-2/lustre_5n_32t_6d_1000f_617m_5i/slurm-%x-%j.out source /home/vhs/Sea/.venv/bin/activate srun -N5 ../scripts/clear_client_pc.sh start=`date +%s.%N` srun -N 1 bash ./results/exp_threads/run-2/lustre_5n_32t_6d_1000f_617m_5i/n0_sea_parallel.sh & srun -N 1 bash ./results/exp_threads/run-2/lustre_5n_32t_6d_1000f_617m_5i/n1_sea_parallel.sh & srun -N 1 bash ./results/exp_threads/run-2/lustre_5n_32t_6d_1000f_617m_5i/n2_sea_parallel.sh & srun -N 1 bash ./results/exp_threads/run-2/lustre_5n_32t_6d_1000f_617m_5i/n3_sea_parallel.sh & srun -N 1 bash ./results/exp_threads/run-2/lustre_5n_32t_6d_1000f_617m_5i/n4_sea_parallel.sh & wait end=`date +%s.%N` runtime=$( echo "$end - $start" | bc -l ) echo "Runtime: $runtime"
import tensorflow as tf def make_weights(shape, name='weights'): return tf.Variable(tf.truncated_normal(shape=shape, stddev=0.05), name=name) def make_biases(shape, name='biases'): return tf.Variable(tf.constant(0.05, shape=shape), name=name) def convolution_layer(prev_layer, f_size, inp_c, out_c, stride_s): _weights = make_weights([f_size, f_size, inp_c, out_c]) _bias = make_biases([out_c]) conv_result = tf.nn.conv2d(prev_layer, _weights, [1, stride_s, stride_s, 1], padding='SAME') return tf.add(conv_result, _bias)
import React from "react"; import Modal from "../Modal"; import { connect } from "react-redux"; import { deleteStream, getStream } from "../../actions"; class StreamDelete extends React.Component { renderContent = () => { if (this.props.stream === undefined) { return "Loading ..."; } return `Are you sure you want to delete stream with title: "${this.props.stream.title}" ?`; }; componentDidMount() { this.props.getStream(this.props.match.params.id); } onActionClicked = () => { this.props.deleteStream(this.props.match.params.id); }; render = () => { return ( <div> <Modal header="Delete Stream" content={this.renderContent()} cancelUrl="/" actionText="Delete" onActionClicked={this.onActionClicked} /> </div> ); }; } const mapStateToProps = (state, ownProps) => { return { stream: state.streams[ownProps.match.params.id] }; }; export default connect(mapStateToProps, { deleteStream, getStream })( StreamDelete );
<filename>js_modules/profile.js /* ///////////////////////// LEGAL NOTICE /////////////////////////////// This file is part of ZScripts, a modular script framework for Pokemon Online server scripting. Copyright (C) 2013 <NAME>, aka "ArchZombie" / "ArchZombie0x", <<EMAIL>> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. /////////////////////// END LEGAL NOTICE /////////////////////////////// */ /* profile.js Implements: profileMatches(src): Returns a list of all the profile IDs the player matches profileID(src): Returns a single ID for the player. If there are multiple matches, it merges them together. If there are none, it creates a new profile profileByName(name): Returns if any profile matches this name, the profile ID, otherwise -1 profileByIp(ipaddr): Returns a matching profile ID, otherwise -1 trace(profid): When profiles are merged one profile will take priority, but the others will still exist profileUpdateInfo(prof, src): Updates profile information */ ({ require: ["io", "logs"] , database: null /* <Object profiles: <Object Key:[<Int indexForProfile>] Value:[<Object profile>] > , profile_counter: <INT> > */ , relationaldatabase: new Object /* <Object names: <Object Key:[<String "$"> + <String name>] Value:[<Int indexForProfile>] > , ips: <Object Key:[<String ipaddr>] Value:[<Int indexForProfile>] > */ , users: new Object , loadModule: function () { this.database = this.io.openDB("profile"); if (!this.database.profiles) this.database.profiles = new Object; if (!this.database.profile_counter) this.database.profile_counter = 0; var uids = sys.playerIds(); this.updateAllRelations(); for (var x in uids) { this.registerPlayer(uids[x]); } } , unloadModule: function () { this.io.closeDB("profile"); } , updateAllRelations: function() { this.relationaldatabase = { names: new Object, ips: new Object }; for (var x in this.database.profiles) { this.updateProfileRelations(x); } } , profileID: function (src) { var _; if (_ = this.users[src]) return _; else { return this.users[src] = this.registerPlayer(src); } } , lastName: function (prof) { return this.database.profiles[prof].lastName; } , profileNames: function (prof) { return this.database.profiles[prof].names; } , profileIPs: function (prof) { return this.database.profiles[prof].ips; } , updateProfileRelations: function (id) { var prof = this.database.profiles[id]; if (prof.mergedInto) return; var prof_names = prof.names; var prof_ips = prof.ips; for (var x in prof_names) { if (!("$"+ prof_names[x] in this.relationaldatabase.names)) this.relationaldatabase.names["$"+ prof_names[x]] = id; else if (this.relationaldatabase.names["$"+prof_names[x]] != id) this.logs.logMessage(this.logs.ERROR, "Error condition, multimatch on profile #" + id); } for (var x in prof_ips) { if (!(prof_ips[x] in this.relationaldatabase.ips)) this.relationaldatabase.ips[prof_ips[x]] = id; else if (this.relationaldatabase.ips[prof_ips[x]] != id) this.logs.logMessage(this.logs.ERROR, "Error condition, multimatch on profile #" + id); } } , profileMatches: function (src) { var sys_name$src = sys.name(src); var name = sys_name$src.toLowerCase(); var ip = sys.ip(src); var matches = new Object; if (ip in this.relationaldatabase.ips) { matches[this.relationaldatabase.ips[ip]] = null; } if ("$"+name in this.relationaldatabase.names) { matches[this.relationaldatabase.names["$"+name]] = null; } return Object.keys(matches); } , profileUpdateInfo: function (profid, src) { var prof = this.database.profiles[profid]; var sys_name$src = sys.name(src); var sys_ip$src = sys.ip(src); if (prof.names.indexOf(sys_name$src.toLowerCase()) == -1) prof.names.push(sys_name$src.toLowerCase()); if (prof.ips.indexOf(sys_ip$src) == -1) prof.ips.push(sys_ip$src); prof.lastName = sys_name$src; prof.lastIP = sys_ip$src; prof.lastOnline = +new Date; this.updateProfileRelations(profid); return; } , registerPlayer: function(src) { var matchesList = this.profileMatches(src); if (matchesList.length == 0) { var p = this.newProfile(src); this.profileUpdateInfo(p, src); return p; } else if (matchesList.length > 1) { this.logs.logMessage(this.logs.INFO, "Merging profiles " + JSON.stringify(matchesList)); this.mergeProfiles(matchesList); } var i = parseInt(matchesList[0]); var prof = this.database.profiles[i]; this.profileUpdateInfo(i, src); return i; } , profileByIP: function (ip) { if (ip in this.relationaldatabase.ips) return this.relationaldatabase.ips[ip]; else return -1; } , profileByName: function (n) { var name = "$"+ n.toLowerCase(); if (name in this.relationaldatabase.names) return this.relationaldatabase.names[name]; else return -1; } , newProfile: function (src) { var prof = new Object; var prof_id = this.database.profile_counter++; prof.names = []; prof.ips = []; this.database.profiles[prof_id] = prof; return prof_id; } , trace: function (prof) { var p = this.database.profiles[prof]; var idx = prof; while (p.mergedInto) { idx = p.mergedInto; p = this.database.profiles[p.mergedInto]; } return idx; } , mergeProfiles: function (list) { var origin = this.database.profiles[list[0]]; this.logs.logMessage(this.logs.WARN, "Merging profiles " + JSON.stringify(list)); for (var x1 in list) { if (x1 == 0) continue; this.database.profiles[list[x1]].mergedInto = list[0]; for (var x2 in this.database.profiles[list[x1]].names) { if (origin.names.indexOf(this.database.profiles[list[x1]].names[x2]) == -1) { origin.names.push(this.database.profiles[list[x1]].names[x2]); } } for (var x2 in this.database.profiles[list[x1]].ips) { if (origin.ips.indexOf(this.database.profiles[list[x1]].ips[x2]) == -1) { origin.ips.push(this.database.profiles[list[x1]].ips[x2]); } } } } });
function makeToc(contentElement, tocSelector, options) { if (options == null) { options = {}; } if (contentElement == null) { throw new Error('need to provide a selector where to scan for headers'); } if (tocSelector == null) { throw new Error('need to provide a selector where inject the TOC'); } if (typeof contentElement === 'string') { contentElement = document.querySelectorAll(contentElement + ' > *'); } else { contentElement = contentElement.children; } var allChildren = Array.prototype.slice.call(contentElement); var min = 6; var headers = allChildren.filter(function(item) { var classesList = item.className.split(' '); if (classesList.indexOf("toc-ignore") != -1) { return false; } if ((options.ignore || []).indexOf(getText(item)) != -1) { return false; } var splitted = item.nodeName.split(''); var headingNumber = parseInt(splitted[1]); if (splitted[0] === 'H' && headingNumber >= 1 && headingNumber <= (options.max || 6)) { min = Math.min(min, headingNumber); return true; } }); var hierarchy = createHierarchy(headers, min); var toc = parseNodes(hierarchy.nodes); var container = document.querySelector(tocSelector); setText(container, ''); container.appendChild(toc); } function createHierarchy(headers, minLevel) { var hierarchy = { nodes: [] }; window.hierarchy = hierarchy; var previousNode = { parent: hierarchy }; var level = minLevel; var init = false; headers.forEach(function(header) { var headingNumber = parseInt(header.nodeName.substr(1)); var object = { title: getText(header), link: window.location.pathname + '#' + header.id, originLevel: headingNumber, nodes: [] }; if (headingNumber === level) { object.parent = previousNode.parent; // keep level } else if (headingNumber - level >= 1) { // go one step deeper, regardless how much // the difference between headingNumber and level is if (init === false) { var missingParent = { parent: previousNode.parent, title: '', link: '', originLevel: NaN, nodes: [] }; previousNode.parent.nodes.push(missingParent); previousNode = missingParent; } object.parent = previousNode; level++; } else if (level - headingNumber >= 1) { // go one or more step up again var ref = previousNode.parent; while (level - headingNumber >= 1) { ref = ref.parent; level--; } object.parent = ref; } else { console.error('unkown toc path'); } object.parent.nodes.push(object); previousNode = object; init = true; }); return hierarchy; } function parseNodes(nodes) { var ul = document.createElement("UL"); for(var i=0; i<nodes.length; i++) { ul.appendChild(parseNode(nodes[i])); } return ul; } function parseNode(node) { var li = document.createElement("LI"); var a = document.createElement("A"); setText(a, node.title); a.href = node.link; li.appendChild(a); if(node.nodes) { li.appendChild(parseNodes(node.nodes)); } return li; } function getText(elem) { if (elem.textContent != null) { return elem.textContent; } else { elem.innerText; } } function setText(elem, value) { if (elem.textContent != null) { elem.textContent = value; } else { elem.innerText = value; } } module.exports = makeToc; module.exports.update = function() { var element = document.querySelector("[data-toc]"); if (element != null) { var options = {}; var ignore = (element.attributes.getNamedItem("data-toc-ignore")||{}).value var max = (element.attributes.getNamedItem("data-toc-max")||{}).value if (ignore != null) { options.ignore = ignore; } if (max != null) { options.max = parseInt(max); } makeToc(element.parentNode, '[data-toc]', options); } }; window.addEventListener('load', module.exports.update);
curl "http://localhost:8080/user/Delete" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $MICRO_API_TOKEN" \ -d '{ "id": "fdf34f34f34-f34f34-f43f43f34-f4f34f" }'
package io.opensphere.imagery.algorithm.genetic; import io.opensphere.core.util.lang.ExpectedCloneableException; /** * A candidate for the genetic algorithms fitness function. */ public class Candidate implements Cloneable { /** * Fitness as judged by fitness function. */ private double myFitness; /** The Fitness measurement. */ // left room for an object to be used for fitness measurement private Object myFitnessMeasurement; /** * The codon sequence for this Candidate. */ private SequenceString mySequence; @Override public Candidate clone() { try { final Candidate cand = (Candidate)super.clone(); cand.mySequence = mySequence.clone(); cand.myFitness = myFitness; cand.myFitnessMeasurement = myFitnessMeasurement; return cand; } catch (CloneNotSupportedException e) { throw new ExpectedCloneableException(e); } } /** * Get the fitness of this Candidate. Your fitness function decides whether * high or low, positive or negative fitness is good or bad. * * @return the <code>double</code> fitness of this Candidate */ public double getFitness() { Double.parseDouble("1"); return myFitness; } /** * Return an object that is the measure of this Candidates fitness. * * @return the <code>Object</code> that is the fitness */ public Object getFitnessMeasurement() { return myFitnessMeasurement; } /** * Return this Candidates {@link SequenceString SequenceString}. * * @return the {@link SequenceString SequenceString} for this Candidate * @see SequenceString */ public SequenceString getSequence() { return mySequence; } /** * Set the fitness of this candidate. * * @param aFitness the <code>double</code> that is the new fitness of this * Candidate. */ public void setFitness(double aFitness) { myFitness = aFitness; } /** * Set the object which is the measure of this Candidates fitness. * * @param aFitnessMeasurement the fitness measurement. */ public void setFitnessMeasurement(Object aFitnessMeasurement) { myFitnessMeasurement = aFitnessMeasurement; } /** * Set this Candidates {@link SequenceString SequenceString}. * * @param newSequence {@link SequenceString SequenceString} the Sequence to * set to */ public void setSequence(SequenceString newSequence) { mySequence = newSequence; } @Override public String toString() { return "Candidate [mySequence=" + mySequence + ", myFitness=" + myFitness + ", myFitnessMeasurement=" + myFitnessMeasurement + "]"; } }
#!/bin/bash set -e set -o pipefail if [ $(uname -s) = Darwin ]; then basedir=$(dirname $(cd "$(dirname "$0")"; pwd -P)) else basedir=$(dirname $(dirname $(readlink -fm $0))) fi export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8 : "${TARGETS:="linux mac win"}" declare -A variables=() # Get latest JDK version from https://adoptopenjdk.net/releases.html?variant=openjdk15&jvmVariant=hotspot JDK_VERSION=14.0.2+12 JDK_MAJOR_VERSION=`echo $JDK_VERSION | cut -f1 -d"." | cut -f1 -d+` JDK_VERSION_URL_ENC=`echo "$JDK_VERSION" | sed 's/+/%2B/g'` JDK_VERSION_URL_ENC2=`echo "$JDK_VERSION" | sed 's/+/_/g'` variables["JDK_DOWNLOAD_FILENAME_linux"]="OpenJDK${JDK_MAJOR_VERSION}U-jdk_x64_linux_hotspot_${JDK_VERSION_URL_ENC2}.tar.gz" variables["JDK_DOWNLOAD_FILENAME_mac"]="OpenJDK${JDK_MAJOR_VERSION}U-jdk_x64_mac_hotspot_${JDK_VERSION_URL_ENC2}.tar.gz" variables["JDK_DOWNLOAD_FILENAME_win"]="OpenJDK${JDK_MAJOR_VERSION}U-jdk_x64_windows_hotspot_${JDK_VERSION_URL_ENC2}.zip" variables["JAVA_HOME_linux"]="jdk-$JDK_VERSION" variables["JAVA_HOME_mac"]="jdk-$JDK_VERSION/Contents/Home" variables["JAVA_HOME_win"]="jdk-$JDK_VERSION" JAVAFX_VERSION="15.0.1" variables["JAVAFX_SDK_FILENAME_linux"]="openjfx-${JAVAFX_VERSION}_linux-x64_bin-sdk.zip" variables["JAVAFX_SDK_FILENAME_mac"]="openjfx-${JAVAFX_VERSION}_osx-x64_bin-sdk.zip" variables["JAVAFX_SDK_FILENAME_win"]="openjfx-${JAVAFX_VERSION}_windows-x64_bin-sdk.zip" variables["JAVAFX_JMODS_FILENAME_linux"]="openjfx-${JAVAFX_VERSION}_linux-x64_bin-jmods.zip" variables["JAVAFX_JMODS_FILENAME_mac"]="openjfx-${JAVAFX_VERSION}_osx-x64_bin-jmods.zip" variables["JAVAFX_JMODS_FILENAME_win"]="openjfx-${JAVAFX_VERSION}_windows-x64_bin-jmods.zip" variables["DECOMPRESS_linux"]="tar -C jdks/linux -zxf" variables["DECOMPRESS_mac"]="tar -C jdks/mac -zxf" variables["DECOMPRESS_win"]="unzip -q -d jdks/win" OS=`uname -s` if [ $OS = "Darwin" ]; then export JAVA_HOME=$basedir/import/jdks/mac/${variables["JAVA_HOME_mac"]} else export JAVA_HOME=$basedir/import/jdks/linux/${variables["JAVA_HOME_linux"]} fi # get the SHA-256 hash of the specified file getHash () { if [ $(uname -s) = Darwin ]; then h=`shasum -a 256 $1 | awk '{print $1}'` else h=`sha256sum $1 | awk '{print $1}'` fi echo $h } # normalizes the specified jar or zip for reproducible build. Enforces consistent zip file order and sets all timestamps to midnight on Jan 1 2019 normalizeZip () { $JAVA_HOME/bin/java --module-path "$basedir/import/commons-compress-1.20/commons-compress-1.20.jar":"$basedir/target/org.getmonero.util.normalizeZip.jar" \ -m org.getmonero.util.normalizeZip 1546300800000 "$1" }
def compute_average(a, b): return (a + b) / 2 print(compute_average(2, 3)) # 2.5
# ============================================================ # Author: 凍仁翔 / chusiang.lai (at) gmail.com # Blog: http://note.drx.tw # Filename: wheel-scrolling.sh # Modified: 2014-12-31 21:39 # Description: # Reference: # 1. 凍仁的筆記: Logitech Marble Trackball on Ubuntu 10.04+ # - http://note.drx.tw/2010/06/logitech-marble-trackball-on-ubuntu.html # =========================================================== #!/bin/bash DEV_WHEEL=$(lsusb | grep "Logitech, Inc. TrackMan Wheel" | wc -l) if [ $DEV_WHEEL -eq "1" ] then xinput set-prop 'Logitech Trackball' "Evdev Wheel Emulation" 1 xinput set-prop 'Logitech Trackball' "Evdev Wheel Emulation Button" 3 xinput set-prop 'Logitech Trackball' "Evdev Wheel Emulation Timeout" 200 xinput set-prop 'Logitech Trackball' "Evdev Wheel Emulation Axes" 6 7 4 5 xinput set-prop 'Logitech Trackball' "Evdev Middle Button Emulation" 1 xinput set-prop 'Logitech Trackball' "Evdev Middle Button Timeout" 50 STATUS="'Wheel TrackBall' 'Scrolling bas been enabled'" else STATUS="'Wheel TrackBall' 'No search device'" fi echo "notify-send -t 2000 -i mouse $STATUS" | bash
package server import "gopkg.in/mgo.v2" type DBImpl struct { Session *mgo.Session DB *mgo.Database } func (s *DBImpl) InitDB() { s.Session, _ = mgo.Dial(Settings.DB["url"][0]) if s.Session != nil { s.DB = s.Session.DB(Settings.DB["name"][0]) } }
package com.sbsuen.fitfam.exercise; import org.springframework.data.mongodb.repository.MongoRepository; public interface ExerciseRepository extends MongoRepository<Exercise,String> { }
import React from 'react'; import {shallow} from 'enzyme'; import Footer from './Footer'; describe ('Footer Component', () => { // Component Tests let wrapper; beforeEach(() => { wrapper = shallow(<Footer />); }); it('renders the footer', () => { const footer = wrapper.find('footer'); expect(footer).toExist; }); it('renders the year', () => { const thisYear = new Date().getFullYear().toString(); // const date = wrapper.find(thisYear) expect(wrapper.find(thisYear)).toExist; }); });
#!/bin/sh kubectl create -f namespaces.yml kubectl create -f clusterRole.yml kubectl create -f kube-state-metrics.yml kubectl create -f grafana-deployment.yml kubectl create -f grafana-service.yml kubectl create -f alertmanager-configmap.yml kubectl create -f alertmanager-deployment.yml kubectl create -f alertmanager-service.yml kubectl create -f prometheus-config-map.yml kubectl create -f prometheus-rules-config-map.yml kubectl create -f prometheus-deployment.yml kubectl create -f prometheus-service.yml
<filename>idem_azurerm/states/azurerm/containerregistry/task.py # -*- coding: utf-8 -*- """ Azure Resource Manager (ARM) Container Registry Task State Module .. versionadded:: 3.0.0 .. versionchanged:: 4.0.0 :maintainer: <<EMAIL>> :configuration: This module requires Azure Resource Manager credentials to be passed via acct. Note that the authentication parameters are case sensitive. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example configuration for Azure Resource Manager authentication: .. code-block:: yaml azurerm: default: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: <PASSWORD> The authentication parameters can also be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter of each state, but this is not preferred and could be deprecated in the future. """ # Import Python libs from dict_tools import differ import logging log = logging.getLogger(__name__) async def present( hub, ctx, name, registry_name, resource_group, task_type, platform_os, platform_arch, platform_variant=None, context_path=None, context_access_token=None, task_file_path=None, image_names=None, is_push_enabled=None, no_cache=None, target=None, encoded_task_content=None, encoded_values_content=None, values_file_path=None, values_dict=None, agent_num_cores=None, status=None, trigger=None, timeout=None, credential_login_mode=None, credential_login_server=None, credential_username=None, credential_password=<PASSWORD>, identity_principal_id=None, identity_tenant_id=None, identity_type=None, user_assigned_identities=None, tags=None, connection_auth=None, **kwargs, ): """ .. versionadded:: 3.0.0 .. versionchanged:: 4.0.0 Ensure a container registry task exists. :param name: The name of the task. :param registry_name: The name of the container registry. :param resource_group: The name of the resource group to which the container registry belongs. :param task_type: The type of task to be scheduled. Must be 'DockerBuildStep', 'EncodedTaskStep', or 'FileTaskStep'. :param platform_os: The platform OS property against which the task has to happen. Accepts 'Windows' or 'Linux'. :param platform_arch: The platform architecture property against which the task has to happen. Accepts 'amd64', 'x86', or 'arm'. :param platform_variant: The platform CPU variant property against which the run has to happen. Accepts 'v6', 'v7', or 'v8'. :param context_path: (DockerBuildStep, EncodedTaskStep, FileTaskStep) The URL(absolute or relative) of the source context for the task step. The build context for the step of the task should be a well formed absolute URI or there should be only one source trigger for the task. :param context_access_token: (DockerBuildStep, EncodedTaskStep, FileTaskStep) The token (git PAT or SAS token of storage account blob) associated with the context for a step. :param task_file_path: (DockerBuildStep, FileTaskStep REQUIRED) The template/definition file path relative to the source. :param image_names: (DockerBuildStep) A list of strings containing the fully qualified image names including the repository and tag. :param is_push_enabled: (DockerBuildStep) The value of this property indicates whether the image built should be pushed to the registry or not. SDK default value: True. :param no_cache: (DockerBuildStep) The value of this property indicates whether the image cache is enabled or not. SDK default value: False. :param target: (DockerBuildStep) The name of the target build stage for the docker build. :param encoded_task_content: (EncodedTaskStep REQUIRED) Base64 encoded value of the template/definition file content. :param encoded_values_content: (EncodedTaskStep) Base64 encoded value of the parameters/values file content. :param values_file_path: (FileTaskStep) The values/parameters file path relative to the source context. :param values_dict: The collection of overridable values or arguments that can be passed when running a task. This is a list of dictionaries containing the following keys: 'name', 'value', and 'is_secret' :param agent_num_cores: The CPU configuration in terms of number of cores required for the run. :param trigger: The properties that describe all triggers for the task. This is a dictionary containing trigger information as described in the documentation for the `Azure Python SDK <https://docs.microsoft.com/en-us/python/api/azure-mgmt-containerregistry/azure.mgmt.containerregistry.v2019_04_01.models.triggerproperties?view=azure-python>`__. :param status: The current status of task. Possible values include: 'Disabled', 'Enabled'. :param timeout: Run timeout in seconds. Default value: 3600. :param credential_login_mode: The authentication mode which determines the source registry login scope. The credentials for the source registry will be generated using the given scope. These credentials will be used to login to the source registry during the run. Possible values include: 'None', 'Default'. :param credential_login_server: Describes the registry login server (myregistry.azurecr.io) for accessing other custom registries. :param credential_username: Username for accessing the registry defined in credential_login_server. :param credential_password: Password for accessing the registry defined in credential_login_server. :param identity_principal_id: The principal ID of resource identity. :param identity_tenant_id: The tenant ID of resource. :param identity_type: The identity type. Possible values include: 'SystemAssigned', 'UserAssigned'. :param user_assigned_identities: The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: ``/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}``. :param tags: A dictionary of strings can be passed as tag metadata to the object. Example usage: .. code-block:: yaml Ensure container registry task exists: azurerm.containerregistry.task.present: - name: testtask - registry_name: testrepo - resource_group: testgroup - task_type: DockerBuildStep - platform_os: Linux - platform_arch: amd64 - context_path: "https://github.com/Azure-Samples/acr-build-helloworld-node" - task_file_path: Dockerfile - image_names: - "testrepo:helloworldnode" - tags: how_awesome: very contact_name: <NAME> """ ret = {"name": name, "result": False, "comment": "", "changes": {}} action = "create" if not isinstance(connection_auth, dict): if ctx["acct"]: connection_auth = ctx["acct"] else: ret[ "comment" ] = "Connection information must be specified via acct or connection_auth dictionary!" return ret # get existing container registry task if present task = await hub.exec.azurerm.containerregistry.task.get( ctx, name, registry_name, resource_group, details=True, azurerm_log_level="info", **connection_auth, ) if "error" not in task: action = "update" # task_type changes if not task_type.upper().startswith(task["step"]["type"].upper()): ret["changes"]["task_type"] = { "old": task["step"]["type"], "new": task_type, } # platform_os changes if platform_os.upper() != task["platform"]["os"].upper(): ret["changes"]["platform_os"] = { "old": task["platform"]["os"], "new": platform_os, } # platform_arch changes if platform_arch.upper() != task["platform"]["architecture"].upper(): ret["changes"]["platform_arch"] = { "old": task["platform"]["architecture"], "new": platform_arch, } # platform_variant changes if ( platform_variant and platform_variant.upper() != task["platform"].get("variant", "").upper() ): ret["changes"]["platform_variant"] = { "old": task["platform"].get("variant"), "new": platform_variant, } # timeout changes if timeout and int(timeout) != task["timeout"]: ret["changes"]["timeout"] = { "old": task["timeout"], "new": timeout, } # status changes if status and status.upper() != task.get("status", "").upper(): ret["changes"]["status"] = { "old": task.get("platform"), "new": status, } # is_push_enabled changes if is_push_enabled is not None and is_push_enabled != task["step"].get( "is_push_enabled" ): ret["changes"]["is_push_enabled"] = { "old": task["step"].get("is_push_enabled"), "new": is_push_enabled, } # no_cache changes if no_cache is not None and no_cache != task["step"].get("no_cache"): ret["changes"]["no_cache"] = { "old": task["step"].get("no_cache"), "new": no_cache, } # context_path changes if context_path and context_path != task["step"].get("context_path"): ret["changes"]["context_path"] = { "old": task["step"].get("context_path"), "new": context_path, } # context_access_token changes if context_access_token and context_access_token != task["step"].get( "context_access_token" ): ret["changes"]["context_access_token"] = { "old": task["step"].get("context_access_token"), "new": context_access_token, } # task_file_path changes old_file_path = task["step"].get("docker_file_path") or task["step"].get( "task_file_path" ) if task_file_path and task_file_path != old_file_path: ret["changes"]["task_file_path"] = { "old": old_file_path, "new": task_file_path, } # target changes if target and target != task["step"].get("target"): ret["changes"]["target"] = { "old": task["step"].get("target"), "new": target, } # encoded_task_content changes if encoded_task_content and encoded_task_content != task["step"].get( "encoded_task_content" ): ret["changes"]["encoded_task_content"] = { "old": task["step"].get("encoded_task_content"), "new": encoded_task_content, } # encoded_values_content changes if encoded_values_content and encoded_values_content != task["step"].get( "encoded_values_content" ): ret["changes"]["encoded_values_content"] = { "old": task["step"].get("encoded_values_content"), "new": encoded_values_content, } # values_file_path changes if values_file_path and values_file_path != task["step"].get( "values_file_path" ): ret["changes"]["values_file_path"] = { "old": task["step"].get("values_file_path"), "new": values_file_path, } # values_dict changes if values_dict: old_vals = task["step"].get("arguments") or task["step"].get("values", {}) val_diff = differ.deep_diff(old_vals, values_dict) if val_diff: ret["changes"]["values_dict"] = val_diff # agent_num_cores changes old_cores = task.get("agent_configuration", {}).get("cpu") if agent_num_cores and int(agent_num_cores) != old_cores: ret["changes"]["agent_num_cores"] = { "old": task["agent_num_cores"], "new": agent_num_cores, } # trigger changes if trigger: trig_diff = differ.deep_diff(task.get("trigger", {}), trigger) if trig_diff: ret["changes"]["trigger"] = trig_diff # credentials changes if credential_login_server: credentials = { "source_registry": {"custom_registries": {credential_login_server: {}}} } if credential_login_mode: credentials["source_registry"]["login_mode"] = credential_login_mode if credential_username: credentials["source_registry"]["custom_registries"][ credential_login_server ]["username"] = credential_username if credential_password: credentials["source_registry"]["custom_registries"][ credential_login_server ]["username"] = credential_password cred_diff = differ.deep_diff(task.get("credentials", {}), credentials) if cred_diff: ret["changes"]["credentials"] = cred_diff # identity_principal_id changes old_prid = task.get("identity", {}).get("principal_id") if identity_principal_id and identity_principal_id != old_prid: ret["changes"]["identity_principal_id"] = { "old": old_prid, "new": identity_principal_id, } # identity_tenant_id changes old_tnid = task.get("identity", {}).get("tenant_id") if identity_tenant_id and identity_tenant_id != old_tnid: ret["changes"]["identity_tenant_id"] = { "old": old_tnid, "new": identity_tenant_id, } # identity_type changes old_idtype = task.get("identity", {}).get("type") if identity_type and identity_type != old_idtype: ret["changes"]["identity_type"] = { "old": old_idtype, "new": identity_type, } # user_assigned_identities changes if user_assigned_identities: old_uai = task.get("identity", {}).get("user_assigned_identities", []) comp = await hub.exec.azurerm.utils.compare_list_of_dicts( old_uai, user_assigned_identities, key_name="principal_id" ) if comp.get("changes"): ret["changes"]["user_assigned_identities"] = comp["changes"] # image_names changes old_img = sorted(task["step"].get("image_names", [])) images = sorted(image_names or []) if old_img != images: ret["changes"]["image_names"] = { "old": old_img, "new": image_names, } # tag changes tag_diff = differ.deep_diff(task.get("tags", {}), tags or {}) if tag_diff: ret["changes"]["tags"] = tag_diff if not ret["changes"]: ret["result"] = True ret["comment"] = "Container registry task {0} is already present.".format( name ) return ret if ctx["test"]: ret["comment"] = "Container registry task {0} would be updated.".format( name ) ret["result"] = None return ret elif ctx["test"]: ret["comment"] = "Container registry task {0} would be created.".format(name) ret["result"] = None return ret task_kwargs = kwargs.copy() task_kwargs.update(connection_auth) task = await hub.exec.azurerm.containerregistry.task.create_or_update( ctx=ctx, name=name, registry_name=registry_name, resource_group=resource_group, task_type=task_type, platform_os=platform_os, platform_arch=platform_arch, platform_variant=platform_variant, context_path=context_path, context_access_token=context_access_token, task_file_path=task_file_path, image_names=image_names, is_push_enabled=is_push_enabled, no_cache=no_cache, target=target, encoded_task_content=encoded_task_content, encoded_values_content=encoded_values_content, values_file_path=values_file_path, values_dict=values_dict, agent_num_cores=agent_num_cores, status=status, trigger=trigger, timeout=timeout, credential_login_mode=credential_login_mode, credential_login_server=credential_login_server, credential_username=credential_username, credential_password=<PASSWORD>, identity_principal_id=identity_principal_id, identity_tenant_id=identity_tenant_id, identity_type=identity_type, user_assigned_identities=user_assigned_identities, tags=tags, **task_kwargs, ) if action == "create": ret["changes"] = {"old": {}, "new": task} if "error" not in task: ret["result"] = True ret["comment"] = f"Container registry task {name} has been {action}d." return ret ret["comment"] = "Failed to {0} container registry task {1}! ({2})".format( action, name, task.get("error") ) if not ret["result"]: ret["changes"] = {} return ret async def absent( hub, ctx, name, registry_name, resource_group, connection_auth=None, **kwargs ): """ .. versionadded:: 3.0.0 Ensure a task does not exist in a container registry. :param name: Name of the task. :param registry_name: The name of the container registry. :param resource_group: The name of the resource group to which the container registry belongs. .. code-block:: yaml Ensure container registry task is absent: azurerm.containerregistry.task.absent: - name: testtask - registry_name: testrepo - resource_group: testgroup """ ret = {"name": name, "result": False, "comment": "", "changes": {}} if not isinstance(connection_auth, dict): if ctx["acct"]: connection_auth = ctx["acct"] else: ret[ "comment" ] = "Connection information must be specified via acct or connection_auth dictionary!" return ret task = await hub.exec.azurerm.containerregistry.task.get( ctx, name, registry_name, resource_group, azurerm_log_level="info", **connection_auth, ) if "error" in task: ret["result"] = True ret["comment"] = "Container registry task {0} is already absent.".format(name) return ret if ctx["test"]: ret["comment"] = "Container registry task {0} would be deleted.".format(name) ret["result"] = None ret["changes"] = { "old": task, "new": {}, } return ret deleted = await hub.exec.azurerm.containerregistry.task.delete( ctx, name, registry_name, resource_group, **connection_auth ) if deleted: ret["result"] = True ret["comment"] = "Container registry task {0} has been deleted.".format(name) ret["changes"] = {"old": task, "new": {}} return ret ret["comment"] = "Failed to delete container registry task {0}!".format(name) return ret
<gh_stars>1-10 // Source : https://leetcode.com/problems/single-number/ // Author : <NAME> /** * @param {number[]} nums * @return {number} */ var singleNumber = function(nums) { var ans = 0; for(var i = 0, len = nums.length; i < len; i++) ans ^= nums[i]; return ans; };
<reponame>navikt/diasight<filename>apps/frontend/src/components/summary/utils/update-composition.ts import { BundleTypeKind, Bundle_RequestMethodKind, IBundle, IComposition, ICondition, IReference, IResourceList, } from "@ahryman40k/ts-fhir-types/lib/R4"; import { SummaryChange } from "../../../layouts/contexts/summary-context"; import clonedeep from "lodash.clonedeep"; export const summaryToTransactionBundle = (summary: SummaryChange[]) => { const compositions: IComposition[] = []; const resources: IResourceList[] = []; const sum: SummaryChange[] = clonedeep(summary); sum.map((s) => s.resources.map((r) => { if (!resources.includes(r)) resources.push(r); }) ); for (const s of sum) { const localComp = compositions.find((c) => c.id === s.composition.id); const index = localComp ? compositions.indexOf(localComp) : -1; const updatedComposition = addResourcesToComposition( s.composition, s.condition, s.resources ); console.log(index); if (index !== -1) { compositions[index] = { ...updatedComposition }; } else { compositions.push({ ...updatedComposition }); } } const transactionBundle: IBundle = { resourceType: "Bundle", id: "bundle-transaction", type: BundleTypeKind._transaction, entry: [], }; resources.map((r) => { transactionBundle.entry?.push({ fullUrl: r.id, resource: r, request: { method: Bundle_RequestMethodKind._post, url: r.resourceType }, }); }); compositions.map((c) => { transactionBundle.entry?.push({ fullUrl: c.resourceType + "/" + c.id, resource: c, request: { method: Bundle_RequestMethodKind._put, url: `${c.resourceType}/${c.id}` }, }); }); return transactionBundle; }; const addResourcesToComposition = ( composition: IComposition, condition: ICondition, resources: IResourceList[] ) => { const conditionSection = findCompositionSection(composition, condition); if (conditionSection && composition.section) { const index = composition.section.indexOf(conditionSection); resources.map((r) => { const reference: IReference = { reference: r.id }; if (!conditionSection.entry) conditionSection.entry = []; conditionSection.entry = [...conditionSection.entry, reference]; }); composition.section[index] = { ...conditionSection }; } return composition; }; const findCompositionSection = (composition: IComposition, condition: ICondition) => { return composition.section?.find((s) => s.focus?.reference === "Condition/" + condition.id); };
<gh_stars>0 from django.contrib import admin from mptt.admin import MPTTModelAdmin from taggit.models import Tag as TaggitTag from collective_blog.models import Blog, Post, Membership, Comment, Tag from s_markdown.admin import MarkdownAdmin admin.site.unregister(TaggitTag) @admin.register(Blog) class BlogAdmin(MarkdownAdmin, admin.ModelAdmin): pass @admin.register(Post) class PostAdmin(MarkdownAdmin, admin.ModelAdmin): pass @admin.register(Comment) class CommentAdmin(MarkdownAdmin, MPTTModelAdmin): pass @admin.register(Membership) class MembershipAdmin(admin.ModelAdmin): pass @admin.register(Tag) class MembershipAdmin(admin.ModelAdmin): pass
from pypy.objspace.std.model import registerimplementation, W_Object from pypy.objspace.std.register_all import register_all from pypy.objspace.std.stringobject import W_AbstractStringObject from pypy.objspace.std.stringobject import W_StringObject from pypy.objspace.std.unicodeobject import delegate_String2Unicode from pypy.rlib.rstring import StringBuilder from pypy.interpreter.buffer import Buffer class W_StringBufferObject(W_AbstractStringObject): from pypy.objspace.std.stringtype import str_typedef as typedef w_str = None def __init__(self, builder): self.builder = builder # StringBuilder self.length = builder.getlength() def force(self): if self.w_str is None: s = self.builder.build() if self.length < len(s): s = s[:self.length] self.w_str = W_StringObject(s) return s else: return self.w_str._value def __repr__(w_self): """ representation for debugging purposes """ return "%s(%r[:%d])" % ( w_self.__class__.__name__, w_self.builder, w_self.length) def unwrap(self, space): return self.force() def str_w(self, space): return self.force() registerimplementation(W_StringBufferObject) # ____________________________________________________________ def joined2(str1, str2): builder = StringBuilder() builder.append(str1) builder.append(str2) return W_StringBufferObject(builder) # ____________________________________________________________ def delegate_buf2str(space, w_strbuf): w_strbuf.force() return w_strbuf.w_str def delegate_buf2unicode(space, w_strbuf): w_strbuf.force() return delegate_String2Unicode(space, w_strbuf.w_str) def len__StringBuffer(space, w_self): return space.wrap(w_self.length) def add__StringBuffer_String(space, w_self, w_other): if w_self.builder.getlength() != w_self.length: builder = StringBuilder() builder.append(w_self.force()) else: builder = w_self.builder builder.append(w_other._value) return W_StringBufferObject(builder) def str__StringBuffer(space, w_self): # you cannot get subclasses of W_StringBufferObject here assert type(w_self) is W_StringBufferObject return w_self from pypy.objspace.std import stringtype register_all(vars(), stringtype)
<filename>nanowar-webwork2/src/java/org/nanocontainer/nanowar/webwork2/PicoActionProxyFactory.java /***************************************************************************** * Copyright (C) NanoContainer Organization. All rights reserved. * * ------------------------------------------------------------------------- * * The software in this package is published under the terms of the BSD * * style license a copy of which has been included with this distribution in * * the LICENSE.txt file. * * * *****************************************************************************/ package org.nanocontainer.nanowar.webwork2; import com.opensymphony.xwork.ActionInvocation; import com.opensymphony.xwork.ActionProxy; import com.opensymphony.xwork.DefaultActionProxyFactory; import java.util.Map; import org.nanocontainer.nanowar.webwork2.PicoActionInvocation; /** * Extension of XWork's {@link com.opensymphony.xwork.ActionProxyFactory ActionProxyFactory} * which creates PicoActionInvocations. * * @author <NAME> * @see PicoActionInvocation * @deprecated Use DefaultActionProxyFactory */ public class PicoActionProxyFactory extends DefaultActionProxyFactory { public ActionInvocation createActionInvocation(ActionProxy actionProxy) throws Exception { return new PicoActionInvocation(actionProxy); } public ActionInvocation createActionInvocation(ActionProxy actionProxy, Map extraContext) throws Exception { return new PicoActionInvocation(actionProxy, extraContext); } public ActionInvocation createActionInvocation(ActionProxy actionProxy, Map extraContext, boolean pushAction) throws Exception { return new PicoActionInvocation(actionProxy, extraContext, pushAction); } }
# Register server to Spacewalk bash 'spacewalk_registration' do user 'root' code <<-EOH rpm -Uvh http://yum.spacewalkproject.org/2.6-client/RHEL/7/x86_64/spacewalk-client-repo-2.6-0.el7.noarch.rpm rpm -Uvh http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm yum -y install rhn-client-tools rhn-check rhn-setup rhnsd m2crypto yum-rhn-plugin rpm -Uvh http://paladin.myxingfu.net/pub/rhn-org-trusted-ssl-cert-1.0-1.noarch.rpm rhnreg_ks --serverUrl=http://paladin.myxingfu.net/XMLRPC --activationkey=1-centos-el7 cp /etc/yum/pluginconf.d/rhnplugin.conf /tmp mv /etc/yum.repos.d /etc/yum.repos.d.prespace EOH flags "-x" end
#!/bin/bash set -e set -x build_release() { export GOOS=$1 export GOARCH=$2 mkdir -p $RELEASE_DIR/lmsasm-$TRAVIS_TAG-$GOOS-$GOARCH cd $RELEASE_DIR/lmsasm-$TRAVIS_TAG-$GOOS-$GOARCH go build github.com/ev3dev/lmsasm/lmsasm go build github.com/ev3dev/lmsasm/lmsgen cp $TRAVIS_BUILD_DIR/LICENSE.txt . zip $RELEASE_DIR/lmsasm-$TRAVIS_TAG-$GOOS-$GOARCH.zip * } build_release darwin amd64 build_release linux amd64 build_release windows amd64
override func awake(withContext context: Any?) { if let sksFile = Bundle.main.url(forResource: "YourSpriteKitScene", withExtension: "sks") { let scene = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(Data(contentsOf: sksFile)) as? SKScene if let skScene = scene { spriteKitScene.presentScene(skScene) } else { print("Failed to load SpriteKit scene") } } else { print("SpriteKit scene file not found") } }
# Generated by Django 3.0.2 on 2020-01-16 10:50 from django.db import migrations from papermerge.core.utils import get_sql_content class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.RunSQL( get_sql_content('01_triggers.sql') ), migrations.RunSQL( get_sql_content('02_basetreenode.sql') ), migrations.RunSQL( get_sql_content('03_update_lang_cols.sql') ), migrations.RunSQL( get_sql_content('04_views.sql') ), ]
;(function(win){ if(!/洋葱数学$/.test(document.title)){ window.location.href = 'http://yangcong345.com'; return; } if('YangCongHelper' in win){ win.YangCongHelper.run(); }else{ $.ajax({ url: 'https://gist.githubusercontent.com/song940/40c90eb8f25368b0895a/raw/yangcong-helper.js', error: function(err){ alert('Oops ! 洋葱数学小助手遇到了点问题, 如果是网络问题, 请检查网络然后再点一次. 如果还不行, 请删除小助手然后重新安装 .'); win.open('https://lsong.org/~lsong/yangcong-helper'); }, success: function(content){ var script = document.createElement('script'); script.innerHTML = content; document.head.appendChild(script); win.YangCongHelper.init(); } }); } })(window);
<filename>benchmark_dataloader.py import torch from torch.utils.data import Dataset, DataLoader, random_split from torchvision import transforms import os import cv2 from cv2 import resize, GaussianBlur, findHomography, warpPerspective import numpy as np from random import random class Dataloader(Dataset) : def __init__(self, img_path, homographies_path, size) : self.transform = self.get_transform() self.size = size img_name = os.listdir(img_path) img_name.sort() img_name.sort(key=len) img = [os.path.join(img_path, f) for f in img_name] self.yes_img = img homographies_name = [f.replace("jpg", "homography.npy") for f in img_name] homographies = [os.path.join(homographies_path, f) for f in homographies_name] self.homographies = homographies self.len = len(self.yes_img) # - 2 # -2 because 3 images stacking def __len__(self) : return self.len def __getitem__(self, idx) : img_path = self.yes_img[idx] img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = resize(img, (self.size)) tensor_img = self.transform(img) tensor_img = tensor_img.view(3, tensor_img.shape[-2], tensor_img.shape[-1]) homography_path = self.homographies[idx] homography = np.load(homography_path) # homography = self.adapt_homography(homography) return {'img' : img, 'tensor_img' : tensor_img, 'matrix': homography, 'path': img_path} def get_transform(self): img_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) return img_transform def rotate_image(self, image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) return result def get_benchmark_dataloaders(img_path, label_path, size, batch_size=32): dataset = Dataloader(img_path, label_path, size) dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False) return dataloader
package com.hapramp.ui.activity; import android.app.ProgressDialog; import android.arch.lifecycle.Observer; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.ValueEventListener; import com.google.gson.Gson; import com.hapramp.R; import com.hapramp.analytics.EventReporter; import com.hapramp.api.RetrofitServiceGenerator; import com.hapramp.datastore.DataStore; import com.hapramp.datastore.JSONParser; import com.hapramp.models.AppServerUserModel; import com.hapramp.notification.FirebaseNotificationStore; import com.hapramp.notification.NotificationSubscriber; import com.hapramp.preferences.HaprampPreferenceManager; import com.hapramp.steem.CommunityListWrapper; import com.hapramp.steem.models.User; import com.hapramp.steemconnect.SteemConnectUtils; import com.hapramp.steemconnect4j.SteemConnect; import com.hapramp.steemconnect4j.SteemConnectCallback; import com.hapramp.steemconnect4j.SteemConnectException; import com.hapramp.ui.fragments.CompetitionFragment; import com.hapramp.ui.fragments.HomeFragment; import com.hapramp.ui.fragments.ProfileFragment; import com.hapramp.ui.fragments.SettingsFragment; import com.hapramp.utils.AppUpdateChecker; import com.hapramp.utils.BackstackManager; import com.hapramp.utils.ConnectionUtils; import com.hapramp.utils.FollowingsSyncUtils; import com.hapramp.utils.ResponseCodes; import com.hapramp.viewmodel.common.ConnectivityViewModel; import com.hapramp.views.AppUpdateAvailableDialog; import com.hapramp.views.extraa.CreateNewButtonView; import java.util.Locale; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class HomeActivity extends AppCompatActivity implements CreateNewButtonView.ItemClickListener { public static final String EXTRA_TAB_INDEX = "home.activity.tabindex"; private final int BOTTOM_MENU_HOME = 7; private final int BOTTOM_MENU_COMP = 8; private final int BOTTOM_MENU_PROFILE = 9; private final int BOTTOM_MENU_SETTINGS = 10; private final int BOTTOM_MENU_COMPETITIONS = 11; private final int FRAGMENT_HOME = 12; private final int FRAGMENT_PROFILE = 14; private final int FRAGMENT_SETTINGS = 15; private final int FRAGMENT_COMPETITIONS = 16; @BindView(R.id.contentPlaceHolder) FrameLayout contentPlaceHolder; @BindView(R.id.connectivity_text) TextView connectivityText; @BindView(R.id.connectivity_message_container) FrameLayout connectivityMessageContainer; @BindView(R.id.search_icon) ImageView searchIcon; @BindView(R.id.haprampIcon) ImageView haprampIcon; @BindView(R.id.notification_icon) ImageView notificationIcon; @BindView(R.id.action_bar_container) RelativeLayout actionBarContainer; @BindView(R.id.toolbar_drop_shadow) FrameLayout toolbarDropShadow; @BindView(R.id.shadow) ImageView shadow; @BindView(R.id.bottomBar_home) ImageView bottomBarHome; @BindView(R.id.bottomBar_wallet) ImageView bottomBarCompetition; @BindView(R.id.bottomBar_profile) ImageView bottomBarProfile; @BindView(R.id.bottomBar_settings) ImageView bottomBarSettings; @BindView(R.id.bottombar_container) LinearLayout bottombarContainer; @BindView(R.id.createNewBtn) CreateNewButtonView createNewBtn; @BindView(R.id.notification_count) TextView notificationCount; private int lastMenuSelection = BOTTOM_MENU_HOME; private FragmentManager fragmentManager; private HomeFragment homeFragment; private ProfileFragment profileFragment; private SettingsFragment settingsFragment; private CompetitionFragment competitionFragment; private ProgressDialog progressDialog; private Handler mHandler; private ConnectivityViewModel connectivityViewModel; private boolean backPressedOnce = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); initObjects(); syncBasicInfo(); BackstackManager.pushItem(FRAGMENT_HOME); collectExtras(); saveDeviceWidth(); attachListeners(); observeConnection(); listenToNotifications(); updateFirebase(); } private void updateFirebase() { new Thread() { @Override public void run() { EventReporter.reportDeviceId(); EventReporter.reportOpenEvent(); NotificationSubscriber.subscribeForUserTopic(); NotificationSubscriber.subscribeForNewCompetition(); AppUpdateChecker.checkAppUpdatesNode(HomeActivity.this, new AppUpdateChecker.AppUpdateAvailableListener() { @Override public void onAppUpdateAvailable() { mHandler.post(new Runnable() { @Override public void run() { AppUpdateAvailableDialog appUpdateAvailableDialog = new AppUpdateAvailableDialog(HomeActivity.this); appUpdateAvailableDialog.show(); } }); } }); } }.start(); } private void initObjects() { mHandler = new Handler(); fragmentManager = getSupportFragmentManager(); homeFragment = new HomeFragment(); profileFragment = new ProfileFragment(); profileFragment.setUsername(HaprampPreferenceManager.getInstance().getCurrentSteemUsername()); settingsFragment = new SettingsFragment(); competitionFragment = new CompetitionFragment(); progressDialog = new ProgressDialog(this); progressDialog.setCancelable(false); } private void syncBasicInfo() { if (HaprampPreferenceManager.getInstance().getCurrentSteemUserInfoAsJson().length() == 0) { showInterruptedProgressBar("Fetching profile info..."); } checkSteemconnectTokenValidity(); fetchAppUser(); DataStore.performAllCommunitySync(); DataStore.requestSyncLastPostCreationTime(); syncUserFollowings(); } private void fetchAppUser() { RetrofitServiceGenerator.getService().fetchAppUser().enqueue(new Callback<AppServerUserModel>() { @Override public void onResponse(Call<AppServerUserModel> call, Response<AppServerUserModel> response) { if (response.isSuccessful()) { HaprampPreferenceManager.getInstance().saveCurrentAppServerUserAsJson(new Gson().toJson(response.body())); HaprampPreferenceManager.getInstance() .saveUserSelectedCommunitiesAsJson(new Gson().toJson(new CommunityListWrapper(response.body().getCommunityList()))); } else if (response.code() == ResponseCodes.UNAUTHORIZED) { logout(); } else if (response.code() == ResponseCodes.INTERNAL_SERVER_ERROR) { Toast.makeText(HomeActivity.this, "Something went wrong at server!", Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<AppServerUserModel> call, Throwable t) { } }); } private void observeConnection() { connectivityViewModel = ViewModelProviders.of(this).get(ConnectivityViewModel.class); connectivityViewModel.getConnectivityState().observeForever(new Observer<Boolean>() { @Override public void onChanged(@Nullable Boolean isConnected) { if (ConnectionUtils.isConnected(HomeActivity.this)) { hideConnectivityBar(); } else { revealConnectivityBar(); } } }); } private void saveDeviceWidth() { Resources resources = getResources(); DisplayMetrics displayMetrics = resources.getDisplayMetrics(); int deviceWidth = displayMetrics.widthPixels; HaprampPreferenceManager.getInstance().setDeviceWidth(deviceWidth); } private void syncUserFollowings() { FollowingsSyncUtils.syncFollowings(this); } private void collectExtras() { Intent receiveIntent = getIntent(); if (receiveIntent != null) { int tabNumber = receiveIntent.getIntExtra(EXTRA_TAB_INDEX, 0); transactFragment(getFragmentAt(tabNumber)); } else { transactFragment(getFragmentAt(0)); } } private int getFragmentAt(int tabNumber) { switch (tabNumber) { case 0: return FRAGMENT_HOME; case 1: return FRAGMENT_COMPETITIONS; case 2: return FRAGMENT_PROFILE; case 3: return FRAGMENT_SETTINGS; default: return FRAGMENT_HOME; } } private void logout() { HaprampPreferenceManager.getInstance().clearPreferences(); Intent intent = new Intent(this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void attachListeners() { haprampIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (lastMenuSelection == BOTTOM_MENU_HOME) return; BackstackManager.pushItem(FRAGMENT_HOME); transactFragment(FRAGMENT_HOME); } }); bottomBarHome.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // check for the current selection if (lastMenuSelection == BOTTOM_MENU_HOME) return; BackstackManager.pushItem(FRAGMENT_HOME); transactFragment(FRAGMENT_HOME); } }); bottomBarCompetition.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (lastMenuSelection == BOTTOM_MENU_COMPETITIONS) return; BackstackManager.pushItem(FRAGMENT_COMPETITIONS); transactFragment(FRAGMENT_COMPETITIONS); } }); bottomBarProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (lastMenuSelection == BOTTOM_MENU_PROFILE) return; BackstackManager.pushItem(FRAGMENT_PROFILE); transactFragment(FRAGMENT_PROFILE); } }); bottomBarSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (lastMenuSelection == BOTTOM_MENU_SETTINGS) return; BackstackManager.pushItem(FRAGMENT_SETTINGS); transactFragment(FRAGMENT_SETTINGS); } }); createNewBtn.setItemClickListener(this); searchIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(HomeActivity.this, UserSearchActivity.class); startActivity(i); overridePendingTransition(R.anim.slide_right_enter, R.anim.slide_right_exit); } }); notificationIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { navigateToNotificationPage(); } }); } private void navigateToNotificationPage() { Intent intent = new Intent(this, NotificationActivity.class); startActivity(intent); } private void showInterruptedProgressBar(String msg) { if (progressDialog != null) { progressDialog.setMessage(msg); progressDialog.show(); } } @Override public void onBackPressed() { int topItem = BackstackManager.getTop(); if (topItem == FRAGMENT_HOME) { showExistAlert(); } else { BackstackManager.popItem(); transactFragment(BackstackManager.getTop()); } } private void showExistAlert() { if (backPressedOnce) { finish(); return; } backPressedOnce = true; EventReporter.reportEventSession(this); Toast.makeText(this, "Press back once more to exit", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { backPressedOnce = false; } }, 2000); } private void transactFragment(int fragment) { switch (fragment) { case FRAGMENT_HOME: swapSelection(BOTTOM_MENU_HOME); fragmentManager.beginTransaction() .addToBackStack("home") .replace(R.id.contentPlaceHolder, homeFragment) .commit(); break; case FRAGMENT_PROFILE: swapSelection(BOTTOM_MENU_PROFILE); fragmentManager.beginTransaction() .addToBackStack("profile") .replace(R.id.contentPlaceHolder, profileFragment) .commit(); break; case FRAGMENT_SETTINGS: swapSelection(BOTTOM_MENU_SETTINGS); fragmentManager.beginTransaction() .addToBackStack("setting") .replace(R.id.contentPlaceHolder, settingsFragment) .commit(); break; case FRAGMENT_COMPETITIONS: swapSelection(BOTTOM_MENU_COMPETITIONS); fragmentManager.beginTransaction() .addToBackStack("competitions") .replace(R.id.contentPlaceHolder, competitionFragment) .commit(); break; default: break; } } private void swapSelection(int newSelectedMenu) { if (newSelectedMenu == lastMenuSelection) return; resetLastSelection(lastMenuSelection); switch (newSelectedMenu) { case BOTTOM_MENU_HOME: bottomBarHome.setImageResource(R.drawable.home_icon_selected); lastMenuSelection = BOTTOM_MENU_HOME; break; case BOTTOM_MENU_PROFILE: bottomBarProfile.setImageResource(R.drawable.user_icon_selected); lastMenuSelection = BOTTOM_MENU_PROFILE; break; case BOTTOM_MENU_SETTINGS: bottomBarSettings.setImageResource(R.drawable.settings_icon_selected); lastMenuSelection = BOTTOM_MENU_SETTINGS; break; case BOTTOM_MENU_COMPETITIONS: bottomBarCompetition.setImageResource(R.drawable.competition_filled); lastMenuSelection = BOTTOM_MENU_COMPETITIONS; break; default: break; } } private void resetLastSelection(int lastMenuSelection) { switch (lastMenuSelection) { case BOTTOM_MENU_HOME: bottomBarHome.setImageResource(R.drawable.home_icon); break; case BOTTOM_MENU_PROFILE: bottomBarProfile.setImageResource(R.drawable.user_icon); break; case BOTTOM_MENU_SETTINGS: bottomBarSettings.setImageResource(R.drawable.settings_icon); break; case BOTTOM_MENU_COMPETITIONS: bottomBarCompetition.setImageResource(R.drawable.competition); break; default: break; } } @Override public void onCreateArticleButtonClicked() { Intent intent = new Intent(this, CreateArticleActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_up_enter, R.anim.slide_up_exit); } @Override public void onCreatePostButtonClicked() { Intent intent = new Intent(this, CreatePostActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_up_enter, R.anim.slide_up_exit); } @Override public void onCompetitionButtonClicked() { Intent intent = new Intent(this, CompetitionCreatorActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_up_enter, R.anim.slide_up_exit); } private void hideInterruptedProgressBar() { if (progressDialog != null) { progressDialog.dismiss(); } } private void hideConnectivityBar() { try { connectivityMessageContainer.setVisibility(View.GONE); } catch (Exception e) { Log.d("Exception", e.toString()); } } private void revealConnectivityBar() { try { connectivityMessageContainer.setVisibility(View.VISIBLE); } catch (Exception e) { Log.d("Exception", e.toString()); } } private void checkSteemconnectTokenValidity() { final SteemConnect steemConnect = SteemConnectUtils .getSteemConnectInstance(HaprampPreferenceManager.getInstance().getSC2AccessToken()); final Handler mHandler = new Handler(); new Thread() { @Override public void run() { steemConnect.me(new SteemConnectCallback() { @Override public void onResponse(String response) { JSONParser jsonParser = new JSONParser(); final User user = jsonParser.parseSC2UserJson(response); HaprampPreferenceManager.getInstance().saveCurrentSteemUserInfoAsJson(new Gson().toJson(user)); hideInterruptedProgressBar(); } @Override public void onError(final SteemConnectException e) { mHandler.post(new Runnable() { @Override public void run() { hideInterruptedProgressBar(); if (ConnectionUtils.isConnected(HomeActivity.this)) { logout(); } } }); } }); } }.start(); } private void listenToNotifications() { try { FirebaseNotificationStore.getNotificationsListNode().addValueEventListener(new ValueEventListener() { @Override public void onDataChange(final @NonNull DataSnapshot dataSnapshot) { mHandler.post(new Runnable() { @Override public void run() { if (dataSnapshot.exists()) { readNotificationMap((Map<String, Object>) dataSnapshot.getValue()); } else { if (notificationCount != null) { notificationCount.setVisibility(View.GONE); } } } }); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } catch (Exception e) { if (notificationCount != null) { notificationCount.setVisibility(View.GONE); } } } private void readNotificationMap(Map<String, Object> notifs) { int unread = 0; for (Map.Entry<String, Object> entry : notifs.entrySet()) { Map map = (Map) entry.getValue(); if (map.containsKey("read")) { if (map.get("read") instanceof Boolean) { if (!(Boolean) map.get("read")) { unread++; } } } } if (notificationCount != null) { if (unread == 0) { notificationCount.setVisibility(View.GONE); } else { notificationCount.setVisibility(View.VISIBLE); String c = unread > 10 ? "9+" : String.format(Locale.US, "%d", unread); notificationCount.setText(c); } } } }
<reponame>open-risk/numpymatrix # This is a sample Python script using numpymatrix, illustrating the deprecated API import numpymatrix as npm import numpy as np # the old matrix API A = npm.matrix([[1, 2], [3, 4]]) # the new API B = np.array([[1, 2], [3, 4]]) # identical print(A) print(B) # transpose OK print(A.T) print(B.T) # @ is same print(A @ A) print(B @ B) # same print(np.multiply(A, A)) print(np.multiply(B, B)) # * product is NOT OK print(A * A) print(B * B) # ** power is NOT OK print(A ** 2) print(B ** 2)
<gh_stars>0 # Copyright 2019 Microsoft Corporation # # 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. # # Requires Python 2.4+ and Openssl 1.0+ # import errno import os import random import time from azurelinuxagent.common.cgroup import CGroup from azurelinuxagent.common.cgroupconfigurator import CGroupConfigurator from azurelinuxagent.common.cgroupstelemetry import CGroupsTelemetry, Metric from azurelinuxagent.common.osutil.default import BASE_CGROUPS, DefaultOSUtil from azurelinuxagent.common.protocol.restapi import ExtHandler, ExtHandlerProperties from azurelinuxagent.common.utils import fileutil from azurelinuxagent.ga.exthandlers import ExtHandlerInstance from nose.plugins.attrib import attr from tests.tools import AgentTestCase, skip_if_predicate_false, skip_if_predicate_true, \ are_cgroups_enabled, is_trusty_in_travis, i_am_root, data_dir, patch def raise_ioerror(*_): e = IOError() from errno import EIO e.errno = EIO raise e def median(lst): data = sorted(lst) l_len = len(data) if l_len < 1: return None if l_len % 2 == 0: return (data[int((l_len - 1) / 2)] + data[int((l_len + 1) / 2)]) / 2.0 else: return data[int((l_len - 1) / 2)] def generate_metric_list(lst): return [float(sum(lst)) / float(len(lst)), min(lst), max(lst), median(lst), len(lst)] def consume_cpu_time(): waste = 0 for x in range(1, 200000): waste += random.random() return waste def consume_memory(): waste = [] for x in range(1, 3): waste.append([random.random()] * 10000) time.sleep(0.1) waste *= 0 return waste def make_new_cgroup(name="test-cgroup"): return CGroupConfigurator.get_instance().create_extension_cgroups(name) class TestCGroupsTelemetry(AgentTestCase): TestProcessIds = ["1000", "1001", "1002"] TestProcStatmMemoryUsed = 1234 TestProcComm = "python" TestProcCommandLine = "python -u bin/WALinuxAgent-2.2.45-py2.7.egg -run-exthandlers" NumSummarizationValues = 7 @classmethod def setUpClass(cls): AgentTestCase.setUpClass() # Use the default value for memory used from proc_statm cls.mock_get_memory_usage_from_proc_statm = patch("azurelinuxagent.common.resourceusage.MemoryResourceUsage." "get_memory_usage_from_proc_statm", return_value=TestCGroupsTelemetry.TestProcStatmMemoryUsed) cls.mock_get_memory_usage_from_proc_statm.start() # Use the default value for memory used from proc_statm cls.mock_get_tracked_processes = patch("azurelinuxagent.common.cgroup.CGroup.get_tracked_processes", return_value=TestCGroupsTelemetry.TestProcessIds) cls.mock_get_tracked_processes.start() cls.mock_get_proc_name = patch("azurelinuxagent.common.resourceusage.ProcessInfo.get_proc_name", return_value=TestCGroupsTelemetry.TestProcComm) cls.mock_get_proc_name.start() cls.mock_get_proc_cmdline = patch("azurelinuxagent.common.resourceusage.ProcessInfo.get_proc_cmdline", return_value=TestCGroupsTelemetry.TestProcCommandLine) cls.mock_get_proc_cmdline.start() # CPU Cgroups compute usage based on /proc/stat and /sys/fs/cgroup/.../cpuacct.stat; use mock data for those # files original_read_file = fileutil.read_file def mock_read_file(filepath, **args): if filepath == "/proc/stat": filepath = os.path.join(data_dir, "cgroups", "proc_stat_t0") elif filepath.endswith("/cpuacct.stat"): filepath = os.path.join(data_dir, "cgroups", "cpuacct.stat_t0") return original_read_file(filepath, **args) cls._mock_read_cpu_cgroup_file = patch("azurelinuxagent.common.utils.fileutil.read_file", side_effect=mock_read_file) cls._mock_read_cpu_cgroup_file.start() @classmethod def tearDownClass(cls): cls.mock_get_memory_usage_from_proc_statm.stop() cls.mock_get_tracked_processes.stop() cls.mock_get_proc_name.stop() cls.mock_get_proc_cmdline.stop() cls._mock_read_cpu_cgroup_file.stop() AgentTestCase.tearDownClass() def setUp(self): AgentTestCase.setUp(self) CGroupsTelemetry.reset() def tearDown(self): AgentTestCase.tearDown(self) CGroupsTelemetry.reset() @staticmethod def _track_new_extension_cgroups(num_extensions): for i in range(num_extensions): dummy_cpu_cgroup = CGroup.create("dummy_cpu_path_{0}".format(i), "cpu", "dummy_extension_{0}".format(i)) CGroupsTelemetry.track_cgroup(dummy_cpu_cgroup) dummy_memory_cgroup = CGroup.create("dummy_memory_path_{0}".format(i), "memory", "dummy_extension_{0}".format(i)) CGroupsTelemetry.track_cgroup(dummy_memory_cgroup) def _assert_cgroups_are_tracked(self, num_extensions): for i in range(num_extensions): self.assertTrue(CGroupsTelemetry.is_tracked("dummy_cpu_path_{0}".format(i))) self.assertTrue(CGroupsTelemetry.is_tracked("dummy_memory_path_{0}".format(i))) def _assert_calculated_resource_metrics_equal(self, cpu_usage, memory_usage, max_memory_usage, memory_statm_memory_usage, proc_ids=None): if not proc_ids: proc_ids = TestCGroupsTelemetry.TestProcessIds processes_instances = [CGroupsTelemetry.get_process_info_summary(pid) for pid in proc_ids] for _, cgroup_metric in CGroupsTelemetry._cgroup_metrics.items(): self.assertListEqual(cgroup_metric.get_memory_metrics()._data, memory_usage) self.assertListEqual(cgroup_metric.get_max_memory_metrics()._data, max_memory_usage) self.assertListEqual(cgroup_metric.get_cpu_metrics()._data, cpu_usage) for kv_pair in cgroup_metric.get_proc_statm_memory_metrics(): self.assertIn(kv_pair.pid_name_cmdline, processes_instances) self.assertListEqual(kv_pair.resource_metric._data, memory_statm_memory_usage) def _assert_polled_metrics_equal(self, metrics, cpu_metric_value, memory_metric_value, max_memory_metric_value, proc_stat_memory_usage_value, pids=None): for metric in metrics: self.assertIn(metric.category, ["Process", "Memory"]) if metric.category == "Process": self.assertEqual(metric.counter, "% Processor Time") self.assertEqual(metric.value, cpu_metric_value) if metric.category == "Memory": self.assertIn(metric.counter, ["Total Memory Usage", "Max Memory Usage", "Memory Used by Process"]) if metric.counter == "Total Memory Usage": self.assertEqual(metric.value, memory_metric_value) elif metric.counter == "Max Memory Usage": self.assertEqual(metric.value, max_memory_metric_value) elif metric.counter == "Memory Used by Process": if pids: processes_instances = [CGroupsTelemetry.get_process_info_summary(pid) for pid in pids] else: processes_instances = [CGroupsTelemetry.get_process_info_summary(pid) for pid in TestCGroupsTelemetry.TestProcessIds] self.assertIn(metric.instance, processes_instances) self.assertEqual(metric.value, proc_stat_memory_usage_value) def _assert_extension_metrics_data(self, collected_metrics, num_extensions, cpu_percent_values, proc_stat_memory_usage_values, memory_usage_values, max_memory_usage_values, is_cpu_present=True, is_memory_present=True): num_summarization_values = TestCGroupsTelemetry.NumSummarizationValues if not (is_cpu_present or is_memory_present): self.assertEquals(collected_metrics, {}) return else: for i in range(num_extensions): name = "dummy_extension_{0}".format(i) if is_memory_present: self.assertIn(name, collected_metrics) self.assertIn("memory", collected_metrics[name]) self.assertIn("cur_mem", collected_metrics[name]["memory"]) self.assertIn("max_mem", collected_metrics[name]["memory"]) self.assertEqual(num_summarization_values, len(collected_metrics[name]["memory"]["cur_mem"])) self.assertEqual(num_summarization_values, len(collected_metrics[name]["memory"]["max_mem"])) self.assertIn("proc_statm_memory", collected_metrics[name]) self.assertEqual(3, len(collected_metrics[name]["proc_statm_memory"])) # number of processes added for tracked_process in collected_metrics[name]["proc_statm_memory"]: self.assertEqual(num_summarization_values, len(collected_metrics[name]["proc_statm_memory"][tracked_process])) self.assertListEqual(generate_metric_list(proc_stat_memory_usage_values), collected_metrics[name]["proc_statm_memory"][tracked_process][0:5]) self.assertListEqual(generate_metric_list(memory_usage_values), collected_metrics[name]["memory"]["cur_mem"][0:5]) self.assertListEqual(generate_metric_list(max_memory_usage_values), collected_metrics[name]["memory"]["max_mem"][0:5]) if is_cpu_present: self.assertIn("cpu", collected_metrics[name]) self.assertIn("cur_cpu", collected_metrics[name]["cpu"]) self.assertEqual(num_summarization_values, len(collected_metrics[name]["cpu"]["cur_cpu"])) self.assertListEqual(generate_metric_list(cpu_percent_values), collected_metrics[name]["cpu"]["cur_cpu"][0:5]) def test_telemetry_polling_with_active_cgroups(self, *args): num_extensions = 3 self._track_new_extension_cgroups(num_extensions) with patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_max_memory_usage") as patch_get_memory_max_usage: with patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage") as patch_get_memory_usage: with patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage") as patch_get_cpu_usage: with patch("azurelinuxagent.common.cgroup.CGroup.is_active") as patch_is_active: patch_is_active.return_value = True current_cpu = 30 current_memory = 209715200 current_max_memory = 471859200 current_proc_statm = TestCGroupsTelemetry.TestProcStatmMemoryUsed # 1 CPU metric + 1 Current Memory + 1 Max memor + num_processes * memory from statm num_of_metrics_per_extn_expected = 1 + 1 + 1 + 3 * 1 patch_get_cpu_usage.return_value = current_cpu patch_get_memory_usage.return_value = current_memory # example 200 MB patch_get_memory_max_usage.return_value = current_max_memory # example 450 MB num_polls = 10 for data_count in range(1, num_polls + 1): metrics = CGroupsTelemetry.poll_all_tracked() self.assertEqual(len(CGroupsTelemetry._cgroup_metrics), num_extensions) self._assert_calculated_resource_metrics_equal(cpu_usage=[current_cpu] * data_count, memory_usage=[current_memory] * data_count, max_memory_usage=[current_max_memory] * data_count, proc_ids=TestCGroupsTelemetry.TestProcessIds, memory_statm_memory_usage=[current_proc_statm] * data_count) self.assertEqual(len(metrics), num_extensions * num_of_metrics_per_extn_expected) self._assert_polled_metrics_equal(metrics, current_cpu, current_memory, current_max_memory, current_proc_statm) collected_metrics = CGroupsTelemetry.report_all_tracked() self._assert_extension_metrics_data(collected_metrics, num_extensions, [current_cpu] * num_polls, [TestCGroupsTelemetry.TestProcStatmMemoryUsed] * num_polls, [current_memory] * num_polls, [current_max_memory] * num_polls, is_cpu_present=False) self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), num_extensions) self._assert_calculated_resource_metrics_equal([], [], [], [], []) @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_max_memory_usage", side_effect=raise_ioerror) @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage", side_effect=raise_ioerror) @patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage", side_effect=raise_ioerror) @patch("azurelinuxagent.common.cgroup.CGroup.is_active", return_value=False) def test_telemetry_polling_with_inactive_cgroups(self, *_): num_extensions = 5 no_extensions_expected = 0 self._track_new_extension_cgroups(num_extensions) self._assert_cgroups_are_tracked(num_extensions) metrics = CGroupsTelemetry.poll_all_tracked() for i in range(num_extensions): self.assertFalse(CGroupsTelemetry.is_tracked("dummy_cpu_path_{0}".format(i))) self.assertFalse(CGroupsTelemetry.is_tracked("dummy_memory_path_{0}".format(i))) self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), num_extensions) self._assert_calculated_resource_metrics_equal([], [], [], [], proc_ids=None) self.assertEqual(len(metrics), 0) collected_metrics = CGroupsTelemetry.report_all_tracked() self._assert_extension_metrics_data(collected_metrics, num_extensions, [], [], [], [], is_cpu_present=False, is_memory_present=False) self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), no_extensions_expected) self._assert_calculated_resource_metrics_equal([], [], [], [], []) @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_max_memory_usage") @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage") @patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage") @patch("azurelinuxagent.common.cgroup.CGroup.is_active") @patch("azurelinuxagent.common.resourceusage.MemoryResourceUsage.get_memory_usage_from_proc_statm") def test_telemetry_polling_with_changing_cgroups_state(self, patch_get_statm, patch_is_active, patch_get_cpu_usage, patch_get_mem, patch_get_max_mem, *args): num_extensions = 5 self._track_new_extension_cgroups(num_extensions) patch_is_active.return_value = True no_extensions_expected = 0 expected_data_count = 1 current_cpu = 30 current_memory = 209715200 current_max_memory = 471859200 current_proc_statm = 20000000 patch_get_cpu_usage.return_value = current_cpu patch_get_mem.return_value = current_memory # example 200 MB patch_get_max_mem.return_value = current_max_memory # example 450 MB patch_get_statm.return_value = current_proc_statm self._assert_cgroups_are_tracked(num_extensions) CGroupsTelemetry.poll_all_tracked() self._assert_cgroups_are_tracked(num_extensions) patch_is_active.return_value = False patch_get_cpu_usage.side_effect = raise_ioerror patch_get_mem.side_effect = raise_ioerror patch_get_max_mem.side_effect = raise_ioerror patch_get_statm.side_effect = raise_ioerror CGroupsTelemetry.poll_all_tracked() for i in range(num_extensions): self.assertFalse(CGroupsTelemetry.is_tracked("dummy_cpu_path_{0}".format(i))) self.assertFalse(CGroupsTelemetry.is_tracked("dummy_memory_path_{0}".format(i))) self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), num_extensions) self._assert_calculated_resource_metrics_equal( cpu_usage=[current_cpu] * expected_data_count, memory_usage=[current_memory] * expected_data_count, max_memory_usage=[current_max_memory] * expected_data_count, proc_ids=TestCGroupsTelemetry.TestProcessIds, memory_statm_memory_usage=[current_proc_statm] * expected_data_count ) CGroupsTelemetry.report_all_tracked() self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), no_extensions_expected) self._assert_calculated_resource_metrics_equal([], [], [], [], []) # mocking get_proc_stat to make it run on Mac and other systems. This test does not need to read the values of the # /proc/stat file on the filesystem. @patch("azurelinuxagent.common.logger.periodic_warn") def test_telemetry_polling_to_not_generate_transient_logs_ioerror_file_not_found(self, patch_periodic_warn): num_extensions = 1 self._track_new_extension_cgroups(num_extensions) self.assertEqual(0, patch_periodic_warn.call_count) # Not expecting logs present for io_error with errno=errno.ENOENT io_error_2 = IOError() io_error_2.errno = errno.ENOENT with patch("azurelinuxagent.common.utils.fileutil.read_file", side_effect=io_error_2): poll_count = 1 for data_count in range(poll_count, 10): CGroupsTelemetry.poll_all_tracked() self.assertEqual(0, patch_periodic_warn.call_count) @patch("azurelinuxagent.common.logger.periodic_warn") def test_telemetry_polling_to_generate_transient_logs_ioerror_permission_denied(self, patch_periodic_warn): num_extensions = 1 num_controllers = 2 is_active_check_per_controller = 2 self._track_new_extension_cgroups(num_extensions) self.assertEqual(0, patch_periodic_warn.call_count) # Expecting logs to be present for different kind of errors io_error_3 = IOError() io_error_3.errno = errno.EPERM with patch("azurelinuxagent.common.utils.fileutil.read_file", side_effect=io_error_3): poll_count = 1 expected_count_per_call = num_controllers + is_active_check_per_controller # each collect per controller would generate a log statement, and each cgroup would invoke a # is active check raising an exception for data_count in range(poll_count, 10): CGroupsTelemetry.poll_all_tracked() self.assertEqual(poll_count * expected_count_per_call, patch_periodic_warn.call_count) def test_telemetry_polling_to_generate_transient_logs_index_error(self): num_extensions = 1 self._track_new_extension_cgroups(num_extensions) # Generating a different kind of error (non-IOError) to check the logging. # Trying to invoke IndexError during the getParameter call with patch("azurelinuxagent.common.utils.fileutil.read_file", return_value=''): with patch("azurelinuxagent.common.logger.periodic_warn") as patch_periodic_warn: expected_call_count = 2 # 1 periodic warning for the cpu cgroups, and 1 for memory for data_count in range(1, 10): CGroupsTelemetry.poll_all_tracked() self.assertEqual(expected_call_count, patch_periodic_warn.call_count) @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_max_memory_usage") @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage") @patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage") @patch("azurelinuxagent.common.cgroup.CGroup.is_active") @patch("azurelinuxagent.common.resourceusage.MemoryResourceUsage.get_memory_usage_from_proc_statm") def test_telemetry_calculations(self, patch_get_statm, patch_is_active, patch_get_cpu_usage, patch_get_memory_usage, patch_get_memory_max_usage, *args): num_polls = 10 num_extensions = 1 cpu_percent_values = [random.randint(0, 100) for _ in range(num_polls)] # only verifying calculations and not validity of the values. memory_usage_values = [random.randint(0, 8 * 1024 ** 3) for _ in range(num_polls)] max_memory_usage_values = [random.randint(0, 8 * 1024 ** 3) for _ in range(num_polls)] proc_stat_memory_usage_values = [random.randint(0, 8 * 1024 ** 3) for _ in range(num_polls)] self._track_new_extension_cgroups(num_extensions) self.assertEqual(2 * num_extensions, len(CGroupsTelemetry._tracked)) for i in range(num_polls): patch_is_active.return_value = True patch_get_cpu_usage.return_value = cpu_percent_values[i] patch_get_memory_usage.return_value = memory_usage_values[i] # example 200 MB patch_get_memory_max_usage.return_value = max_memory_usage_values[i] # example 450 MB patch_get_statm.return_value = proc_stat_memory_usage_values[i] metrics = CGroupsTelemetry.poll_all_tracked() # 1 CPU metric + 1 Current Memory + 1 Max memory + num_processes (3) * memory from statm self.assertEqual(len(metrics), 6 * num_extensions) self._assert_polled_metrics_equal(metrics, cpu_percent_values[i], memory_usage_values[i], max_memory_usage_values[i], proc_stat_memory_usage_values[i]) collected_metrics = CGroupsTelemetry.report_all_tracked() self._assert_extension_metrics_data(collected_metrics, num_extensions, cpu_percent_values, proc_stat_memory_usage_values, memory_usage_values, max_memory_usage_values) def test_cgroup_tracking(self, *args): num_extensions = 5 num_controllers = 2 self._track_new_extension_cgroups(num_extensions) self._assert_cgroups_are_tracked(num_extensions) self.assertEqual(num_extensions * num_controllers, len(CGroupsTelemetry._tracked)) def test_cgroup_pruning(self, *args): num_extensions = 5 num_controllers = 2 self._track_new_extension_cgroups(num_extensions) self._assert_cgroups_are_tracked(num_extensions) self.assertEqual(num_extensions * num_controllers, len(CGroupsTelemetry._tracked)) CGroupsTelemetry.prune_all_tracked() for i in range(num_extensions): self.assertFalse(CGroupsTelemetry.is_tracked("dummy_cpu_path_{0}".format(i))) self.assertFalse(CGroupsTelemetry.is_tracked("dummy_memory_path_{0}".format(i))) self.assertEqual(0, len(CGroupsTelemetry._tracked)) def test_cgroup_is_tracked(self, *args): num_extensions = 5 self._track_new_extension_cgroups(num_extensions) self._assert_cgroups_are_tracked(num_extensions) self.assertFalse(CGroupsTelemetry.is_tracked("not_present_cpu_dummy_path")) self.assertFalse(CGroupsTelemetry.is_tracked("not_present_memory_dummy_path")) @patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage", side_effect=raise_ioerror) @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage", side_effect=raise_ioerror) def test_process_cgroup_metric_with_incorrect_cgroups_mounted(self, *args): num_extensions = 5 self._track_new_extension_cgroups(num_extensions) for data_count in range(1, 10): metrics = CGroupsTelemetry.poll_all_tracked() self.assertEqual(len(metrics), 0) self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), num_extensions) collected_metrics = {} for name, cgroup_metrics in CGroupsTelemetry._cgroup_metrics.items(): collected_metrics[name] = CGroupsTelemetry._process_cgroup_metric(cgroup_metrics) self.assertEqual(collected_metrics[name], {}) # empty @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage", side_effect=raise_ioerror) def test_process_cgroup_metric_with_no_memory_cgroup_mounted(self, *args): num_extensions = 5 self._track_new_extension_cgroups(num_extensions) with patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage") as patch_get_cpu_usage: with patch("azurelinuxagent.common.cgroup.CGroup.is_active") as patch_is_active: patch_is_active.return_value = True current_cpu = 30 patch_get_cpu_usage.return_value = current_cpu poll_count = 1 for data_count in range(poll_count, 10): metrics = CGroupsTelemetry.poll_all_tracked() self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), num_extensions) self._assert_calculated_resource_metrics_equal(cpu_usage=[current_cpu] * data_count, memory_usage=[] , max_memory_usage=[], proc_ids=[], memory_statm_memory_usage=[]) self.assertEqual(len(metrics), num_extensions * 1) # Only CPU populated self._assert_polled_metrics_equal(metrics, current_cpu, 0, 0, 0) CGroupsTelemetry.report_all_tracked() self.assertEqual(CGroupsTelemetry._cgroup_metrics.__len__(), num_extensions) self._assert_calculated_resource_metrics_equal([], [], [], [], []) @patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage", side_effect=raise_ioerror) def test_process_cgroup_metric_with_no_cpu_cgroup_mounted(self, *args): num_extensions = 5 self._track_new_extension_cgroups(num_extensions) with patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_max_memory_usage") as patch_get_memory_max_usage: with patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage") as patch_get_memory_usage: with patch("azurelinuxagent.common.cgroup.CGroup.is_active") as patch_is_active: patch_is_active.return_value = True current_memory = 209715200 current_max_memory = 471859200 patch_get_memory_usage.return_value = current_memory # example 200 MB patch_get_memory_max_usage.return_value = current_max_memory # example 450 MB num_polls = 10 for data_count in range(1, num_polls + 1): metrics = CGroupsTelemetry.poll_all_tracked() self.assertEqual(len(CGroupsTelemetry._cgroup_metrics), num_extensions) self._assert_calculated_resource_metrics_equal(cpu_usage=[], memory_usage=[current_memory] * data_count, max_memory_usage=[current_max_memory] * data_count, memory_statm_memory_usage=[TestCGroupsTelemetry.TestProcStatmMemoryUsed] * data_count, proc_ids=TestCGroupsTelemetry.TestProcessIds) # Memory is only populated, CPU is not. Thus 5 metrics per cgroup. self.assertEqual(len(metrics), num_extensions * 5) self._assert_polled_metrics_equal(metrics, 0, current_memory, current_max_memory, TestCGroupsTelemetry.TestProcStatmMemoryUsed) collected_metrics = CGroupsTelemetry.report_all_tracked() self._assert_extension_metrics_data(collected_metrics, num_extensions, [], [TestCGroupsTelemetry.TestProcStatmMemoryUsed] * num_polls, [current_memory] * num_polls, [current_max_memory] * num_polls, is_cpu_present=False) self.assertEqual(len(CGroupsTelemetry._cgroup_metrics), num_extensions) self._assert_calculated_resource_metrics_equal([], [], [], [], []) @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_memory_usage", side_effect=raise_ioerror) @patch("azurelinuxagent.common.cgroup.MemoryCgroup.get_max_memory_usage", side_effect=raise_ioerror) @patch("azurelinuxagent.common.cgroup.CpuCgroup.get_cpu_usage", side_effect=raise_ioerror) def test_extension_telemetry_not_sent_for_empty_perf_metrics(self, *args): num_extensions = 5 self._track_new_extension_cgroups(num_extensions) with patch("azurelinuxagent.common.cgroupstelemetry.CGroupsTelemetry._process_cgroup_metric") as \ patch_process_cgroup_metric: with patch("azurelinuxagent.common.cgroup.CGroup.is_active") as patch_is_active: patch_is_active.return_value = False patch_process_cgroup_metric.return_value = {} poll_count = 1 for data_count in range(poll_count, 10): metrics = CGroupsTelemetry.poll_all_tracked() self.assertEqual(0, len(metrics)) collected_metrics = CGroupsTelemetry.report_all_tracked() self.assertEqual(0, len(collected_metrics)) class TestMetric(AgentTestCase): def test_empty_metrics(self): test_metric = Metric() self.assertEqual("None", test_metric.first_poll_time()) self.assertEqual("None", test_metric.last_poll_time()) self.assertEqual(0, test_metric.count()) self.assertEqual(None, test_metric.median()) self.assertEqual(None, test_metric.max()) self.assertEqual(None, test_metric.min()) self.assertEqual(None, test_metric.average()) def test_metrics(self): num_polls = 10 test_values = [random.randint(0, 100) for _ in range(num_polls)] test_metric = Metric() for value in test_values: test_metric.append(value) self.assertListEqual(generate_metric_list(test_values), [test_metric.average(), test_metric.min(), test_metric.max(), test_metric.median(), test_metric.count()]) test_metric.clear() self.assertEqual("None", test_metric.first_poll_time()) self.assertEqual("None", test_metric.last_poll_time()) self.assertEqual(0, test_metric.count()) self.assertEqual(None, test_metric.median()) self.assertEqual(None, test_metric.max()) self.assertEqual(None, test_metric.min()) self.assertEqual(None, test_metric.average())
<gh_stars>0 import { join } from "path"; import { existsSync, readFileSync, writeFileSync } from "fs"; /** * Get the serverless object from package.json, serverless.config.js and .serverlessrc * @param path Path to serverless package (default is current path) */ export function getServerlessConfig(path: string = process.cwd()) { //Get from each type of file let out: { [key: string]: any } = {}; if (existsSync(join(path, "package.json"))) { const { name, version, serverless } = JSON.parse( readFileSync(join(path, "package.json"), { encoding: "utf-8" }) ); out.name = name; out.version = version; if (serverless) out = { ...out, ...serverless }; } if (existsSync(join(path, "serverless.config.js"))) { const result = require(join(path, "serverless.config.js")); if (result) out = { ...out, ...result }; } if (existsSync(join(path, ".serverlessrc"))) { const result = JSON.parse( readFileSync(join(path, ".serverlessrc"), { encoding: "utf-8" }) ); if (result) out = { ...out, ...result }; } return out; } /** * Save a new config map * @param newConfigMap New set of serverless considerations * @param path Path to the serverless package (default current path) * @param targetFile WHether to amend package.json or recreate .serverlessrc (defaults to the latter) */ export function writeServerlessConfig( newConfigMap: { [key: string]: any }, path: string = process.cwd(), targetFile: "package.json" | ".serverlessrc" = ".serverlessrc" ) { switch (targetFile) { case "package.json": { let p = JSON.parse( readFileSync(join(path, "package.json"), { encoding: "utf-8" }) ); p.serverless = newConfigMap; writeFileSync(join(path, "package.json"), JSON.stringify(p, null, 2)); } case ".serverlessrc": const json = JSON.stringify(newConfigMap); writeFileSync(join(path, ".serverlessrc"), json); break; default: throw new Error("Not a valid target for writing"); } } /** * Update a serverless config (shallow only - replacing a tree element replaces the whole tree) * @param configUpdates Map of updates to change (e.g. `{name: "newName"}`) * @param path Path to the serverless package (default is current dir) * @param targetFile Whether to update package.json or .serverlessrc - defaults to latter */ export function updateServerlessConfig( configUpdates: { [key: string]: any }, path: string = process.cwd(), targetFile: "package.json" | ".serverlessrc" = ".serverlessrc" ) { switch (targetFile) { case "package.json": { let p = JSON.parse( readFileSync(join(path, "package.json"), { encoding: "utf-8" }) ); if (!p.serverless) p.serverless = configUpdates; else p.serverless = { ...p.serverless, ...configUpdates }; writeFileSync(join(path, "package.json"), JSON.stringify(p, null, 2)); } case ".serverlessrc": if (!existsSync(join(path, ".serverlessrc"))) return writeServerlessConfig(configUpdates, path, targetFile); let s = JSON.parse( readFileSync(join(path, ".serverlessrc"), { encoding: "utf-8" }) ); s = { ...s, ...configUpdates }; const json = JSON.stringify(s, null, 2); writeFileSync(join(path, ".serverlessrc"), json); break; default: throw new Error("Not a valid target for writing"); } }