text
stringlengths
1
1.05M
package com.ctrip.persistence.entity; import javax.persistence.Entity; import javax.persistence.Table; /** * @author <NAME> */ @Entity @Table(name = "t_element_tpl_param_group") public class ElementTplParamGroup extends BaseEntity { private String name; private String value; private Boolean closed; private Integer sort; public ElementTplParamGroup() { } public ElementTplParamGroup(String name, String value, Boolean closed, Integer sort) { this.name = name; this.value = value; this.closed = closed; this.sort = sort; } public String getName() { return name; } public ElementTplParamGroup setName(String name) { this.name = name; return this; } public String getValue() { return value; } public ElementTplParamGroup setValue(String value) { this.value = value; return this; } public Boolean getClosed() { return closed; } public ElementTplParamGroup setClosed(Boolean closed) { this.closed = closed; return this; } public Integer getSort() { return sort; } public ElementTplParamGroup setSort(Integer sort) { this.sort = sort; return this; } }
<reponame>get-bundled/axyz-sdk import React, { useMemo } from 'react'; import Axyz, { type AxyzSDKOptions } from '@axyzsdk/js'; import { createTheme, CSS, NextUIProvider } from '@nextui-org/react'; import { WagmiProvider } from 'wagmi'; import { ConnectionProvider as SolanaConnectionProvider, WalletProvider as SolanaProvider, } from '@solana/wallet-adapter-react'; import { clusterApiUrl } from '@solana/web3.js'; import EthereumWalletProvider from '../Ethereum/WalletProvider'; import SolanaWalletProvider from '../Solana/WalletProvider'; import ModalConnect from '../ModalConnect'; import { AxyzContext } from '../../hooks/useAxyz'; import ModalProvider from '../ModalProvider'; import ThemeController from './ThemeController'; interface Props extends AxyzSDKOptions { apiKey: string; darkMode?: boolean; connectModal?: boolean; modalCss?: CSS; } const AxyzProvider: React.FC<Props> = ({ children, environment, solanaNetwork, ethereumChain, apiKey, onError, modalCss, connectModal = true, ethereumAutoConnect = true, solanaAutoConnect = true, darkMode = true, }) => { const theme = useMemo(() => createTheme({ type: darkMode ? 'dark' : 'light' }), [darkMode]); const axyz = useMemo( () => Axyz(apiKey, { environment, solanaNetwork, solanaAutoConnect, ethereumChain, ethereumAutoConnect, onError, }), // eslint-disable-next-line react-hooks/exhaustive-deps [apiKey, environment, solanaNetwork] ); return ( <NextUIProvider theme={theme} disableBaseline> <ThemeController darkMode={darkMode} /> <AxyzContext.Provider value={axyz}> <WagmiProvider autoConnect={ethereumAutoConnect} connectors={axyz.ethereum.wallets} connectorStorageKey="axyz.ethereum" > <SolanaConnectionProvider endpoint={clusterApiUrl(solanaNetwork)}> <SolanaProvider autoConnect={solanaAutoConnect} onError={onError} wallets={axyz.solana.wallets} localStorageKey="axyz:solana:wallet" > <EthereumWalletProvider autoConnect={ethereumAutoConnect}> <SolanaWalletProvider autoConnect={solanaAutoConnect}> <ModalProvider> {connectModal && <ModalConnect css={modalCss} onError={onError} />} {children} </ModalProvider> </SolanaWalletProvider> </EthereumWalletProvider> </SolanaProvider> </SolanaConnectionProvider> </WagmiProvider> </AxyzContext.Provider> </NextUIProvider> ); }; export default AxyzProvider;
from fuzzywuzzy import fuzz from fuzzywuzzy import process import os, sys, time KEY_SET_FILE = "data/key.set" if not os.path.exists(KEY_SET_FILE): raise Exception("Key set cannot be located") keys = [str(line.strip()) for line in open(KEY_SET_FILE)] """ Let's only support searching for a single key for now. We will hope that command line arguments will come quoted, but if that isn't the case, we'll compress the words into a single string. """ search_term = "" if len(sys.argv) < 2: raise Exception("Must pass a key to search for in the keyset!") elif len(sys.argv) > 2: search_term = ' '.join(sys.argv[1:]) else: search_term = str(sys.argv[1]) start = time.clock() if not search_term in keys: """ Arbitrarily return the 5 closest matches... """ fuzzy_matches = process.extract(search_term, keys, limit=5) else: fuzzy_matches = [(search_term, 100)] elapsed = (time.clock() - start) print elapsed for match in fuzzy_matches: print match sys.exit(0)
#!/bin/bash while [[kill -0 $0]] do echo "$PID is running" # Do something knowing the pid exists, i.e. the process with $PID is running done python trainval_net.py --da True --src city --tar fcity --net res101 --bs 1 --lr 0.001 --save_dir data/pretrained_model --cuda --lr_decay_step 50000 2>&1 | tee debug/train_loop_04.09.18_1 echo "Executed"
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.phoneSquare = void 0; var phoneSquare = { "viewBox": "0 0 1536 1792", "children": [{ "name": "path", "attribs": { "d": "M1280 1193q0-11-2-16t-18-16.5-40.5-25-47.5-26.5-45.5-25-28.5-15q-5-3-19-13t-25-15-21-5q-15 0-36.5 20.5t-39.5 45-38.5 45-33.5 20.5q-7 0-16.5-3.5t-15.5-6.5-17-9.5-14-8.5q-99-55-170-126.5t-127-170.5q-2-3-8.5-14t-9.5-17-6.5-15.5-3.5-16.5q0-13 20.5-33.5t45-38.5 45-39.5 20.5-36.5q0-10-5-21t-15-25-13-19q-3-6-15-28.5t-25-45.5-26.5-47.5-25-40.5-16.5-18-16-2q-48 0-101 22-46 21-80 94.5t-34 130.5q0 16 2.5 34t5 30.5 9 33 10 29.5 12.5 33 11 30q60 164 216.5 320.5t320.5 216.5q6 2 30 11t33 12.5 29.5 10 33 9 30.5 5 34 2.5q57 0 130.5-34t94.5-80q22-53 22-101zM1536 416v960q0 119-84.5 203.5t-203.5 84.5h-960q-119 0-203.5-84.5t-84.5-203.5v-960q0-119 84.5-203.5t203.5-84.5h960q119 0 203.5 84.5t84.5 203.5z" } }] }; exports.phoneSquare = phoneSquare;
package com.chankin.ssms.core.entity; /* * * 用户自定义异常 * */ public class UserException extends RuntimeException { private long date = System.currentTimeMillis(); public long getDate() { return date; } }
#! /bin/bash if [ -n "$1" ] && ! id "$1" >/dev/null 2>&1; then useradd -g users -G sudo -d /home/users -s /bin/zsh -g users -G sudo $1 && echo "ADDED $1" usermod -aG sudo "$1" echo "$1 ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers fi
import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { Observable, of } from "rxjs"; import { catchError, tap, map } from "rxjs/operators"; import { LoggerService } from "./logger.service"; declare var userContext: any; export class BaseService { userContext; ApiUrlBase; constructor( private httpClient: HttpClient, private loggerService: LoggerService ) { this.userContext = userContext; this.ApiUrlBase = userContext.ApiUrlBase; } postData(url: string, data: any, headers: any): Observable<any> { this.addUserContextHeaders(headers); const httpOptions = { headers }; return this.httpClient.post<any>(this.URL(url), data, httpOptions).pipe( tap((response: any) => { this.loggerService.info("baseService postData get called."), this.ServerErrorHandler(url, response); }), catchError( this.handleError<any>("base service post", "error", this.URL(url)) ) ); } getData(url: string, headers: any): Observable<any> { this.addUserContextHeaders(headers); const httpOptions = { headers }; return this.httpClient.get(this.URL(url), httpOptions).pipe( tap((response: any) => { this.loggerService.info("baseService get data returned."), this.ServerErrorHandler(url, response); }), catchError( this.handleError<any>("base service get", "error", this.URL(url)) ) ); } deleteData(url: string, headers: any): Observable<any> { this.addUserContextHeaders(headers); const httpOptions = { headers }; return this.httpClient.delete<any>(this.URL(url), httpOptions).pipe( tap((_) => this.loggerService.info("baseService deleted the data")), catchError( this.handleError<any>("base service delete", "error", this.URL(url)) ) ); } handleError<T>(operation = "operation", result: T, url: string) { return (error: any): Observable<T> => { // this.imNotificationService.serverErrorNotification("error", "DM_IM_NOTIFICATION_SERVER_ERROR_MESSAGE", "OK", "OK", this.afterServerError, true, url); this.loggerService.error(error); return of(result); }; } ServerErrorHandler(url, response) { if (response && !response.isSuccess) { let errorMessage = response.errorMessage || response.ErrorMessage || ""; // this.imNotificationService.serverErrorNotificationWithErrorMsg("error", "DM_IM_NOTIFICATION_SERVER_ERROR_MESSAGE", "OK", "OK", this.afterServerError, true, url, errorMessage); } } afterServerError() {} addUserContextHeaders(headers) { Object.assign(headers, { "Ocp-Apim-Subscription-Key": userContext.OcpApimSubscriptionKey, RegionID: "8", // "Content-Type": "application/json", UserExecutionContext: userContext.UserContext, }); } postExternalData(url: string, data: any, headers: any): Observable<any> { // this.addUserContextHeaders(headers); // const httpOptions = { headers }; return this.httpClient.post<any>(url, data, headers); } URL(url): string { return this.ApiUrlBase + url; } }
<filename>camel-core/src/main/java/org/apache/camel/spi/TransformerRegistry.java<gh_stars>0 /** * 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.camel.spi; import java.util.Map; import org.apache.camel.Endpoint; import org.apache.camel.StaticService; /** * Registry to cache transformers in memory. * <p/> * The registry contains two caches: * <ul> * <li>static - which keeps all the transformers in the cache for the entire lifecycle</li> * <li>dynamic - which keeps the transformers in a {@link org.apache.camel.util.LRUCache} and may evict transformers which hasn't been requested recently</li> * </ul> * The static cache stores all the transformers that are created as part of setting up and starting routes. * The static cache has no upper limit. * <p/> * The dynamic cache stores the transformers that are created and used ad-hoc, such as from custom Java code that creates new transformers etc. * The dynamic cache has an upper limit, that by default is 1000 entries. * * @param <K> transformer key */ public interface TransformerRegistry<K> extends Map<K, Transformer>, StaticService { /** * Number of transformers in the static registry. */ int staticSize(); /** * Number of transformers in the dynamic registry */ int dynamicSize(); /** * Maximum number of entries to store in the dynamic registry */ int getMaximumCacheSize(); /** * Purges the cache (removes transformers from the dynamic cache) */ void purge(); /** * Whether the given transformer is stored in the static cache * * @param scheme the scheme supported by this transformer * @return <tt>true</tt> if in static cache, <tt>false</tt> if not */ boolean isStatic(String scheme); /** * Whether the given transformer is stored in the static cache * * @param from 'from' data type * @param to 'to' data type * @return <tt>true</tt> if in static cache, <tt>false</tt> if not */ boolean isStatic(DataType from, DataType to); /** * Whether the given transformer is stored in the dynamic cache * * @param scheme the scheme supported by this transformer * @return <tt>true</tt> if in dynamic cache, <tt>false</tt> if not */ boolean isDynamic(String scheme); /** * Whether the given transformer is stored in the dynamic cache * * @param from 'from' data type * @param to 'to' data type * @return <tt>true</tt> if in dynamic cache, <tt>false</tt> if not */ boolean isDynamic(DataType from, DataType to); /** * Cleanup the cache (purging stale entries) */ void cleanUp(); }
from starlette.applications import Starlette from starlette.responses import HTMLResponse from starlette.templating import Jinja2Templates templates = Jinja2Templates(directory="templates") app = Starlette() @app.route('/') async def homepage(request): context = { "title": "Book List", "books": [ { "title": "The Alchemist", "author": "Paulo Coelho" }, { "title": "The Book of Joy", "author": "Dalai Lama, Desmond Tutu" }, { "title": "The Little Prince", "author": "Antoine de Saint-Exupéry" } ] } return templates.TemplateResponse("index.html", context) if __name__ == '__main__': uvicorn.run(app, host='0.0.0.0', port=8000) <!-- index.html --> <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ title }}</h1> <ul> {% for book in books %} <li>{{ book.title }} by {{ book.author }}</li> {% endfor %} </ul> </body> </html>
import React from 'react' import App from "./App"; import './App.css'; import Dashboard from "./componentss/Dashboard" import Wallets from "./componentss/Wallets" import Profile from './componentss/Profile'; import TotalIncome from './componentss/TotalIncome'; import LevelIncome from './componentss/LevelIncome'; import DirectIncome from './componentss/DirectIncome'; import Stakes from './componentss/Stakes'; import Tree from './componentss/Tree'; import Reward from './componentss/Reward'; import {Switch, Link, Route} from 'react-router-dom' class Front extends React.Component< any, any>{ constructor (props:any) { super(props) this.state={ } this.updateState = this.updateState.bind(this) } async updateState(state: any){ this.setState(state) console.log("logging state", this.state) } public render = () => { return( <Switch> <Route exact path="/"> <div> <App updateState={this.updateState}/> </div> </Route> <Route exact path="/wallets"> <Wallets state={this.state}/> </Route> <Route exact path="/Dashboard"> <Dashboard state={this.state}/> </Route> <Route exact path="/Profile"> <Profile state={this.state}/> </Route> <Route exact path="/Stakes"> <Stakes /> </Route> <Route exact path="/Tree"> <Tree /> </Route> <Route exact path="/TotalIncome"> <TotalIncome /> </Route> <Route exact path="/LevelIncome"> <LevelIncome /> </Route> <Route exact path="/DirectIncome"> <DirectIncome /> </Route> <Route exact path="/Reward"> <Reward /> </Route> </Switch> ) } } export default Front
#!/bin/sh #echo "Be sure to compile PageRank2 with appropriate NUM_NODE" CMDNAME=`basename $0` if [ $# -ne 2 ]; then echo "Usage: $CMDNAME run rwr input_id niteration" 1>&2 echo "input_id: 1: sample(num_node=16)" echo " 2: wiki-Vote(num_node=7115)" echo " 14: s14.edge(2.7MB)" echo " ..." echo " 22: s22.edge(991MB)" exit 1 fi niteration=$2 if [ $1 -eq 1 ]; then edge="sample" num_node=16 elif [ $1 -eq 2 ]; then edge="wiki-Vote.txt" num_node=7115 elif [ $1 -gt 13 -a $1 -lt 23 ]; then edge=s${1}.edge num_node=`echo 2^${1} | bc` fi query="sample.query" rwr_in="rwr_in" rwr_out="rwr_out" l1norm_out="l1norm_out" smult_out="smult_out" new_vector="new_vector" vector_difference="vector_difference" diff="difference" converged="check_convergence" touch $rwr_in touch $rwr_out touch $l1norm_out touch $smult_out touch $new_vector touch $vector_difference touch $diff touch $converged if [ ! -e $edge ]; then echo "${edge} doesn't exist, exit" exit fi l1norm_result=0 mixing_c=0.85 converge_threshold=0.05 echo "edge: $edge" echo "num_node=$num_node" # echo "initialize" echo "NormalizeVector" echo "L1norm" ./L1norm ${query} ${l1norm_out} echo "ScalarMult" l1norm_out=`cat ${l1norm_out} | cut -f 2` ./ScalarMult ${query} ${smult_out} ${l1norm_out} ${mixing_c} echo "Normalization completed" while [ ${i:=1} -le $niteration ] do echo "" echo "ITERATION : $i" echo "RWR" ./RWR $edge $rwr_in $rwr_out $num_node $mixing_c $i echo "SaxpyTextoutput" ./Saxpy ${rwr_out} ${smult_out} ${new_vector} 1.0 1 # output is vector echo "Saxpy" ./Saxpy ${new_vector} ${rwr_in} ${vector_difference} -1.0 0 # output is not vector echo "L1norm" ./L1norm ${vector_difference} ${diff} $converge_threshold if [ `cat ${converged}` ]; then echo "CONVERGED" echo "total iteration : ${i}" exit fi mv $new_vector $rwr_in i=`expr $i + 1` done
// Copyright (C) 2019-2021, <NAME>. // @author xiongfa.li // @version V1.0 // Description: package authentication type Manager interface { Authenticate(auth Authentication) (Authentication, error) }
<gh_stars>0 class CancelInterview attr_reader :auth, :application_choice, :interview, :cancellation_reason def initialize( actor:, application_choice:, interview:, cancellation_reason: ) @auth = ProviderAuthorisation.new(actor: actor) @application_choice = application_choice @interview = interview @cancellation_reason = cancellation_reason end def save! auth.assert_can_make_decisions!( application_choice: application_choice, course_option_id: application_choice.offered_option.id, ) if ApplicationStateChange.new(application_choice).can_cancel_interview? ActiveRecord::Base.transaction do interview.update!(cancellation_reason: cancellation_reason, cancelled_at: Time.zone.now) return if @application_choice.interviews.kept.any? ApplicationStateChange.new(application_choice).cancel_interview! end CandidateMailer.interview_cancelled(application_choice, interview, cancellation_reason).deliver_later else raise "Interview cannot be cancelled when the application_choice is in #{application_choice.status} state" end end end
const initState = { userData: [], blogPost: [], geoLocation: { lat: "", lng: "", location: "" }, }; function Reducer(state = initState, action) { switch (action.type) { case "LOAD_DATA": return { ...state, userData: action.payload }; case "GET_POST": return { ...state, post: action.payload }; case "GET_POSTS": return { ...state, blogPost: action.payload }; case "SET_LATLNG": return { ...state, geoLocation: { ...state.geoLocation, ...action.payload, }, }; default: return state; } } export default Reducer;
validate_templates ================== :synopsis: Checks templates on syntax or compile errors. Options ======= verbosity ~~~~~~~~~ A higher verbosity level will print out all the files that are processed not just the onces that contain errors. break ~~~~~ Do not continue scanning other templates after the first failure. includes ~~~~~~~~ Use -i (can be used multiple times) to add directories to the TEMPLATE_DIRS. Settings ======== VALIDATE_TEMPLATES_EXTRA_TEMPLATE_DIRS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You can use `VALIDATE_TEMPLATES_EXTRA_TEMPLATE_DIRS` to include a number of template dirs per default directly from the settings file. This can be usefull for situations where TEMPLATE_DIRS is dynamically generated or switched in middleware or you have other template dirs for external applications like celery you want to check as well. How === ./manage.py validate_templates
package cn.stylefeng.roses.kernel.system.api.exception.enums.theme; import cn.stylefeng.roses.kernel.rule.constants.RuleConstants; import cn.stylefeng.roses.kernel.rule.exception.AbstractExceptionEnum; import cn.stylefeng.roses.kernel.system.api.constants.SystemConstants; import lombok.Getter; /** * 系统主题模板属性异常类 * * @author xixiaowei * @date 2021/12/23 17:01 */ @Getter public enum SysThemeTemplateFieldExceptionEnum implements AbstractExceptionEnum { /** * 系统主题模板属性不存在 */ FIELD_NOT_EXIST(RuleConstants.USER_OPERATION_ERROR_TYPE_CODE + SystemConstants.SYSTEM_EXCEPTION_STEP_CODE + "101", "系统主题模板属性不存在"), /** * 系统主题模板属性被使用 */ FIELD_IS_USED(RuleConstants.USER_OPERATION_ERROR_TYPE_CODE + SystemConstants.SYSTEM_EXCEPTION_STEP_CODE + "102", "系统主题模板属性正在被使用,不允许操作"); /** * 错误编码 */ private final String errorCode; /** * 提示用户信息 */ private final String userTip; SysThemeTemplateFieldExceptionEnum(String errorCode, String userTip) { this.errorCode = errorCode; this.userTip = userTip; } }
/* * 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.sdb.core; import org.apache.jena.sdb.SDB ; import org.apache.jena.sdb.SDBException ; import org.apache.jena.sparql.util.Symbol ; public class SDBConstants { // Not "Integer.MIN_VALUE" which is meaningful to MySQL. public static final int jdbcFetchSizeOff = -1 ; public static Symbol allocSymbol(String shortName) { if ( shortName.matches("^[a-zA-Z]*:") ) throw new SDBException("Symbol short name begins URI scheme") ; return Symbol.create(SDB.symbolSpace+shortName) ; } }
#!/bin/bash # cd basic; ./run_all.sh; cd .. cd advanced; ./run_all.sh; cd .. cd simulations; ./run_all.sh; cd .. cd volumetric; ./run_all.sh; cd .. cd pyplot; ./run_all.sh; cd .. cd other; ./run_all.sh; cd .. # other/dolfin if python -c 'import pkgutil; exit(not pkgutil.find_loader("dolfin"))'; then cd other/dolfin; ./run_all.sh; cd ../.. else echo 'dolfin not found, skip.' fi # other/trimesh if python -c 'import pkgutil; exit(not pkgutil.find_loader("trimesh"))'; then cd other/trimesh; ./run_all.sh; cd ../.. else echo 'trimesh not found, skip.' fi ################################# command line tests echo '---------------------------- command line tests' echo vedo /home/musy/Dropbox/Public/vtk_work/vedo_data/2*.vtk vedo /home/musy/Dropbox/Public/vtk_work/vedo_data/2*.vtk echo '----------------------------' echo vedo /home/musy/Dropbox/Public/vtk_work/vedo_data/2*.vtk vedo -ni -k glossy /home/musy/Dropbox/Public/vtk_work/vedo_data/2*.vtk echo '----------------------------' echo vedo /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.tif vedo /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.tif echo '----------------------------' echo vedo --lego --cmap afmhot_r /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.tif vedo --lego --cmap afmhot_r /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.tif echo '----------------------------' echo vedo -g -c blue /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.slc vedo -g -c blue /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.slc echo '----------------------------' echo vedo --slicer /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.tif vedo --slicer /home/musy/Dropbox/Public/vtk_work/vedo_data/embryo.tif echo '----------------------------' echo vedo -s "/home/musy/Dropbox/Public/vtk_work/vedo_data/2??.vtk" vedo -s /home/musy/Dropbox/Public/vtk_work/vedo_data/2??.vtk echo '---------------------------- should open a GUI' echo vedo vedo ##################################### not run/ignored: # python basic/closewindow.py # python basic/lights.py # python basic/multiblocks.py # python other/animation1.py # python other/animation2.py # python other/makeVideo.py # python other/spherical_harmonics2.py
python setup.py sdist pip install twine -q -q twine upload dist/* -u $user -p $passw rm -rf build/ dist/ *.egg-info/
python3 xmTool/demo_CAM2.py 4349 1 python3 xmTool/demo_CAM2.py 3175 2 python3 xmTool/demo_CAM2.py 1407 3 python3 xmTool/demo_CAM2.py 5630 1 python3 xmTool/demo_CAM2.py 0722 12 python3 xmTool/demo_CAM2.py 1584 4 python3 xmTool/demo_CAM2.py 4349 1 python3 xmTool/demo_CAM2.py 0859 2 python3 xmTool/demo_CAM2.py 1295 9
def translate_account_group_ids(role): translated_ids = [] for id in role['accountGroupIds']: if isinstance(id, int): translated_ids.append(roman_numeral(id)) else: translated_ids.append(id.upper()[::-1]) return translated_ids def roman_numeral(n): roman_numerals = { 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M' } result = '' for value in sorted(roman_numerals.keys(), reverse=True): while n >= value: result += roman_numerals[value] n -= value return result
import csv import statistics class CSVProcessor: def __init__(self): self.data = [] def load_data(self, file_path): with open(file_path, 'r') as file: csv_reader = csv.reader(file) self.data = [row for row in csv_reader] def calculate_statistics(self, column): column_data = [int(row[column]) for row in self.data[1:]] # Extract the specified column data mean = statistics.mean(column_data) median = statistics.median(column_data) stdev = statistics.stdev(column_data) return mean, median, stdev def filter_data(self, column, value): filtered_data = [row for row in self.data if row[column] == value] return filtered_data
function ssh_ping() { local host="${1}" if [ ! -z "${2+x}" ]; then local user="${2}" else local user=`whoami` fi local result=`ssh_exe "${host}" "echo \"hello\"" "${user}" 2>/dev/null | { grep 'hello' || test $? = 1; }` if [ -z "${result}" ]; then echo 'false' else echo 'true' fi } function ssh_exe() { local host="${1}" local cmd="${2}" if [ ! -z "${3+x}" ]; then local user="${3}" else local user=`whoami` fi #ssh -o "UserKnownHostsFile=/dev/null" -o "StrictHostKeyChecking=no" -o "BatchMode=yes" "${host}" ${cmd} </dev/null ssh -o "StrictHostKeyChecking=no" -o "BatchMode=yes" "${user}@${host}" ${cmd} </dev/null }
<reponame>orthopteroid/psychic-sniffle<gh_stars>1-10 // copyright 2016 <NAME> (<EMAIL>) // MIT license #include <iostream> #include <cstring> #include <cstring> #include "sniffle.h" #include "cpuinfo.h" using namespace sniffle; ////////////////////////////// template<typename Rep, uint Dimension, uint Population> struct Schwefel { typedef Rep StateType[Dimension]; static float_t Eval(const StateType& state) { // schwefel per https://www.sfu.ca/~ssurjano/Code/schwefm.html // global min for D=20 is (420.9687, ..., 420.9687) and can be found using best methods in 40K evals float_t sum = 0.f; for(int d=0; d<Dimension; d++) { float_t x = (float_t)1000.f * (float_t)state[d] / (float_t)((Rep)~0) - (float_t)500.f; sum += x * sin(sqrt(abs(x))); } return sum - 418.9829 * Dimension; } static void Solve(int solns) { printf("Minimze Schwefel<%d> : https://www.sfu.ca/~ssurjano/schwef.html\n", Dimension); float_t f[Population]; Maximizer<StateType, Population, ByteAnalyser> solver; float_t best = 0.f; uint i = 0; uint t = 0; solver.reset(); while( t < 1e6 ) { #pragma omp for for( int p=0; p<Population; p++ ) f[p] = Eval( solver.GetStateArr()[p] ); if( t == 10000 || best != f[0] ) { float ff = solver.stateAnalyser.calcSmallestChannelDifference(); best = f[0]; if( t == 10000 || ff >= .99f ) { printf("%u, %8.4f, %8.4f, [", t, best, ff); for( int d=0; d<Dimension; d++ ) { StateType &state = *solver.GetStateArr(); double_t val = (float_t) 1000. * (float_t) state[d] / (float_t) ((Rep) ~0) - (float_t) 500.; printf("%8.8f%s ", val, d < Dimension - 1 ? "," : "]\n" ); } fflush(stdout); t = 0; solver.reset(); if( ++i == solns ) break; continue; } } solver.crank(f); t++; } } }; int main() { srand(int(time(NULL))); #if defined(NDEBUG) { int cores = EnumCores(); printf("OpenMP using %d threads\n", cores); omp_set_num_threads(cores); } #endif Schwefel<uint16_t, 20, 400>::Solve(10); return 0; }
<reponame>rainu/mqtt-logger package main import ( "github.com/alexflint/go-arg" "go.uber.org/zap" "os" "regexp" "time" ) type Config struct { MqttBrokerAddress string `arg:"--broker,required,env:MQTT_BROKER_ADDRESS,help:The mqtt broker address."` MqttTopics []string `arg:"--topic,separate,env:MQTT_TOPICS,help:List of the mqtt topics to subscribe to."` MqttRawTopicBlacklist []string `arg:"--blacklist,env:MQTT_TOPIC_BLACKLIST,help:List of regular expression."` MqttUsername string `arg:"--user,env:MQTT_USERNAME,help:The mqtt username."` MqttPassword string `arg:"--password,env:MQTT_PASSWORD,help:The mqtt password."` MqttTimeout time.Duration `default:"1m" arg:"--timeout,env:MQTT_TIMEOUT,help:The timeout for the mqtt connection."` MqttCaCert string `arg:"--ca-cert,env:MQTT_CA_CERT,help:The path of the CA-Cert file for secure mqtt connection."` MqttTopicBlacklist []*regexp.Regexp `arg:"-"` } func NewConfig() *Config { c := &Config{} arg.MustParse(c) if len(c.MqttTopics) == 0 { c.MqttTopics = []string{"#"} } for _, regExp := range c.MqttRawTopicBlacklist { compiled, err := regexp.Compile(regExp) if err != nil { zap.L().With( zap.Error(err), zap.String("expression", regExp), ).Error("Error while compoiling blacklist regular expression") os.Exit(1) } c.MqttTopicBlacklist = append(c.MqttTopicBlacklist, compiled) } return c } func (s *Config) Log() { zap.L().With( zap.Strings("MQTT_TOPICS", s.MqttTopics), zap.Strings("MQTT_TOPIC_BLACKLIST", s.MqttRawTopicBlacklist), zap.String("MQTT_BROKER_ADDRESS", s.MqttBrokerAddress), zap.String("MQTT_USERNAME", s.MqttUsername), zap.String("MQTT_PASSWORD", <PASSWORD>*"), zap.Duration("MQTT_TIMEOUT", s.MqttTimeout), zap.String("MQTT_CA_CERT", s.MqttCaCert), ).Info("Using configuration") }
<filename>types/helpers.go<gh_stars>0 package types import ( "io" "github.com/hexbee-net/errors" "github.com/hexbee-net/parquet/encoding" ) func encodeValue(w io.Writer, enc ValuesEncoder, all []interface{}) error { if err := enc.Init(w); err != nil { return err } if err := enc.EncodeValues(all); err != nil { return err } return enc.Close() } func decodeInt32(d encoding.Decoder, data []int32) error { for i := range data { u, err := d.Next() if err != nil { return err } data[i] = u } return nil } func writeFull(w io.Writer, buf []byte) error { if len(buf) == 0 { return nil } cnt, err := w.Write(buf) if err != nil { return err } if cnt != len(buf) { return errors.WithFields( errors.New("invalid number of bytes written"), errors.Fields{ "expected": cnt, "actual": len(buf), }) } return nil } // check the b2 into b1 to find the max prefix len. func prefix(b1, b2 []byte) int { l := len(b1) if l2 := len(b2); l > l2 { l = l2 } for i := 0; i < l; i++ { if b1[i] != b2[i] { return i } } return l }
<gh_stars>0 package cn.finalteam.rxgalleryfinalprovider.imageloader; import android.content.Context; import android.graphics.drawable.Drawable; import com.squareup.picasso.Picasso; import java.io.File; import cn.finalteam.rxgalleryfinalprovider.ui.widget.FixImageView; /** * Desction: * Author:pengjianbo * Date:16/6/17 下午1:23 */ public class PicassoImageLoader implements AbsImageLoader { @Override public void displayImage(Object context, String path, FixImageView imageView, Drawable defaultDrawable, int width, int height) { Context ctx = (Context) context; Picasso.with(ctx) .load(new File(path)) .placeholder(defaultDrawable) .error(defaultDrawable) .resize(width, height) .tag(context) .into(imageView); } }
import { assert } from '@0x/assert'; import { addressUtils } from '@0x/utils'; import { JSONRPCRequestPayload, JSONRPCResponsePayload } from 'ethereum-types'; import * as _ from 'lodash'; import { Callback, ErrorCallback, PartialTxParams, WalletSubproviderErrors } from '../types'; import { Subprovider } from './subprovider'; export abstract class BaseWalletSubprovider extends Subprovider { protected static _validateTxParams(txParams: PartialTxParams): void { if (txParams.to !== undefined) { assert.isETHAddressHex('to', txParams.to); } assert.isHexString('nonce', txParams.nonce); } private static _validateSender(sender: string): void { if (sender === undefined || !addressUtils.isAddress(sender)) { throw new Error(WalletSubproviderErrors.SenderInvalidOrNotSupplied); } } public abstract getAccountsAsync(): Promise<string[]>; public abstract signTransactionAsync(txParams: PartialTxParams): Promise<string>; public abstract signPersonalMessageAsync(data: string, address: string): Promise<string>; public abstract signTypedDataAsync(address: string, typedData: any): Promise<string>; /** * This method conforms to the web3-provider-engine interface. * It is called internally by the ProviderEngine when it is this subproviders * turn to handle a JSON RPC request. * @param payload JSON RPC payload * @param next Callback to call if this subprovider decides not to handle the request * @param end Callback to call if subprovider handled the request and wants to pass back the request. */ // tslint:disable-next-line:async-suffix public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback): Promise<void> { let accounts; let txParams; let address; let typedData; switch (payload.method) { case 'eth_coinbase': try { accounts = await this.getAccountsAsync(); end(null, accounts[0]); } catch (err) { end(err); } return; case 'eth_accounts': try { accounts = await this.getAccountsAsync(); end(null, accounts); } catch (err) { end(err); } return; case 'eth_sendTransaction': txParams = payload.params[0]; try { BaseWalletSubprovider._validateSender(txParams.from); const filledParams = await this._populateMissingTxParamsAsync(txParams); const signedTx = await this.signTransactionAsync(filledParams); const response = await this._emitSendTransactionAsync(signedTx); end(null, response.result); } catch (err) { end(err); } return; case 'eth_signTransaction': txParams = payload.params[0]; try { const filledParams = await this._populateMissingTxParamsAsync(txParams); const signedTx = await this.signTransactionAsync(filledParams); const result = { raw: signedTx, tx: txParams, }; end(null, result); } catch (err) { end(err); } return; case 'eth_sign': case 'personal_sign': const data = payload.method === 'eth_sign' ? payload.params[1] : payload.params[0]; address = payload.method === 'eth_sign' ? payload.params[0] : payload.params[1]; try { const ecSignatureHex = await this.signPersonalMessageAsync(data, address); end(null, ecSignatureHex); } catch (err) { end(err); } return; case 'eth_signTypedData': [address, typedData] = payload.params; try { const signature = await this.signTypedDataAsync(address, typedData); end(null, signature); } catch (err) { end(err); } return; default: next(); return; } } private async _emitSendTransactionAsync(signedTx: string): Promise<JSONRPCResponsePayload> { const payload = { method: 'eth_sendRawTransaction', params: [signedTx], }; const result = await this.emitPayloadAsync(payload); return result; } private async _populateMissingTxParamsAsync(partialTxParams: PartialTxParams): Promise<PartialTxParams> { let txParams = partialTxParams; if (partialTxParams.gasPrice === undefined) { const gasPriceResult = await this.emitPayloadAsync({ method: 'eth_gasPrice', params: [], }); const gasPrice = gasPriceResult.result.toString(); txParams = { ...txParams, gasPrice }; } if (partialTxParams.nonce === undefined) { const nonceResult = await this.emitPayloadAsync({ method: 'eth_getTransactionCount', params: [partialTxParams.from, 'pending'], }); const nonce = nonceResult.result; txParams = { ...txParams, nonce }; } if (partialTxParams.gas === undefined) { const gasResult = await this.emitPayloadAsync({ method: 'eth_estimateGas', params: [partialTxParams], }); const gas = gasResult.result.toString(); txParams = { ...txParams, gas }; } return txParams; } }
#!/bin/bash ###################################################################### # Custom entrypoint that activate conda before running spleeter. # # @author Félix Voituret <fvoituret@deezer.com> # @version 1.0.0 ###################################################################### # shellcheck disable=1091 . "/opt/conda/etc/profile.d/conda.sh" conda activate base spleeter "$@"
//##################################################################### // Copyright 2010, <NAME>. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Matrices/SPARSE_MATRIX_FLAT_NXN.h> #include <PhysBAM_Tools/Parallel_Computation/INT_ITERATOR_THREADED.h> #include <PhysBAM_Tools/Parallel_Computation/PCG_SPARSE_THREADED.h> #include <PhysBAM_Tools/Vectors/SPARSE_VECTOR_ND.h> using namespace PhysBAM; //##################################################################### // Function Parallel_Solve //##################################################################### template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,const ARRAY<ARRAY<INTERVAL<int> > >& all_ghost_indices,SPARSE_MATRIX_FLAT_NXN<T>& A,VECTOR_ND<T>& x,VECTOR_ND<T>& b,const T tolerance) { Init_Barriers(); RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); assert(tid==domain_index(interior_domain.max_corner)); const INTERVAL<int>& interior_indices=all_interior_indices(tid); const ARRAY<INTERVAL<int> >& ghost_indices=all_ghost_indices(tid); int global_n=A.n,interior_n=interior_indices.Size()+1; T global_tolerance=tolerance; int desired_iterations=global_n;if(enforce_compatibility) desired_iterations--;if(maximum_iterations) desired_iterations=min(desired_iterations,maximum_iterations); VECTOR_ND<T> z_interior(interior_n,false); #ifdef USE_PTHREADS pthread_mutex_lock(&sum_lock); #endif temp.Resize(global_n);p.Resize(global_n); #ifdef USE_PTHREADS pthread_mutex_unlock(&sum_lock); #endif // build interior views of x,b,p,z,temp VECTOR_ND<T> x_interior,b_interior,p_interior,temp_interior; x_interior.Set_Subvector_View(x,interior_indices); b_interior.Set_Subvector_View(b,interior_indices); p_interior.Set_Subvector_View(p,interior_indices); temp_interior.Set_Subvector_View(temp,interior_indices); // adjust x for the null space if(enforce_compatibility && remove_null_space_solution_component) x_interior-=(T)(Global_Sum((T)x_interior.Sum_Double_Precision(),tid)/global_n); // find initial residual, r=b-Ax - reusing b for the residual #ifdef USE_PTHREADS pthread_barrier_wait(&barr); #endif A.Times(interior_indices,ghost_indices,x,temp); b_interior-=temp_interior; if(enforce_compatibility) b_interior-=(T)(Global_Sum((T)b_interior.Sum_Double_Precision(),tid)/global_n); if(Global_Max(b_interior.Max_Abs())<=global_tolerance){ #ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT if(show_results) LOG::filecout("NO ITERATIONS NEEDED\n"); #endif return;} SPARSE_MATRIX_FLAT_NXN<T>* C=0; // find an incomplete cholesky preconditioner - actually an LU that saves square roots, and an inverted diagonal to save on divides if(incomplete_cholesky){ C=A.Create_Submatrix(interior_indices); C->In_Place_Incomplete_Cholesky_Factorization(modified_incomplete_cholesky,modified_incomplete_cholesky_coefficient, preconditioner_zero_tolerance,preconditioner_zero_replacement);} double rho=0,rho_old=0; for(int iteration=1;;iteration++){ if(incomplete_cholesky){ // solve Mz=r C->Solve_Forward_Substitution(b_interior,temp_interior,true); // diagonal should be treated as the identity C->Solve_Backward_Substitution(temp_interior,z_interior,false,true);} // diagonal is inverted to save on divides else z_interior=b_interior; // set z=r when there is no preconditioner // for Neumann boundary conditions only, make sure z sums to zero if(enforce_compatibility) z_interior-=(T)(Global_Sum((T)z_interior.Sum_Double_Precision(),tid)/global_n); // update search direction rho_old=rho;rho=Global_Sum((T)VECTOR_ND<T>::Dot_Product_Double_Precision(z_interior,b_interior),tid); T beta=0;if(iteration==1) p_interior=z_interior;else{beta=(T)(rho/rho_old);for(int i=1;i<=interior_n;i++) p_interior(i)=z_interior(i)+beta*p_interior(i);} // when iteration=1, beta=0 // update solution and residual #ifdef USE_PTHREADS pthread_barrier_wait(&barr); #endif A.Times(interior_indices,ghost_indices,p,temp); T alpha=(T)(rho/Global_Sum((T)VECTOR_ND<T>::Dot_Product_Double_Precision(p_interior,temp_interior),tid)); for(int i=1;i<=interior_n;i++){x_interior(i)+=alpha*p_interior(i);b_interior(i)-=alpha*temp_interior(i);} // remove null space component of b before computing residual norm because we might have converged up to the null space but have some null space component left due to roundoff if(enforce_compatibility) b_interior-=(T)(Global_Sum((T)b_interior.Sum_Double_Precision(),tid)/global_n); #ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT T residual=Global_Max(b_interior.Max_Abs()); // check for convergence std::stringstream ss; if(show_residual) ss<<residual<<std::endl; if(residual<=global_tolerance){if(show_results) ss<<"NUMBER OF ITERATIONS = "<<iteration<<std::endl;break;} if(iteration==desired_iterations){if(show_results) ss<<"DID NOT CONVERGE IN "<<iteration<<" ITERATIONS"<<std::endl;break;} LOG::filecout(ss.str()); #endif } delete C; } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_In_Parts(SPARSE_MATRIX_FLAT_NXN<T>& A,VECTOR_ND<T>& x,VECTOR_ND<T>& b,const T tolerance) { int global_n=A.n; T global_tolerance=tolerance; int desired_iterations=global_n;if(enforce_compatibility) desired_iterations--;if(maximum_iterations) desired_iterations=min(desired_iterations,maximum_iterations); VECTOR_ND<T> z(global_n,false); temp.Resize(global_n);p.Resize(global_n); INT_ITERATOR_THREADED_ALPHA<PCG_SPARSE_THREADED<TV> > threaded_iterator(1,global_n,&thread_queue); int num_intervals=threaded_iterator.intervals.m; ARRAY<T> local_sum(num_intervals); // adjust x for the null space T sum=0; if(enforce_compatibility && remove_null_space_solution_component){ threaded_iterator.template Run<VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Sum,x,local_sum); for(int i=1;i<=num_intervals;i++) sum+=local_sum(i);} // find initial residual, r=b-Ax - reusing b for the residual threaded_iterator.template Run<SPARSE_MATRIX_FLAT_NXN<T>&,VECTOR_ND<T>&,VECTOR_ND<T>&,T>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Part_One,A,x,b,sum/global_n); if(enforce_compatibility){sum=0; threaded_iterator.template Run<VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Sum,b,local_sum); for(int i=1;i<=num_intervals;i++) sum+=local_sum(i); threaded_iterator.template Run<VECTOR_ND<T>&,T>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Subtract,b,sum/global_n);} threaded_iterator.template Run<VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Max,b,local_sum); T max_val=0;for(int i=1;i<=num_intervals;i++) max_val=max(max_val,local_sum(i)); if(max_val<=global_tolerance){ #ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT if(show_results) LOG::filecout("NO ITERATIONS NEEDED\n"); #endif return;} // find an incomplete cholesky preconditioner - actually an LU that saves square roots, and an inverted diagonal to save on divides SPARSE_MATRIX_FLAT_NXN<T>* C=0; if(incomplete_cholesky){ C=new SPARSE_MATRIX_FLAT_NXN<T>(A); C->In_Place_Incomplete_Cholesky_Factorization(modified_incomplete_cholesky,modified_incomplete_cholesky_coefficient, preconditioner_zero_tolerance,preconditioner_zero_replacement);} double rho=0,rho_old=0; for(int iteration=1;;iteration++){ if(incomplete_cholesky){ // solve Mz=r C->Solve_Forward_Substitution(b,temp,true); // diagonal should be treated as the identity C->Solve_Backward_Substitution(temp,z,false,true);} // diagonal is inverted to save on divides else z=b; // set z=r when there is no preconditioner // for Neumann boundary conditions only, make sure z sums to zero if(enforce_compatibility){T sum=0; threaded_iterator.template Run<VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Sum,z,local_sum); for(int i=1;i<=num_intervals;i++) sum+=local_sum(i); threaded_iterator.template Run<VECTOR_ND<T>&,T>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Subtract,z,sum/global_n);} // update search direction threaded_iterator.template Run<VECTOR_ND<T>&,VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Dot,z,b,local_sum); rho_old=rho;rho=0;for(int i=1;i<=num_intervals;i++) rho+=local_sum(i); threaded_iterator.template Run<VECTOR_ND<T>&,T,T,int>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Part_Two,z,(T)rho,(T)rho_old,iteration); // update solution and residual threaded_iterator.template Run<SPARSE_MATRIX_FLAT_NXN<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Part_Three,A); threaded_iterator.template Run<VECTOR_ND<T>&,VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Dot,p,temp,local_sum); T sum=0;for(int i=1;i<=num_intervals;i++) sum+=local_sum(i); threaded_iterator.template Run<VECTOR_ND<T>&,VECTOR_ND<T>&,T>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Part_Four,x,b,(T)rho/sum); // remove null space component of b before computing residual norm because we might have converged up to the null space but have some null space component left due to roundoff if(enforce_compatibility){T sum=0; threaded_iterator.template Run<VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Sum,b,local_sum); for(int i=1;i<=num_intervals;i++) sum+=local_sum(i); threaded_iterator.template Run<VECTOR_ND<T>&,T>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Subtract,b,sum/global_n);} #ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT threaded_iterator.template Run<VECTOR_ND<T>&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Threaded_Max,b,local_sum); T residual=0;for(int i=1;i<=num_intervals;i++) residual=max(residual,local_sum(i)); // check for convergence std::stringstream ss; if(show_residual) ss<<residual<<std::endl; if(residual<=global_tolerance){if(show_results) ss<<"NUMBER OF ITERATIONS = "<<iteration<<std::endl;break;} if(iteration==desired_iterations){if(show_results) ss<<"DID NOT CONVERGE IN "<<iteration<<" ITERATIONS"<<std::endl;break;} LOG::filecout(ss.str()); #endif } delete C; } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_In_Parts(DOMAIN_ITERATOR_THREADED_ALPHA<PCG_SPARSE_THREADED<TV>,TV>& threaded_iterator,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,const ARRAY<ARRAY<INTERVAL<int> > >& all_ghost_indices,SPARSE_MATRIX_FLAT_NXN<T>& A,VECTOR_ND<T>& x,VECTOR_ND<T>& b,const T tolerance) { int global_n=A.n,num_domains=threaded_iterator.domains.m; T global_tolerance=tolerance; int desired_iterations=global_n;if(enforce_compatibility) desired_iterations--;if(maximum_iterations) desired_iterations=min(desired_iterations,maximum_iterations); ARRAY<VECTOR_ND<T> > z_interior(num_domains),x_interior(num_domains),b_interior(num_domains),p_interior(num_domains),temp_interior(num_domains); temp.Resize(global_n);p.Resize(global_n); ARRAY<T> local_sum(num_domains); // build interior views of x,b,p,z,temp threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,VECTOR_ND<T>&,VECTOR_ND<T>&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Part_One,domain_index,all_interior_indices,x,b,z_interior,x_interior,b_interior,p_interior,temp_interior); // adjust x for the null space if(enforce_compatibility && remove_null_space_solution_component){T sum=0; threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Sum,domain_index,all_interior_indices,x_interior,local_sum); for(int i=1;i<=num_domains;i++) sum+=local_sum(i); //threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,T>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Distribute,domain_index,all_interior_indices,x_interior,sum/global_n);} for(int i=1;i<=num_domains;i++) x_interior(i)-=sum/global_n;} // find initial residual, r=b-Ax - reusing b for the residual threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,const ARRAY<ARRAY<INTERVAL<int> > >&,SPARSE_MATRIX_FLAT_NXN<T>&,VECTOR_ND<T>&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Part_Two,domain_index,all_interior_indices,all_ghost_indices,A,x,b_interior,temp_interior); if(enforce_compatibility){T sum=0; threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Sum,domain_index,all_interior_indices,b_interior,local_sum); for(int i=1;i<=num_domains;i++) sum+=local_sum(i); //threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,T>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Distribute,domain_index,all_interior_indices,b_interior,sum/global_n);} for(int i=1;i<=num_domains;i++) b_interior(i)-=sum/global_n;} threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Max,domain_index,all_interior_indices,b_interior,local_sum); T max_val=0;for(int i=1;i<=num_domains;i++) max_val=max(max_val,local_sum(i)); if(max_val<=global_tolerance){ #ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT if(show_results) LOG::filecout("NO ITERATIONS NEEDED\n"); #endif return;} // find an incomplete cholesky preconditioner - actually an LU that saves square roots, and an inverted diagonal to save on divides ARRAY<SPARSE_MATRIX_FLAT_NXN<T>*> C(num_domains); threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,SPARSE_MATRIX_FLAT_NXN<T>&,ARRAY<SPARSE_MATRIX_FLAT_NXN<T>*>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Part_Three,domain_index,all_interior_indices,A,C); double rho=0,rho_old=0; for(int iteration=1;;iteration++){ threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<SPARSE_MATRIX_FLAT_NXN<T>*>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Part_Four,domain_index,all_interior_indices,z_interior,b_interior,temp_interior,C); // for Neumann boundary conditions only, make sure z sums to zero if(enforce_compatibility){T sum=0; threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Sum,domain_index,all_interior_indices,z_interior,local_sum); for(int i=1;i<=num_domains;i++) sum+=local_sum(i); //threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,T>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Distribute,domain_index,all_interior_indices,z_interior,sum/global_n);} for(int i=1;i<=num_domains;i++) z_interior(i)-=sum/global_n;} // update search direction threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Dot,domain_index,all_interior_indices,z_interior,b_interior,local_sum); rho_old=rho;rho=0;for(int i=1;i<=num_domains;i++) rho+=local_sum(i); threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,T,T,int>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Part_Five,domain_index,all_interior_indices,z_interior,p_interior,(T)rho,(T)rho_old,iteration); // update solution and residual threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,const ARRAY<ARRAY<INTERVAL<int> > >&,const SPARSE_MATRIX_FLAT_NXN<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Part_Six,domain_index,all_interior_indices,all_ghost_indices,A); threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Dot,domain_index,all_interior_indices,p_interior,temp_interior,local_sum); T sum=0;for(int i=1;i<=num_domains;i++) sum+=local_sum(i); threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<VECTOR_ND<T> >&,T>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Part_Seven,domain_index,all_interior_indices,x_interior,b_interior,p_interior,temp_interior,(T)rho/sum); // remove null space component of b before computing residual norm because we might have converged up to the null space but have some null space component left due to roundoff if(enforce_compatibility){T sum=0; threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Sum,domain_index,all_interior_indices,b_interior,local_sum); for(int i=1;i<=num_domains;i++) sum+=local_sum(i); //threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,T>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Distribute,domain_index,all_interior_indices,b_interior,sum/global_n);} for(int i=1;i<=num_domains;i++) b_interior(i)-=sum/global_n;} #ifndef COMPILE_WITHOUT_READ_WRITE_SUPPORT threaded_iterator.template Run<const ARRAY<int,TV_INT>&,const ARRAY<INTERVAL<int> >&,ARRAY<VECTOR_ND<T> >&,ARRAY<T>&>(*this,&PCG_SPARSE_THREADED<TV>::Solve_Max,domain_index,all_interior_indices,b_interior,local_sum); T residual=0;for(int i=1;i<=num_domains;i++) residual=max(residual,local_sum(i)); // check for convergence std::stringstream ss; if(show_residual) ss<<residual<<std::endl; if(residual<=global_tolerance){if(show_results) ss<<"NUMBER OF ITERATIONS = "<<iteration<<std::endl;break;} if(iteration==desired_iterations){if(show_results) ss<<"DID NOT CONVERGE IN "<<iteration<<" ITERATIONS"<<std::endl;break;} LOG::filecout(ss.str()); #endif } for(int i=1;i<=num_domains;i++) delete C(i); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Part_One(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,VECTOR_ND<T>& x,VECTOR_ND<T>& b,ARRAY<VECTOR_ND<T> >& z_interior,ARRAY<VECTOR_ND<T> >& x_interior,ARRAY<VECTOR_ND<T> >& b_interior,ARRAY<VECTOR_ND<T> >& p_interior,ARRAY<VECTOR_ND<T> >& temp_interior) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); assert(tid==domain_index(interior_domain.max_corner)); const INTERVAL<int>& interior_indices=all_interior_indices(tid); int interior_n=interior_indices.Size()+1; z_interior(tid).Resize(interior_n); x_interior(tid).Set_Subvector_View(x,interior_indices); b_interior(tid).Set_Subvector_View(b,interior_indices); p_interior(tid).Set_Subvector_View(p,interior_indices); temp_interior(tid).Set_Subvector_View(temp,interior_indices); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Part_Two(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,const ARRAY<ARRAY<INTERVAL<int> > >& all_ghost_indices,SPARSE_MATRIX_FLAT_NXN<T>& A,VECTOR_ND<T>& x,ARRAY<VECTOR_ND<T> >& b_interior,ARRAY<VECTOR_ND<T> >& temp_interior) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); const INTERVAL<int>& interior_indices=all_interior_indices(tid); const ARRAY<INTERVAL<int> >& ghost_indices=all_ghost_indices(tid); A.Times(interior_indices,ghost_indices,x,temp); b_interior(tid)-=temp_interior(tid); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Part_Three(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,SPARSE_MATRIX_FLAT_NXN<T>& A,ARRAY<SPARSE_MATRIX_FLAT_NXN<T>*>& C) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); const INTERVAL<int>& interior_indices=all_interior_indices(tid); C(tid)=0; if(incomplete_cholesky){ C(tid)=A.Create_Submatrix(interior_indices); C(tid)->In_Place_Incomplete_Cholesky_Factorization(modified_incomplete_cholesky,modified_incomplete_cholesky_coefficient, preconditioner_zero_tolerance,preconditioner_zero_replacement);} } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Part_Four(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,ARRAY<VECTOR_ND<T> >& z_interior,ARRAY<VECTOR_ND<T> >& b_interior,ARRAY<VECTOR_ND<T> >& temp_interior,ARRAY<SPARSE_MATRIX_FLAT_NXN<T>*>& C) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); if(incomplete_cholesky){ // solve Mz=r C(tid)->Solve_Forward_Substitution(b_interior(tid),temp_interior(tid),true); // diagonal should be treated as the identity C(tid)->Solve_Backward_Substitution(temp_interior(tid),z_interior(tid),false,true);} // diagonal is inverted to save on divides else z_interior(tid)=b_interior(tid); // set z=r when there is no preconditioner } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Part_Five(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,ARRAY<VECTOR_ND<T> >& z_interior,ARRAY<VECTOR_ND<T> >& p_interior,T rho,T rho_old,int iteration) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); const INTERVAL<int>& interior_indices=all_interior_indices(tid); int interior_n=interior_indices.Size()+1; T beta=0;if(iteration==1) p_interior(tid)=z_interior(tid);else{beta=(T)(rho/rho_old);for(int i=1;i<=interior_n;i++) p_interior(tid)(i)=z_interior(tid)(i)+beta*p_interior(tid)(i);} } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Part_Six(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,const ARRAY<ARRAY<INTERVAL<int> > >& all_ghost_indices,const SPARSE_MATRIX_FLAT_NXN<T>& A) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); const INTERVAL<int>& interior_indices=all_interior_indices(tid); const ARRAY<INTERVAL<int> >& ghost_indices=all_ghost_indices(tid); A.Times(interior_indices,ghost_indices,p,temp); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Part_Seven(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,ARRAY<VECTOR_ND<T> >& x_interior,ARRAY<VECTOR_ND<T> >& b_interior,ARRAY<VECTOR_ND<T> >& p_interior,ARRAY<VECTOR_ND<T> >& temp_interior,T alpha) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); const INTERVAL<int>& interior_indices=all_interior_indices(tid); int interior_n=interior_indices.Size()+1; for(int i=1;i<=interior_n;i++){x_interior(tid)(i)+=alpha*p_interior(tid)(i);b_interior(tid)(i)-=alpha*temp_interior(tid)(i);} } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Distribute(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,ARRAY<VECTOR_ND<T> >& interior,const T sum) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); interior(tid)-=sum; } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Sum(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,ARRAY<VECTOR_ND<T> >& interior,ARRAY<T>& sum) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); sum(tid)=(T)interior(tid).Sum_Double_Precision(); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Max(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,ARRAY<VECTOR_ND<T> >& interior,ARRAY<T>& sum) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); sum(tid)=interior(tid).Max_Abs(); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Solve_Dot(RANGE<TV_INT>& domain,const ARRAY<int,TV_INT>& domain_index,const ARRAY<INTERVAL<int> >& all_interior_indices,ARRAY<VECTOR_ND<T> >& interior_1,ARRAY<VECTOR_ND<T> >& interior_2,ARRAY<T>& sum) { RANGE<TV_INT> interior_domain(domain);interior_domain.max_corner-=TV_INT::All_Ones_Vector();interior_domain.min_corner+=TV_INT::All_Ones_Vector(); int tid=domain_index(interior_domain.min_corner); sum(tid)=(T)VECTOR_ND<T>::Dot_Product_Double_Precision(interior_1(tid),interior_2(tid)); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Subtract(VECTOR_ND<T>& vector,const T sum,int start_index,int end_index) { for(int i=start_index;i<=end_index;i++) vector(i)-=sum; } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Sum(VECTOR_ND<T>& vector,ARRAY<T>& sum,int start_index,int end_index,int tid) { sum(tid)=(T)vector.Sum_Double_Precision(start_index,end_index); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Dot(VECTOR_ND<T>& vector1,VECTOR_ND<T>& vector2,ARRAY<T>& sum,int start_index,int end_index,int tid) { sum(tid)=(T)VECTOR_ND<T>::Dot_Product_Double_Precision(vector1,vector2,start_index,end_index); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Max(VECTOR_ND<T>& vector,ARRAY<T>& sum,int start_index,int end_index,int tid) { sum(tid)=vector.Max_Abs(start_index,end_index); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Part_One(SPARSE_MATRIX_FLAT_NXN<T>& A,VECTOR_ND<T>& x,VECTOR_ND<T>& b,const T sum,int start_index,int end_index) { for(int i=start_index;i<=end_index;i++) x(i)-=sum; A.Times(start_index,end_index,p,temp); for(int i=start_index;i<=end_index;i++) b(i)-=temp(i); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Part_Two(VECTOR_ND<T>& z,T rho,T rho_old,int iteration,int start_index,int end_index) { T beta=0;if(iteration==1){for(int i=start_index;i<=end_index;i++) p(i)=z(i);}else{beta=(T)(rho/rho_old);for(int i=start_index;i<=end_index;i++) p(i)=z(i)+beta*p(i);} } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Part_Three(SPARSE_MATRIX_FLAT_NXN<T>& A,int start_index,int end_index) { A.Times(start_index,end_index,p,temp); } template<class TV> void PCG_SPARSE_THREADED<TV>:: Threaded_Part_Four(VECTOR_ND<T>& x,VECTOR_ND<T>& b,T alpha,int start_index,int end_index) { for(int i=start_index;i<=end_index;i++){x(i)+=alpha*p(i);b(i)-=alpha*temp(i);} } //##################################################################### template class PCG_SPARSE_THREADED<VECTOR<float,1> >; template class PCG_SPARSE_THREADED<VECTOR<float,2> >; template class PCG_SPARSE_THREADED<VECTOR<float,3> >; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class PCG_SPARSE_THREADED<VECTOR<double,1> >; template class PCG_SPARSE_THREADED<VECTOR<double,2> >; template class PCG_SPARSE_THREADED<VECTOR<double,3> >; #endif
#!/bin/bash ########################################################### ## Ejemplo: Se muestra como usar los decimales ## para que tenga deciamles, hay que definir la variable ########################################################### ## Leer de teclado y guardar en variable NUMERO1 read -p 'Introduce el primer numero : ' NUMERO1 ## Leer de teclado y guardar en variable NUMERO2 read -p 'Introduce el segundo numero : ' NUMERO2 ## Realiza la suma de los dos numeros suma=$[$NUMERO1+$NUMERO2] ## scale para indicar el numero de decimales media=$( echo " scale=2; $suma/3 " | bc -l ) echo "La media es : $media"
$(document).ready(function(){ var deliveryTeam = []; $.get("api/manage-team/team/delivery", function(data){ deliveryTeam =JSON.parse(JSON.stringify(data)).data; for(var i=0; i<deliveryTeam.length; i++){ var card = $('.delivery_boy_card').clone(); card.removeClass('delivery_boy_card').addClass('delivery_boy_cloned').removeClass('hidden'); $('.delivery_boy').append(card); card.attr('data-team-id',deliveryTeam[i].id); card.children().children().eq(0).children().append(deliveryTeam[i].username); card.children().children().eq(1).children().eq(0).attr('href','deliveryBoyHistory?id='+deliveryTeam[i].id).attr('data-assignee-id',deliveryTeam[i].id); } }); // Search delivery boys card $("#delivery_boy_search_view").on('keyup',function(e){ var text = $.trim($(this).val()).replace(/ +/g, '').toLowerCase(); var card = $(".delivery_boy_cloned"); var input; $.each(card,function(index,data){ input = $.trim($(this).children().children().children().text()).toLowerCase().replace(/ +/g, ''); (!~input.indexOf(text) == 0) ? $(this).show() : $(this).hide(); }); }); // search row $("#delivery_boy_history_info_search").on('keyup',function(e){ var text = $.trim($(this).val()).replace(/ +/g, '').toLowerCase(); var tRow = $(".del-boy-hist-row"); var input; $.each(tRow,function(index,data){ input = $.trim($(this).children().text()).toLowerCase().replace(/ +/g, ''); (!~input.indexOf(text) == 0) ? $(this).show() : $(this).hide(); }); }); /*$('.delivery_boy_cloned').on('click',function(){ var assign_to = $(this).attr('data-team-id'); alert(assign_to); $.get("api/manage_delivery/delivery_boys_history", function(data){ deliveryTeam =JSON.parse(JSON.stringify(data)); for(var i=0; i<deliveryTeam.data.length; i++){ $('.del_boy_name').html(deliveryTeam.data[i].assign_to_name); var row = $('.del-boy-hist-row').clone(); row.removeClass('del-boy-hist-row').addClass('del-boy-hist-row-cloned').removeClass('hidden'); $('.del-boy-hist-tbody').append(row); if(deliveryTeam.data[i].assign_to == assign_to){ $.each(row,function(data){ $(this).children().eq(1).append(deliveryTeam.data[i].order_id); $(this).children().eq(2).append(deliveryTeam.data[i].client_name); $(this).children().eq(3).append(deliveryTeam.data[i].delivery_address); $(this).children().eq(4).append(deliveryTeam.data[i].order_status); $(this).children().eq(5).append(deliveryTeam.data[i].delivery_date); }); }else{ } } }); });*/ });
<reponame>YaroShkvorets/ant-design-vue import type { PanelMode } from '../interface'; export default function getExtraFooter( prefixCls: string, mode: PanelMode, renderExtraFooter?: (mode: PanelMode) => any, ) { if (!renderExtraFooter) { return null; } return <div class={`${prefixCls}-footer-extra`}>{renderExtraFooter(mode)}</div>; }
<filename>li-apache-kafka-clients/src/main/java/com/linkedin/kafka/clients/utils/CompositeCollection.java /* * Copyright 2019 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License").
 See License in the project root for license information. */ package com.linkedin.kafka.clients.utils; import java.util.Collection; import java.util.Iterator; /** * quick and simple unmodifiable implementation of a collection on top of a pair of other collections. * @param <T> value type */ public class CompositeCollection<T> implements Collection<T> { private final Collection<T> a; private final Collection<T> b; public CompositeCollection(Collection<T> a, Collection<T> b) { if (a == null || b == null) { throw new IllegalArgumentException("arguments must not be null"); } this.a = a; this.b = b; } @Override public int size() { return a.size() + b.size(); } @Override public boolean isEmpty() { return a.isEmpty() && b.isEmpty(); } @Override public boolean contains(Object o) { return a.contains(o) || b.contains(o); } @Override public Iterator<T> iterator() { return new CompositeIterator<>(a.iterator(), b.iterator()); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <U> U[] toArray(U[] a) { throw new UnsupportedOperationException(); } @Override public boolean add(T t) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } }
#!/bin/sh read -r -p 'Commit message: ' desc # prompt user for commit message branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p') git add . git add -u git commit -m "$desc" git push origin $branch
package com.company; import java.util.Scanner; public class Exercise_2_13 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the monthly saving amount: "); double monthlySaving = input.nextDouble(); double monthlyRate = 0.00417; double amount; amount = monthlySaving * (1 + monthlyRate); monthlySaving = 100 + amount; amount = monthlySaving * (1 + monthlyRate); monthlySaving = 100 + amount; amount = monthlySaving * (1 + monthlyRate); monthlySaving = 100 + amount; amount = monthlySaving * (1 + monthlyRate); monthlySaving = 100 + amount; amount = monthlySaving * (1 + monthlyRate); monthlySaving = 100 + amount; amount = monthlySaving * (1 + monthlyRate); monthlySaving = 100 + amount; System.out.println("After the sixth month, the account value is $"+ amount); } }
<gh_stars>10-100 package artifality.item.base; import artifality.extension.Artifact; import artifality.item.ArtifactSettings; import net.minecraft.item.ItemStack; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import java.awt.*; public class ArtifactItem extends BaseTrinketItem implements Artifact { private final ArtifactSettings settings; public ArtifactItem(ArtifactSettings settings) { super(settings.getItemSettings()); this.settings = settings; } @Override public ArtifactSettings getSettings() { return settings; } @Override public Text getName(ItemStack stack) { Color color = settings.getRarity().getColor(); return new TranslatableText(this.getTranslationKey(stack)).setStyle(Style.EMPTY.withColor(color.getRGB())); } }
<reponame>yamamotok/dataobject import { hasFactory } from './hasFactory'; import { hasToPlain } from './hasToPlain'; export function isDataObject(ctor: unknown): boolean { if (typeof ctor !== 'function') { return false; } return hasToPlain(ctor) && hasFactory(ctor); }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.PIDFCoefficients; @com.qualcomm.robotcore.eventloop.opmode.TeleOp(name = "UltimateGoalTeleOp", group = "Competition") public class TeleOp extends Robot { @Override public void init() { super.init(); } @Override public void loop() { setTime = System.currentTimeMillis(); PIDFCoefficients pidOrig = brrr.getPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER); // change coefficients using methods included with DcMotorEx class. PIDFCoefficients pidNew = new PIDFCoefficients(NEW_P, NEW_I, NEW_D, NEW_F); brrr.setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, pidNew); PIDFCoefficients pidModified = brrr.getPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER); brrr.setPower(x); if (gamepad1.left_bumper) { frontLeft.setPower((-gamepad1.left_stick_y + gamepad1.left_stick_x + gamepad1.right_stick_x) * .35); frontRight.setPower((gamepad1.left_stick_y + gamepad1.left_stick_x + gamepad1.right_stick_x) * .35); backRight.setPower((gamepad1.left_stick_y - gamepad1.left_stick_x + gamepad1.right_stick_x) * .35); backLeft.setPower((-gamepad1.left_stick_y - gamepad1.left_stick_x + gamepad1.right_stick_x) * .35); } else { frontLeft.setPower(-gamepad1.left_stick_y + gamepad1.left_stick_x + gamepad1.right_stick_x); frontRight.setPower(gamepad1.left_stick_y + gamepad1.left_stick_x + gamepad1.right_stick_x); backRight.setPower(gamepad1.left_stick_y - gamepad1.left_stick_x + gamepad1.right_stick_x); backLeft.setPower(-gamepad1.left_stick_y - gamepad1.left_stick_x + gamepad1.right_stick_x); } if (gamepad1.a) { isPressed = true; shoot(); } else { } if (gamepad1.left_trigger > 0) { intake.setPower(-1); } else if (gamepad1.right_trigger > 0) { intake.setPower(gamepad1.right_trigger); } else { intake.setPower(0); } if (gamepad1.dpad_down) { if(wobbleServo.getPosition() > 0.46){ wobble.setTargetPosition(425); wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); wobble.setPower(0.3); while(wobble.isBusy()) { } wobbleServo.setPosition(0); wobble.setPower(0); wobble.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); wobble.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } else{ } } else if (gamepad1.dpad_up) { if (wobbleServo.getPosition() < 0.1) { wobbleServo.setPosition(0.47); wobble.setTargetPosition(-425); wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); wobble.setPower(0.3); while(wobble.isBusy()) { } wobble.setPower(0); wobble.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); wobble.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } else { } } else if (gamepad1.dpad_right){ if(wobbleServo.getPosition() > 0.46) { wobble.setTargetPosition(320); wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); wobble.setPower(0.3); while (wobble.isBusy()) { } wobbleServo.setPosition(0); wobble.setPower(0); wobble.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); wobble.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } else { } } else if (gamepad1.dpad_left){ if (wobbleServo.getPosition() < 0.1) { wobble.setTargetPosition(-320); wobble.setMode(DcMotor.RunMode.RUN_TO_POSITION); wobble.setPower(0.3); while(wobble.isBusy()) { } wobbleServo.setPosition(0.47); wobble.setPower(0); wobble.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); wobble.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); } else { } } else { wobble.setPower(0); } telemetry.addData("Runtime", "%.03f", getRuntime()); telemetry.addData("P,I,D (orig)", "%.04f, %.04f, %.0f", pidOrig.p, pidOrig.i, pidOrig.d); telemetry.addData("P,I,D (modified)", "%.04f, %.04f, %.04f", pidModified.p, pidModified.i, pidModified.d); telemetry.addData("Speed", brrr.getVelocity()); telemetry.addData("Power", brrr.getPower()); telemetry.addData("Wobble counts", wobble.getCurrentPosition()); telemetry.addData("wobble servo position", wobbleServo.getPosition()); telemetry.update(); } public void shoot() { while (isPressed) { brrr.setPower(-0.88); while(System.currentTimeMillis() - setTime < 1400) { telemetry.addData("Revving", true); telemetry.update(); } while(System.currentTimeMillis() - setTime < 1650) { shooterServo.setPosition(0.5); telemetry.addData("Shot Number", 1); telemetry.update(); } shooterServo.setPosition(0.312); while(System.currentTimeMillis() - setTime < 2025) { } while(System.currentTimeMillis() - setTime < 2250) { shooterServo.setPosition(0.5); telemetry.addData("Shot Number", 2); telemetry.update(); } shooterServo.setPosition(0.312); while(System.currentTimeMillis() - setTime < 2650) { } while(System.currentTimeMillis() - setTime < 2875) { shooterServo.setPosition(0.5); telemetry.addData("Shot Number", 3); telemetry.update(); } shooterServo.setPosition(0.312); isPressed = false; brrr.setPower(0); } } }
#!/bin/bash dotnet build AutoMiniProfiler.sln /nologo dotnet test AutoMiniProfiler.sln
// @flow import * as React from 'react' import { Avatar, Box2, ConnectedUsernames, FloatingMenu, HOCTimers, Icon, ProgressIndicator, Text, type PropsWithTimer, } from '../../../../../common-adapters/' import {collapseStyles, globalColors, globalMargins, isMobile, platformStyles} from '../../../../../styles' import {formatTimeForPopup, formatTimeForRevoked, msToDHMS} from '../../../../../util/timestamp' import {addTicker, removeTicker, type TickerID} from '../../../../../util/second-timer' import {PopupHeaderText, type MenuItem} from '../../../../../common-adapters/popup-menu' import type {DeviceType} from '../../../../../constants/types/devices' import type {Position} from '../../../../../common-adapters/relative-popup-hoc' type Props = { attachTo: ?React.Component<any, any>, author: string, deviceName: string, deviceRevokedAt: ?number, deviceType: DeviceType, explodesAt: number, hideTimer: boolean, items: Array<MenuItem | 'Divider' | null>, onHidden: () => void, position: Position, style?: Object, timestamp: number, visible: boolean, yourMessage: boolean, } type State = { secondsLeft: number, } class ExplodingPopupHeader extends React.Component<PropsWithTimer<Props>, State> { timer: TickerID state = { secondsLeft: 0, } componentWillMount() { if (!__STORYBOOK__) { this.timer = addTicker(this.tick) } this.tick() } componentWillUnmount() { this.timer && removeTicker(this.timer) } tick = () => { const now = __STORYBOOK__ ? 1999999999000 : Date.now() let secondsLeft = Math.floor((this.props.explodesAt - now) / 1000) if (secondsLeft < 0) { // TODO remove if we end up w/ an "exploded" popup this.props.onHidden() secondsLeft = 0 } this.setState({secondsLeft}) } render() { const {author, deviceName, deviceRevokedAt, hideTimer, timestamp, yourMessage} = this.props const whoRevoked = yourMessage ? 'You' : author const bombVerticalOffset = isMobile ? 0 : -20 return ( <Box2 direction="vertical" fullWidth={true} style={{alignItems: 'center', paddingTop: (isMobile ? 96 : 64) + bombVerticalOffset}} > <Icon style={{marginBottom: globalMargins.tiny, position: 'absolute', top: bombVerticalOffset}} type={isMobile ? 'icon-fancy-bomb-129-96' : 'icon-fancy-bomb-86-64'} /> <Box2 direction="vertical" gap="tiny" gapStart={true} gapEnd={true}> <Text type="BodySmall" style={{color: globalColors.black_75}}> EXPLODING MESSAGE </Text> </Box2> <Box2 direction="horizontal"> <Text type="BodySmall">by</Text> <Box2 direction="horizontal" gap="xtiny" gapStart={true} style={{alignItems: 'center'}}> <Avatar username={author} size={16} clickToProfile="tracker" /> <ConnectedUsernames clickable={true} colorFollowing={true} colorYou={true} usernames={[author]} underline={true} type="BodySmallSemibold" /> </Box2> </Box2> <Box2 direction="horizontal"> <Text type="BodySmall">using device {deviceName}</Text> </Box2> <Box2 direction="horizontal"> <Text type="BodySmall">{formatTimeForPopup(timestamp)}</Text> </Box2> {deviceRevokedAt && ( <PopupHeaderText color={globalColors.white} backgroundColor={globalColors.blue} style={styleRevokedAt} > {whoRevoked} revoked this device on {formatTimeForRevoked(deviceRevokedAt)}. </PopupHeaderText> )} <Box2 direction="vertical" gap="xsmall" fullWidth={true} gapEnd={true} gapStart={true} style={collapseStyles([ styleTimerBox, { backgroundColor: this.state.secondsLeft < oneMinuteInS ? globalColors.red : globalColors.black_75, }, ])} > {hideTimer ? ( <ProgressIndicator white={true} style={{width: 17, height: 17}} /> ) : ( <Text style={{color: globalColors.white, textAlign: 'center'}} type="BodySemibold"> {msToDHMS(this.props.explodesAt - Date.now())} </Text> )} </Box2> </Box2> ) } } const ExplodingPopupMenu = (props: PropsWithTimer<Props>) => { const header = { style: { paddingBottom: 0, paddingTop: 24, }, title: 'header', view: <ExplodingPopupHeader {...props} />, } return ( <FloatingMenu attachTo={props.attachTo} closeOnSelect={true} header={header} items={props.items} onHidden={props.onHidden} position={props.position} style={collapseStyles([stylePopup, props.style])} visible={props.visible} /> ) } const oneMinuteInS = 60 const stylePopup = platformStyles({ common: { overflow: 'visible', }, isElectron: { width: 196, }, isMobile: { width: '100%', }, }) const styleRevokedAt = { borderBottomLeftRadius: 3, borderBottomRightRadius: 3, marginBottom: -globalMargins.small, marginTop: globalMargins.small, width: '100%', } const styleTimerBox = platformStyles({ common: { alignItems: 'center', justifyContent: 'center', marginTop: globalMargins.tiny, }, isMobile: { height: 46, }, }) export default HOCTimers(ExplodingPopupMenu)
#!/usr/bin/env bats load '../lib/helper' load '../bats/extensions/bats-support/load' load '../bats/extensions/bats-assert/load' load '../bats/extensions/bats-file/load' @test "view: helm view" { run helm secrets view assert_failure assert_output --partial 'Error: secrets file required.' } @test "view: helm view --help" { run helm secrets view --help assert_success assert_output --partial 'View specified encrypted yaml file' } @test "view: File not exits" { run helm secrets view nonexists assert_failure assert_output --partial 'File does not exist: nonexists' } @test "view: secrets.yaml" { FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" run helm secrets view "${FILE}" assert_success assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: some-secrets.yaml" { FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/some-secrets.yaml" run helm secrets view "${FILE}" assert_success assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: values.yaml" { FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/values.yaml" run helm secrets view "${FILE}" assert_success assert_output --partial 'global_secret: ' assert_output --partial 'global_values' } @test "view: secrets.yaml + special char directory name" { if is_windows; then skip "Skip on Windows" fi FILE="${SPECIAL_CHAR_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" run helm secrets view "${FILE}" assert_success assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: secrets.yaml + --driver-args (simple)" { if ! is_driver "sops"; then skip fi FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" run helm secrets --driver-args "--verbose" view "${FILE}" assert_success assert_output --partial "Data key recovered successfully" assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: secrets.yaml + -a (simple)" { if ! is_driver "sops"; then skip fi FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" run helm secrets -a "--verbose" view "${FILE}" assert_success assert_output --partial "Data key recovered successfully" assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: secrets.yaml + HELM_SECRETS_DRIVER_ARGS (simple)" { if ! is_driver "sops"; then skip fi FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" HELM_SECRETS_DRIVER_ARGS=--verbose export HELM_SECRETS_DRIVER_ARGS run helm secrets view "${FILE}" assert_success assert_output --partial "Data key recovered successfully" assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: secrets.yaml + --driver-args (complex)" { if ! is_driver "sops"; then skip fi FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" run helm secrets --driver-args "--verbose --output-type \"yaml\"" view "${FILE}" assert_success assert_output --partial "Data key recovered successfully" assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: secrets.yaml + -a (complex)" { if ! is_driver "sops"; then skip fi FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" run helm secrets -a "--verbose --output-type \"yaml\"" view "${FILE}" assert_success assert_output --partial "Data key recovered successfully" assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' } @test "view: secrets.yaml + HELM_SECRETS_DRIVER_ARGS (complex)" { if ! is_driver "sops"; then skip fi FILE="${TEST_TEMP_DIR}/assets/values/${HELM_SECRETS_DRIVER}/secrets.yaml" # shellcheck disable=SC2089 HELM_SECRETS_DRIVER_ARGS="--verbose --output-type \"yaml\"" # shellcheck disable=SC2090 export HELM_SECRETS_DRIVER_ARGS run helm secrets view "${FILE}" assert_success assert_output --partial "Data key recovered successfully" assert_output --partial 'global_secret: ' assert_output --partial 'global_bar' }
#!/bin/bash rlwrap stellite-wallet-cli --wallet-file wallet_m --password "" --testnet --trusted-daemon --daemon-address localhost:38081 --log-file wallet_m.log start_mining
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'; import { Observable, of } from 'rxjs'; import { mergeMap, take } from 'rxjs/operators'; import { Hero } from './hero.model'; import { HeroService } from './hero.service'; @Injectable({ providedIn: 'root' }) export class HeroResolverService implements Resolve<Hero> { constructor(private heroService: HeroService) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Hero> { const id = +route.paramMap.get('id'); return this.heroService.getHero(id).pipe( take(1), mergeMap(hero => of(hero)) ); } }
#!/bin/bash set -e set +x if [[ ($1 == '--help') || ($1 == '-h') ]]; then echo "usage: $(basename $0) [firefox|webkit] [--full-history] [--has-all-builds]" echo echo "List CDN status for browser" echo exit 0 fi if [[ $# == 0 ]]; then echo "missing browser: 'firefox' or 'webkit'" echo "try './$(basename $0) --help' for more information" exit 1 fi trap "cd $(pwd -P)" EXIT cd "$(dirname "$0")" HOST="https://playwright2.blob.core.windows.net/builds" FFOX_REVISION=$(head -1 ../firefox/BUILD_NUMBER) FFOX_ARCHIVES=( "$HOST/firefox/%s/firefox-mac-10.14.zip" "$HOST/firefox/%s/firefox-ubuntu-18.04.zip" "$HOST/firefox/%s/firefox-win32.zip" "$HOST/firefox/%s/firefox-win64.zip" ) FFOX_ALIASES=( "FF-MAC" "FF-UBUNTU-18.04" "FF-WIN32" "FF-WIN64" ) WK_REVISION=$(head -1 ../webkit/BUILD_NUMBER) WK_ARCHIVES=( "$HOST/webkit/%s/webkit-ubuntu-18.04.zip" "$HOST/webkit/%s/webkit-ubuntu-20.04.zip" "$HOST/webkit/%s/webkit-mac-10.14.zip" "$HOST/webkit/%s/webkit-mac-10.15.zip" "$HOST/webkit/%s/webkit-win64.zip" ) WK_ALIASES=( "WK-UBUNTU-18.04" "WK-UBUNTU-20.04" "WK-MAC-10.14" "WK-MAC-10.15" "WK-WIN64" ) COLUMN="%-18s" # COLORS RED=$'\e[1;31m' GRN=$'\e[1;32m' YEL=$'\e[1;33m' END=$'\e[0m' REVISION="" ARCHIVES="" ALIASES="" if [[ ("$1" == "firefox") || ("$1" == "firefox/") ]]; then REVISION=$FFOX_REVISION ARCHIVES=("${FFOX_ARCHIVES[@]}") ALIASES=("${FFOX_ALIASES[@]}") elif [[ ("$1" == "webkit") || ("$1" == "webkit/") ]]; then REVISION=$WK_REVISION ARCHIVES=("${WK_ARCHIVES[@]}") ALIASES=("${WK_ALIASES[@]}") else echo ERROR: unknown browser - "$1" exit 1 fi if [[ $* == *--has-all-builds ]]; then for i in "${ARCHIVES[@]}"; do URL=$(printf $i $REVISION) if ! [[ $(curl -s -L -I $URL | head -1 | cut -f2 -d' ') == 200 ]]; then exit 1 fi done; exit 0 fi STOP_REVISION=$((REVISION - 3)) if [[ $* == *--full-history* ]]; then STOP_REVISION=0 fi printf "%7s" "" for i in "${ALIASES[@]}"; do printf $COLUMN $i done printf "\n" while (( REVISION > $STOP_REVISION )); do printf "%-7s" ${REVISION} for i in "${ARCHIVES[@]}"; do URL=$(printf $i $REVISION) if [[ $(curl -s -L -I $URL | head -1 | cut -f2 -d' ') == 200 ]]; then printf ${GRN}$COLUMN${END} "YES" else printf ${RED}$COLUMN${END} "NO" fi done; echo REVISION=$((REVISION - 1 )) if [[ $REVISION == "999" ]]; then REVISION=2 fi done;
from socket import inet_pton, AF_INET6, error as SocketError from .base import ProxyPart class HostPart(ProxyPart): __slots__ = () attribute = '_host' def render(self, obj, value, raw=False): result = super(HostPart, self).render(obj, value, raw) try: if not raw: result.encode('ascii') except UnicodeEncodeError: result = result.encode('idna').decode('ascii') if result: try: # Identify and armour IPv6 address literals. inet_pton(AF_INET6, value) except SocketError: pass else: result = '[' + result + ']' return result def __set__(self, obj, value): if isinstance(value, bytes): value = value.decode('idna') elif value.startswith('xn--'): value = value.encode('ascii').decode('idna') value = value.lower().rstrip('.') super().__set__(obj, value)
% python timeit.py "100**100" 100000 loops, best of 3: 4.04 usec per loop % python timeit.py "200**200" 100000 loops, best of 3: 9.03 usec per loop % python timeit.py "100**100" "200**200" 100000 loops, best of 3: 13.1 usec per loop
// Book class class Book { private String title; private String author; private boolean available; public Book(String title, String author) { this.title = title; this.author = author; this.available = true; } public String getTitle() { return title; } public boolean isAvailable() { return available; } public void setAvailable(boolean available) { this.available = available; } } // Library class import java.util.ArrayList; import java.util.List; class Library { private List<Book> books; public Library() { this.books = new ArrayList<>(); } public void addBook(Book book) { books.add(book); } public void borrowBook(String title) { for (Book book : books) { if (book.getTitle().equals(title) && book.isAvailable()) { book.setAvailable(false); System.out.println("You have borrowed the book: " + title); return; } } System.out.println("The book " + title + " is not available for borrowing."); } public void returnBook(String title) { for (Book book : books) { if (book.getTitle().equals(title) && !book.isAvailable()) { book.setAvailable(true); System.out.println("You have returned the book: " + title); return; } } System.out.println("The book " + title + " is not in the library or is already available."); } public void displayAvailableBooks() { System.out.println("Available books in the library:"); for (Book book : books) { if (book.isAvailable()) { System.out.println(book.getTitle()); } } } } // LibraryApp class public class LibraryApp { public static void main(String[] args) { Library library = new Library(); Book book1 = new Book("The Great Gatsby", "F. Scott Fitzgerald"); Book book2 = new Book("To Kill a Mockingbird", "Harper Lee"); Book book3 = new Book("1984", "George Orwell"); library.addBook(book1); library.addBook(book2); library.addBook(book3); library.displayAvailableBooks(); library.borrowBook("To Kill a Mockingbird"); library.displayAvailableBooks(); library.returnBook("To Kill a Mockingbird"); library.displayAvailableBooks(); } }
#!/usr/bin/env bash # Author : Titouan Laessle # Copyright 2017 Titouan Laessle # License : MIT # Quick check if we do have the directories, if not create them function check_parent { parent_dir=$( dirname $1 ) if [[ ! -d $parent_dir ]]; then mkdir $parent_dir fi } # Will download the feature table of the species species="$1" # Checking if parent directory already exist output_table="$2" check_parent $output_table # Using accession script to find the right accession accession=$( bash ../input/accessions.sh $species ) # The 10th element contains the file "name", which we use to extract the files we need genes=$(echo $accession | cut -f 10 -d '/')'_genomic.gff.gz' wget $accession$genes # We will add the UTR using NCBI python code python ../scripts/add_utrs_to_gff.py $genes > temp mv temp $output_table # We will also add the introns using own code python3 ../scripts/add_introns_to_gff.py $output_table temp mv temp $output_table # Clean everything rm $genes
SELECT e1.name as employeeName, e2.name as managerName FROM employee e1 INNER JOIN employee e2 ON e1.managerID = e2.id;
<reponame>fyamvbf/nablarch-sandbox CREATE TABLE PUBLIC.BATCH_REQUEST ( BATCH_REQUEST_ID VARCHAR(100) NOT NULL, BATCH_REQUEST_NAME VARCHAR(100) NOT NULL, PROCESS_HALT_FLG CHAR(1) NOT NULL, PROCESS_ACTIVE_FLG CHAR(1) NOT NULL, SERVICE_AVAILABLE CHAR(1) NOT NULL, RESUME_POINT BIGINT NOT NULL, PRIMARY KEY (BATCH_REQUEST_ID) ); COMMENT ON table PUBLIC.BATCH_REQUEST is '�o�b�`���N�G�X�g'; COMMENT ON column PUBLIC.BATCH_REQUEST.BATCH_REQUEST_ID is '�o�b�`���N�G�X�gID'; COMMENT ON column PUBLIC.BATCH_REQUEST.BATCH_REQUEST_NAME is '���N�G�X�g��'; COMMENT ON column PUBLIC.BATCH_REQUEST.PROCESS_HALT_FLG is '������~�t���O'; COMMENT ON column PUBLIC.BATCH_REQUEST.PROCESS_ACTIVE_FLG is '�A�N�e�B�u�t���O'; COMMENT ON column PUBLIC.BATCH_REQUEST.SERVICE_AVAILABLE is '�T�[�r�X�񋟉”ۏ��'; COMMENT ON column PUBLIC.BATCH_REQUEST.RESUME_POINT is '���W���[���|�C���g'; CREATE TABLE PUBLIC.BUSINESS_DATE ( SEGMENT_ID CHAR(2) NOT NULL, BIZ_DATE CHAR(8) NOT NULL, PRIMARY KEY (SEGMENT_ID) ); COMMENT ON table PUBLIC.BUSINESS_DATE is '�Ɩ����t'; COMMENT ON column PUBLIC.BUSINESS_DATE.SEGMENT_ID is '�Z�O�����gID'; COMMENT ON column PUBLIC.BUSINESS_DATE.BIZ_DATE is '�Ɩ����t'; CREATE TABLE PUBLIC.CODE_NAME ( CODE_ID CHAR(8) NOT NULL, CODE_VALUE VARCHAR(2) NOT NULL, LANG CHAR(2) NOT NULL, SORT_ORDER SMALLINT NOT NULL, CODE_NAME VARCHAR(50) NOT NULL, SHORT_NAME VARCHAR(50), OPTION01 VARCHAR(50), OPTION02 VARCHAR(50), OPTION03 VARCHAR(50), OPTION04 VARCHAR(50), OPTION05 VARCHAR(50), OPTION06 VARCHAR(50), OPTION07 VARCHAR(50), OPTION08 VARCHAR(50), OPTION09 VARCHAR(50), OPTION10 VARCHAR(50), PRIMARY KEY (CODE_ID, CODE_VALUE, LANG) ); COMMENT ON table PUBLIC.CODE_NAME is '�R�[�h����'; COMMENT ON column PUBLIC.CODE_NAME.CODE_ID is '�R�[�hID'; COMMENT ON column PUBLIC.CODE_NAME.CODE_VALUE is '�R�[�h�l'; COMMENT ON column PUBLIC.CODE_NAME.LANG is '����'; COMMENT ON column PUBLIC.CODE_NAME.SORT_ORDER is '�\�[�g��'; COMMENT ON column PUBLIC.CODE_NAME.CODE_NAME is '����'; COMMENT ON column PUBLIC.CODE_NAME.SHORT_NAME is '�R�[�h����'; COMMENT ON column PUBLIC.CODE_NAME.OPTION01 is '�I�v�V��������01'; COMMENT ON column PUBLIC.CODE_NAME.OPTION02 is '�I�v�V��������02'; COMMENT ON column PUBLIC.CODE_NAME.OPTION03 is '�I�v�V��������03'; COMMENT ON column PUBLIC.CODE_NAME.OPTION04 is '�I�v�V��������04'; COMMENT ON column PUBLIC.CODE_NAME.OPTION05 is '�I�v�V��������05'; COMMENT ON column PUBLIC.CODE_NAME.OPTION06 is '�I�v�V��������06'; COMMENT ON column PUBLIC.CODE_NAME.OPTION07 is '�I�v�V��������07'; COMMENT ON column PUBLIC.CODE_NAME.OPTION08 is '�I�v�V��������08'; COMMENT ON column PUBLIC.CODE_NAME.OPTION09 is '�I�v�V��������09'; COMMENT ON column PUBLIC.CODE_NAME.OPTION10 is '�I�v�V��������10'; CREATE TABLE PUBLIC.CODE_PATTERN ( CODE_ID CHAR(8) NOT NULL, CODE_VALUE VARCHAR(2) NOT NULL, PATTERN01 CHAR(1) NOT NULL, PATTERN02 CHAR(1), PATTERN03 CHAR(1), PATTERN04 CHAR(1), PATTERN05 CHAR(1), PATTERN06 CHAR(1), PATTERN07 CHAR(1), PATTERN08 CHAR(1), PATTERN09 CHAR(1), PATTERN10 CHAR(1), PATTERN11 CHAR(1), PATTERN12 CHAR(1), PATTERN13 CHAR(1), PATTERN14 CHAR(1), PATTERN15 CHAR(1), PATTERN16 CHAR(1), PATTERN17 CHAR(1), PATTERN18 CHAR(1), PATTERN19 CHAR(1), PATTERN20 CHAR(1), PRIMARY KEY (CODE_ID, CODE_VALUE) ); COMMENT ON table PUBLIC.CODE_PATTERN is '�R�[�h�p�^�[��'; COMMENT ON column PUBLIC.CODE_PATTERN.CODE_ID is '�R�[�hID'; COMMENT ON column PUBLIC.CODE_PATTERN.CODE_VALUE is '�R�[�h�l'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN01 is '�p�^�[��01'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN02 is '�p�^�[��02'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN03 is '�p�^�[��03'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN04 is '�p�^�[��04'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN05 is '�p�^�[��05'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN06 is '�p�^�[��06'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN07 is '�p�^�[��07'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN08 is '�p�^�[��08'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN09 is '�p�^�[��09'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN10 is '�p�^�[��10'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN11 is '�p�^�[��11'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN12 is '�p�^�[��12'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN13 is '�p�^�[��13'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN14 is '�p�^�[��14'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN15 is '�p�^�[��15'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN16 is '�p�^�[��16'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN17 is '�p�^�[��17'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN18 is '�p�^�[��18'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN19 is '�p�^�[��19'; COMMENT ON column PUBLIC.CODE_PATTERN.PATTERN20 is '�p�^�[��20'; CREATE TABLE PUBLIC.MAIL_ATTACHED_FILE ( MAIL_REQUEST_ID VARCHAR(20) NOT NULL, SERIAL_NUMBER NUMERIC(10) NOT NULL, FILE_NAME VARCHAR(150) NOT NULL, CONTENT_TYPE VARCHAR(50) NOT NULL, ATTACHED_FILE BYTEA NOT NULL, PRIMARY KEY (MAIL_REQUEST_ID, SERIAL_NUMBER) ); COMMENT ON table PUBLIC.MAIL_ATTACHED_FILE is '���[���Y�t�t�@�C��'; COMMENT ON column PUBLIC.MAIL_ATTACHED_FILE.MAIL_REQUEST_ID is '���[�����M�v��ID'; COMMENT ON column PUBLIC.MAIL_ATTACHED_FILE.SERIAL_NUMBER is '�A��'; COMMENT ON column PUBLIC.MAIL_ATTACHED_FILE.FILE_NAME is '�Y�t�t�@�C����'; COMMENT ON column PUBLIC.MAIL_ATTACHED_FILE.CONTENT_TYPE is '�Y�t�t�@�C��CONTENT-TYPE'; COMMENT ON column PUBLIC.MAIL_ATTACHED_FILE.ATTACHED_FILE is '�Y�t�t�@�C��'; CREATE TABLE PUBLIC.MAIL_RECIPIENT ( MAIL_REQUEST_ID VARCHAR(20) NOT NULL, SERIAL_NUMBER BIGINT NOT NULL, RECIPIENT_TYPE CHAR(1) NOT NULL, MAIL_ADDRESS VARCHAR(254) NOT NULL, PRIMARY KEY (MAIL_REQUEST_ID, SERIAL_NUMBER) ); COMMENT ON table PUBLIC.MAIL_RECIPIENT is '���[�����M��'; COMMENT ON column PUBLIC.MAIL_RECIPIENT.MAIL_REQUEST_ID is '���[�����M�v��ID'; COMMENT ON column PUBLIC.MAIL_RECIPIENT.SERIAL_NUMBER is '�A��'; COMMENT ON column PUBLIC.MAIL_RECIPIENT.RECIPIENT_TYPE is '���M��敪'; COMMENT ON column PUBLIC.MAIL_RECIPIENT.MAIL_ADDRESS is '���[���A�h���X'; CREATE TABLE PUBLIC.MAIL_REQUEST ( MAIL_REQUEST_ID VARCHAR(20) NOT NULL, MAIL_SEND_PATTERN_ID VARCHAR(2), SUBJECT VARCHAR(150) NOT NULL, MAIL_BODY VARCHAR(4000) NOT NULL, MAIL_FROM VARCHAR(254) NOT NULL, REPLY_TO VARCHAR(254) NOT NULL, RETURN_PATH VARCHAR(254) NOT NULL, CHARSET VARCHAR(50) NOT NULL, STATUS CHAR(1) NOT NULL, REQUEST_DATETIME TIMESTAMP, SEND_DATETIME TIMESTAMP, PROCESS_ID CHAR(36), PRIMARY KEY (MAIL_REQUEST_ID) ); COMMENT ON table PUBLIC.MAIL_REQUEST is '���[�����M�v��'; COMMENT ON column PUBLIC.MAIL_REQUEST.MAIL_REQUEST_ID is '���[�����M�v��ID'; COMMENT ON column PUBLIC.MAIL_REQUEST.MAIL_SEND_PATTERN_ID is '���[�����M�p�^�[��ID'; COMMENT ON column PUBLIC.MAIL_REQUEST.SUBJECT is '����'; COMMENT ON column PUBLIC.MAIL_REQUEST.MAIL_BODY is '�{��'; COMMENT ON column PUBLIC.MAIL_REQUEST.MAIL_FROM is '���M�҃��[���A�h���X'; COMMENT ON column PUBLIC.MAIL_REQUEST.REPLY_TO is '�ԐM�惁�[���A�h���X'; COMMENT ON column PUBLIC.MAIL_REQUEST.RETURN_PATH is '���߂��惁�[���A�h���X'; COMMENT ON column PUBLIC.MAIL_REQUEST.CHARSET is '�����Z�b�g'; COMMENT ON column PUBLIC.MAIL_REQUEST.STATUS is '�X�e�[�^�X'; COMMENT ON column PUBLIC.MAIL_REQUEST.REQUEST_DATETIME is '�v������'; COMMENT ON column PUBLIC.MAIL_REQUEST.SEND_DATETIME is '���M����'; COMMENT ON column PUBLIC.MAIL_REQUEST.PROCESS_ID is '�v���Z�XID'; CREATE TABLE PUBLIC.MAIL_TEMPLATE ( MAIL_TEMPLATE_ID VARCHAR(10) NOT NULL, LANG CHAR(2) NOT NULL, SUBJECT VARCHAR(150) NOT NULL, MAIL_BODY TEXT NOT NULL, CHARSET VARCHAR(50) NOT NULL, PRIMARY KEY (MAIL_TEMPLATE_ID, LANG) ); COMMENT ON table PUBLIC.MAIL_TEMPLATE is '���[���e���v���[�g'; COMMENT ON column PUBLIC.MAIL_TEMPLATE.MAIL_TEMPLATE_ID is '���[���e���v���[�gID'; COMMENT ON column PUBLIC.MAIL_TEMPLATE.LANG is '����'; COMMENT ON column PUBLIC.MAIL_TEMPLATE.SUBJECT is '����'; COMMENT ON column PUBLIC.MAIL_TEMPLATE.MAIL_BODY is '�{��'; COMMENT ON column PUBLIC.MAIL_TEMPLATE.CHARSET is '�����Z�b�g'; CREATE TABLE PUBLIC.SAMPLE_USER ( USER_INFO_ID CHAR(20) NOT NULL, LOGIN_ID VARCHAR(20) NOT NULL, KANJI_NAME VARCHAR(50) NOT NULL, KANA_NAME VARCHAR(50) NOT NULL, STATUS CHAR(1) NOT NULL, PRIMARY KEY (USER_INFO_ID) ); COMMENT ON table PUBLIC.SAMPLE_USER is '�T���v�����[�U���'; COMMENT ON column PUBLIC.SAMPLE_USER.USER_INFO_ID is '���[�U���ID'; COMMENT ON column PUBLIC.SAMPLE_USER.LOGIN_ID is '���O�C��ID'; COMMENT ON column PUBLIC.SAMPLE_USER.KANJI_NAME is '��������'; COMMENT ON column PUBLIC.SAMPLE_USER.KANA_NAME is '���Ȏ���'; COMMENT ON column PUBLIC.SAMPLE_USER.STATUS is '�����X�e�[�^�X'; ALTER TABLE PUBLIC.CODE_NAME ADD FOREIGN KEY ( CODE_ID, CODE_VALUE ) REFERENCES PUBLIC.CODE_PATTERN ( CODE_ID, CODE_VALUE ); ALTER TABLE PUBLIC.MAIL_ATTACHED_FILE ADD FOREIGN KEY ( MAIL_REQUEST_ID ) REFERENCES PUBLIC.MAIL_REQUEST ( MAIL_REQUEST_ID ); ALTER TABLE PUBLIC.MAIL_RECIPIENT ADD FOREIGN KEY ( MAIL_REQUEST_ID ) REFERENCES PUBLIC.MAIL_REQUEST ( MAIL_REQUEST_ID ); CREATE TABLE INS_PROJECT_SEND_MESSAGE ( SEND_MESSAGE_SEQUENCE CHAR(10) NOT NULL, PROJECT_NAME VARCHAR(128) NOT NULL, PROJECT_TYPE VARCHAR(128) NOT NULL, PROJECT_CLASS VARCHAR(128) NOT NULL, PROJECT_START_DATE DATE, PROJECT_END_DATE DATE, CLIENT_ID NUMERIC(9,0), PROJECT_MANAGER VARCHAR(128), PROJECT_LEADER VARCHAR(128), USER_ID NUMERIC(9,0) NOT NULL, NOTE VARCHAR(512), SALES NUMERIC(9,0), COST_OF_GOODS_SOLD NUMERIC(9,0), SGA NUMERIC(9,0), ALLOCATION_OF_CORP_EXPENSES NUMERIC(9,0), STATUS CHAR(1), INSERT_USER_ID CHAR(10), INSERT_DATE TIMESTAMP, UPDATED_USER_ID CHAR(10), UPDATED_DATE TIMESTAMP(10), INSERT_REQUEST_ID CHAR(30) ) ; CREATE INDEX PRO_INS_REQ_ST_IDX ON INS_PROJECT_SEND_MESSAGE (STATUS) ; ALTER TABLE INS_PROJECT_SEND_MESSAGE ADD CONSTRAINT PK_PROJECT PRIMARY KEY (SEND_MESSAGE_SEQUENCE) ; CREATE TABLE INS_PROJECT_RECEIVE_MESSAGE ( RECEIVED_MESSAGE_SEQUENCE CHAR(10) NOT NULL, PROJECT_NAME VARCHAR(128) NOT NULL, PROJECT_TYPE VARCHAR(128) NOT NULL, PROJECT_CLASS VARCHAR(128) NOT NULL, PROJECT_START_DATE DATE, PROJECT_END_DATE DATE, CLIENT_ID NUMERIC(9,0), PROJECT_MANAGER VARCHAR(128), PROJECT_LEADER VARCHAR(128), USER_ID NUMERIC(9,0) NOT NULL, NOTE VARCHAR(512), SALES NUMERIC(9,0), COST_OF_GOODS_SOLD NUMERIC(9,0), SGA NUMERIC(9,0), ALLOCATION_OF_CORP_EXPENSES NUMERIC(9,0), STATUS CHAR(1), INSERT_USER_ID CHAR(10), INSERT_DATE TIMESTAMP, UPDATED_USER_ID CHAR(10), UPDATED_DATE TIMESTAMP, INSERT_REQUEST_ID CHAR(30) ) ; CREATE INDEX PRO_TEMP_ST_IDX ON INS_PROJECT_RECEIVE_MESSAGE (STATUS) ; ALTER TABLE INS_PROJECT_RECEIVE_MESSAGE ADD CONSTRAINT PK_PROJECT2 PRIMARY KEY (RECEIVED_MESSAGE_SEQUENCE) ; CREATE TABLE ID_GENERATE ( GENERATOR_ID VARCHAR(30) NOT NULL, GENERATED_NO NUMERIC(10,0) NOT NULL ) ; ALTER TABLE ID_GENERATE ADD CONSTRAINT PK_ID_GENERATE PRIMARY KEY (GENERATOR_ID) ;
/* rule = RewriteConsoleUsage */ package fix.standard_services import scala.io.StdIn.readLine object ConsoleUsage { def consoleProgram() = { println("Please enter your name") val name = readLine() val x = 3 println("Hello " + name) } }
#!/bin/bash export pip_build_version=$(python get_version.py) export build_version=$pip_build_version export docker_build_version=$(echo $pip_build_version | sed 's/+/_/g') wheel_suffix=$(python -c "import sys; print(sys.version_info.major)") wheel_name_tail="${pip_build_version}-py${wheel_suffix}-none-any.whl" build_module () { directory=$1 module_name=$2 cwd=$3 wheel_path="${cwd}/${directory}/dist/${module_name}-${wheel_name_tail}" cd ${cwd}/${directory} && \ rm -rf "./build" || true && \ rm -rf "./dist" || true && \ python setup.py sdist bdist_wheel && \ python -m pip install -U $wheel_path && \ cd .. && \ mkdir -p ${cwd}/dist 2>/dev/null && \ cp $wheel_path ${cwd}/dist }
<reponame>albangaignard/galaxy-PROV /* * The MIT License * * Copyright 2016 <NAME> <<EMAIL>>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import fr.univnantes.galaxyld.GHistAPI; import fr.univnantes.galaxyld.GalaxyProvenanceException; import fr.univnantes.galaxyld.Util; import java.util.Map; import org.apache.commons.lang.time.StopWatch; import org.codehaus.jettison.json.JSONException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author <NAME> <<EMAIL>> */ public class TestGalaxAPI { private static String gURL; private static String gApiKey; public TestGalaxAPI() { } @BeforeClass public static void setUpClass() throws GalaxyProvenanceException { TestGalaxAPI.gURL = Util.getProperty("URL"); TestGalaxAPI.gApiKey = Util.getProperty("API-key"); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void directApiTest() throws JSONException, GalaxyProvenanceException { String url = Util.getProperty("URL"); String key = Util.getProperty("API-KEY"); // GHistAPI gAPI = new GHistAPI("https://galaxy-bird.univ-nantes.fr/galaxy/", "dd3b7fce727d53ac00512ea19a8f5d4f"); GHistAPI gAPI = new GHistAPI(url, key); StopWatch sw = new StopWatch(); sw.start(); Map<String,String> map = gAPI.listHistories(); for (String k : map.keySet()) { System.out.println(map.get(k)); } String provTTL = gAPI.getProv("491a45f0d6ea6596"); sw.stop(); System.out.println("Direct REST : done in " + sw.getTime() + " ms"); System.out.println(provTTL); } // https://usegalaxy.org | d75134deaabcda270120e146b41672e4 }
task=multitask # or bart model="bart" echo $model if [ $model == "t5" ] then folder_prefix="VLT5" backbone="t5-base" batch_size=300 elif [ $model == "bart" ] then folder_prefix="VLBart" backbone="facebook/bart-base" batch_size=500 fi echo $folder_prefix echo $backbone feature=RN101 lr=1e-3 lora_dim=128 name=${feature}_LMmultilora${lora_dim}+lr${lr}_bs${batch_size}_image224 output=snap/${folder_prefix}_${task}/$name TOKENIZERS_PARALLELISM=True PYTHONPATH=$PYTHONPATH:./src \ python -m torch.distributed.launch \ --nproc_per_node=$1 \ --master_port=26786 \ src/${task}.py \ --distributed --multiGPU \ --optim adamw \ --warmup_ratio 0.1 \ --clip_grad_norm 5 \ --lr ${lr} \ --epochs 20 \ --num_workers 4 \ --backbone ${backbone} \ --output $output ${@:2} \ --num_beams 5 \ --use_lora \ --lora_dim ${lora_dim} \ --batch_size ${batch_size} \ --valid_batch_size ${batch_size} \ --tasks "vqa,gqa,nlvr,caption" \ --feature ${feature} --n_boxes 36 --downsample \ --image_size "(224,224)" \ --run_name $name
<gh_stars>0 package org.springaop.chapter.two.pointcut; public class RegExpTargetExample { public void printName() { System.out.println("Max"); } public void printAction() { System.out.println("swim"); } public void printSpot() { System.out.println("in Poetto beach"); } }
import os import torch class BaseModel(object): def initialize(self, opt): self.opt = opt self.gpu_ids = opt.gpu_ids self.is_Train = opt.is_Train self.save_dir = os.path.join(opt.checkpoints_dir, opt.model) self.result_dir = os.path.join(opt.test_dir, opt.pretrained_G) if opt.pretrained_G else opt.test_dir # helper saving function that can be used by subclasses def save_network(self,network, network_label, epoch_label, gpu_ids): save_filename = '{0}_net_{1}.path'.format(epoch_label, network_label) save_path = os.path.join(self.save_dir, save_filename) torch.save(network.cpu().state_dict(), save_path) if len(gpu_ids) and torch.cuda.is_available(): network.cuda(device=gpu_ids[0]) def load(self, network, filename): # save_path = os.path.join(self.save_dir, filename) save_path = os.path.join('checkpoints', filename) network.load_state_dict(torch.load(save_path)) # for the use of the breakpoint def reload(self, count_epoch): G_filename = '{}_net_G.path'.format(count_epoch) D_filename = '{}_net_D.path'.format(count_epoch) self.load(self.G, G_filename) self.load(self.D, D_filename) # update learning rate (called once every epoch) def update_learning_rate(self): for scheduler in self.schedulers: scheduler.step() lr = self.optimizers[0].param_groups[0]['lr'] print('learning rate = %.7f'%lr)
rm -rf ./build/macos/Build/Products/Debug/* rm -rf ./build/macos/Build/Products/Release/*
'use strict'; var _32 = { elem: 'svg', attrs: { xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 32 32', width: 32, height: 32, }, content: [ { elem: 'path', attrs: { d: 'M9.5 8h10.6a5 5 0 1 0 0-2H9.5a5.5 5.5 0 0 0 0 11h11a3.5 3.5 0 0 1 0 7h-8.6a5 5 0 1 0 0 2h8.6a5.5 5.5 0 0 0 0-11h-11a3.5 3.5 0 0 1 0-7zM25 4a3 3 0 1 1-3 3 3 3 0 0 1 3-3zM7 28a3 3 0 1 1 3-3 3 3 0 0 1-3 3z', }, }, ], name: '3D-curve--auto-colon', size: 32, }; module.exports = _32;
#!/bin/bash for n in {3..48..3} do echo "./mp " $1 " " $2 " " $4 " " ${n} ./throughput_mp $1 ${n} $2 $3 $4 $5 $6 $7 $8 >> results/throughput_mp.txt done echo "./sequential " $1 " " $2 " " $4 " " 1 ./sequential $1 1 $2 $3 $4 $5 $6 $7 $8 >> results/sequential.txt cd plot ./tput_mp.sh cp tput_mp.eps "../throughput_mp_"$1"_"$2"_"$3"_"$4"_"$5"_"$6"_"$7"_"$8".eps" ./speedup_mp.sh cp speedup_mp.eps "../speedup_mp_"$1"_"$2"_"$3"_"$4"_"$5"_"$6"_"$7"_"$8".eps" cd .. rm results/*.txt plot/*.eps
<reponame>Jwt-acs/ANG-JWTAuthenticator<filename>src/app/starter/profile/profile.component.ts<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { LoginServiceService } from '../../services/login-service.service'; import swal from 'sweetalert'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.css'] }) export class ProfileComponent implements OnInit { firstName:any; showauth:boolean=false auth:any; authnumber:any; profRes:any; successMessage:any; authnumbers:any; uid:any; checkterms:any; username:any; lastname:any; email:any; constructor(private router:Router,private loginService:LoginServiceService) { this.auth=sessionStorage.getItem('auth'); this.uid=sessionStorage.getItem('uid'); this.username=sessionStorage.getItem('name'); this.lastname=sessionStorage.getItem('lastname'); this.email=sessionStorage.getItem('email'); } ngOnInit(): void { } activateauth(){ this.showauth=true; } update(){ sessionStorage.setItem('name',this.username) sessionStorage.setItem('lastname',this.lastname) sessionStorage.setItem('email',this.email) this.loginService.updateprofile(this.uid,this.username,this.lastname,this.email).subscribe( success=>{ this.profRes=success swal(this.profRes); sessionStorage.setItem('auth','no') this.auth=sessionStorage.getItem('auth'); } ); } getuniq(){ var applicationname='JWTAuthenticator'; this.loginService.getdeviceuniqid(this.email,applicationname).subscribe( success=>{ this.profRes =success console.log(this.profRes); for (let key of this.profRes) { console.log("object:", key); this.successMessage=key.msg; this.authnumbers=key.appUniqeID; } this.updateauth(); sessionStorage.setItem('auth','yes') }); } updateauth(){ debugger; var q=2; this.loginService.authdata(this.uid,this.authnumbers,q).subscribe( success=>{ this.profRes =success swal(success); }); } selectauth(){ } noauth(){ debugger; var q=1; this.loginService.noauthdata(this.uid,q).subscribe( success=>{ this.profRes=success swal(this.profRes); sessionStorage.setItem('auth','no') this.auth=sessionStorage.getItem('auth'); } ); } logout(){ this.router.navigate(['/']); } }
<reponame>Weked/JUnit_Test_Exercise<filename>biblioteca3.0/src/bibliotecaUFMA/cadastroUsuario.java package bibliotecaUFMA; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SpringLayout; public class cadastroUsuario extends JPanel implements ActionListener{ /** * */ private static final long serialVersionUID = 1L; private JLabel cadastro; private JLabel nome; private JLabel sobrenome; private JLabel cpf; private JLabel senha; private JLabel id; private JTextField campoNome; private JTextField campoSobrenome; private JTextField campoCpf; private JTextField campoSenha; private JTextField campoId; private JButton btCadastro; private SpringLayout layout; private biblioteca b; private CadastroUsuarioFunction function; public cadastroUsuario(biblioteca x){ this.b = x; this.setSize(450, 250); this.componentes(); this.setLayout(layout); } public void componentes(){ layout = new SpringLayout(); cadastro = new JLabel ("Cadastro Usuario: "); nome = new JLabel("Nome: "); sobrenome = new JLabel("Sobrenome: "); cpf = new JLabel ("CPF: "); senha = new JLabel("Senha: "); id = new JLabel ("ID: "); campoNome = new JTextField(20); campoSobrenome = new JTextField(20); campoCpf = new JTextField(11); campoSenha = new JTextField(20); campoId = new JTextField(5); btCadastro = new JButton("Cadastrar"); btCadastro.addActionListener(this); cadastro.setFont(new Font("Arial",0 , 18)); function = new CadastroUsuarioFunction(); this.add(cadastro); this.add(nome); this.add(campoNome); this.add(sobrenome); this.add(cpf); this.add(campoCpf); this.add(campoSobrenome); this.add(senha); this.add(campoSenha); this.add(btCadastro); this.add(id); this.add(campoId); //tip Texts nome.setToolTipText("Digite Ao Lado Seu Nome"); campoNome.setToolTipText("Digite Aqui Seu Nome"); sobrenome.setToolTipText("Digite Ao Lado Seu Sobrenome"); campoSobrenome.setToolTipText("Digite Aqui Seu Sobrenome"); cpf.setToolTipText("Digite Ao Lado Seu CPF"); campoCpf.setToolTipText("Digite Aqui Seu CPF"); id.setToolTipText("Digite ao Lado Seu ID"); senha.setToolTipText("Digite ao Lado Sua Senha"); campoId.setToolTipText("Digite aqui Seu ID"); campoSenha.setToolTipText("Digite aqui Sua Senha"); btCadastro.setToolTipText("Informe Seus Dados, e Clique Para Se Cadastrar"); layout.putConstraint(SpringLayout.WEST, cadastro, 5, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.NORTH, cadastro, 10, SpringLayout.NORTH, this); layout.putConstraint(SpringLayout.WEST, nome, 38, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.NORTH, nome, 40, SpringLayout.SOUTH, cadastro); layout.putConstraint(SpringLayout.WEST, campoNome, 5, SpringLayout.EAST, nome); layout.putConstraint(SpringLayout.NORTH, campoNome, 40, SpringLayout.SOUTH, cadastro); layout.putConstraint(SpringLayout.WEST, sobrenome, 5, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.NORTH, sobrenome, 10, SpringLayout.SOUTH, nome); layout.putConstraint(SpringLayout.WEST, campoSobrenome, 5, SpringLayout.EAST, sobrenome); layout.putConstraint(SpringLayout.NORTH, campoSobrenome, 10, SpringLayout.SOUTH, nome); layout.putConstraint(SpringLayout.WEST, cpf, 50, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.NORTH, cpf, 10, SpringLayout.SOUTH, sobrenome); layout.putConstraint(SpringLayout.WEST, campoCpf, 5, SpringLayout.EAST, cpf); layout.putConstraint(SpringLayout.NORTH, campoCpf, 10, SpringLayout.SOUTH, sobrenome); layout.putConstraint(SpringLayout.WEST, senha, 35, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.NORTH, senha, 10, SpringLayout.SOUTH, cpf); layout.putConstraint(SpringLayout.WEST, campoSenha, 5, SpringLayout.EAST, senha); layout.putConstraint(SpringLayout.NORTH, campoSenha, 10, SpringLayout.SOUTH, cpf); layout.putConstraint(SpringLayout.WEST, id, 60, SpringLayout.WEST, this); layout.putConstraint(SpringLayout.NORTH, id, 10, SpringLayout.SOUTH, senha); layout.putConstraint(SpringLayout.WEST, campoId, 5, SpringLayout.EAST, id); layout.putConstraint(SpringLayout.NORTH, campoId, 10, SpringLayout.SOUTH, senha); layout.putConstraint(SpringLayout.EAST, btCadastro, 0, SpringLayout.EAST, campoSenha); layout.putConstraint(SpringLayout.NORTH, btCadastro, 10, SpringLayout.SOUTH, campoId); } @Override public void actionPerformed(ActionEvent evento) { if(evento.getSource() == btCadastro){ try{ String nome = campoNome.getText(); String sobrenome = campoSobrenome.getText(); long cpf = Long.parseLong(campoCpf.getText()); int senha = Integer.parseInt(campoSenha.getText()); int id = Integer.parseInt(campoId.getText()); /*System.out.println(nome); System.out.println(sobrenome); System.out.println(cpf); System.out.println(senha); System.out.println(id);*/ ///////////// /* contaUsuario userAccount = new contaUsuario(senha, id); usuario user = new usuario(nome, sobrenome, cpf, userAccount); b.getUsuarios().put(id, user); */ /* System.out.println(b.getUsuarios().size()); for(int key : b.getUsuarios().keySet()){ System.out.println(b.getUsuarios().get(key).getNome()); System.out.println(b.getUsuarios().get(key).getSobrenome()); System.out.println(b.getUsuarios().get(key).getCpf()); System.out.println(b.getUsuarios().get(key).getConta().getId()); System.out.println(b.getUsuarios().get(key).getConta().getSenha()); }*/ //JOptionPane.showMessageDialog(this, String.format("ta funcionando")); if(function.cadastro(b, senha, id, nome, sobrenome, cpf)){ JOptionPane.showMessageDialog(this, String.format("Usuario Cadastrado com Sucesso!!!")); campoNome.setText(""); campoSobrenome.setText(""); campoCpf.setText(""); campoSenha.setText(""); campoId.setText(""); }/*else{ JOptionPane.showMessageDialog(this, String.format("veio no else")); }*/ }catch(Exception excessao){ JOptionPane.showMessageDialog(this, String.format("Verifique seus dados!")); } } } }
class Admin::NewAuctionViewModel < Admin::BaseViewModel attr_reader :auction DEFAULT_START_DAYS = 5 DEFAULT_END_DAYS = 7 DEFAULT_DELIVERY_DAYS = 12 def initialize(auction = nil) @auction = auction end def new_record auction || Auction.new end def new_auction_nav_class 'usa-current' end def c2_proposal_partial 'components/null' end def paid_at_partial 'components/null' end def estimated_delivery_due_at DcTimePresenter.convert_and_format(default_date_time('delivery_due_at').convert) end def date_default(field) default_date_time(field).convert.to_date end def hour_default(field) default_date_time(field).hour end def minute_default(field) default_date_time(field).minute end def meridiem_default(field) default_date_time(field).meridiem end def billable_to_options ClientAccountQuery.new.active.map(&:to_s) end def customer_options Customer.sorted end def delivery_url_partial 'components/null' end private def default_date_time(field) if field == 'started' DefaultDateTime.new(DEFAULT_START_DAYS.business_days.from_now) elsif field == 'ended' DefaultDateTime.new(DEFAULT_END_DAYS.business_days.from_now) else DefaultDateTime.new(DEFAULT_DELIVERY_DAYS.business_days.from_now) end end end
import sys import re import os from typing import List from pathlib import Path def process_output_files(output_dir: str, output_base_names: List[str]) -> List[str]: chrom_regex = re.compile(r'(chr[a-zA-Z0-9]+)') chromosomes = [chrom_regex.search(x).group(1) for x in output_base_names] output_dir = Path(output_dir) if not output_dir.exists(): os.makedirs(str(output_dir)) return chromosomes
c = [[0] * 15 for i in range(5)] for i in range(5): d = list(input()) d_len = len(d) for j in range(d_len): c[i][j] = d[j] for i in range(15): for j in range(5): if c[j][i] == 0: continue else: print(c[j][i], end='')
#!/bin/bash timeout 12 cvc4 cvc4-m-i-q-T_12-VS-z3-T_1-GeRnz_1.smt2 --tlimit=12000 >/dev/null 2>&1 retVal=$? if [ $retVal -eq 124 ] then timeout 1 z3 -smt2 cvc4-m-i-q-T_12-VS-z3-T_1-GeRnz_1.smt2 -T:1 >/dev/null 2>&1 exit $? fi exit 1
<filename>script/js/weather.js<gh_stars>0 // Weather - Openweathermap.org API - Markle $.getJSON('http://api.openweathermap.org/data/2.5/weather?id=4923226&units=imperial&APPID=180f0c84f43029018bef20431f8b0416', function(data) { console.log(data.name); $('#currentTemp').text(data.main.temp + '°'); $('#description').text(data.weather[0].main); })
package com.guigu.single; /* * ����ʽ�� * �ӳٴ������ʵ������ * * 懒汉式: * 延迟创建这个实例对象 * * (1)构造器私有化 * (2)用一个静态变量保存这个唯一的实例 * (3)提供一个静态方法,获取这个实例对象 */ public class Singleton5 { private static Singleton5 instance; private Singleton5(){ } public static Singleton5 getInstance(){ if(instance == null){ synchronized (Singleton5.class) { if(instance == null){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } instance = new Singleton5(); } } } return instance; } }
<reponame>mjirik/scaffanweb # /usr/bin/env python # -*- coding: utf-8 -*- import os import zipfile # zipdir # # def zipdir(path, zip_fn): # # ziph = zipfile.ZipFile(zip_fn, 'w', zipfile.ZIP_DEFLATED) # # ziph is zipfile handle # for root, dirs, files in os.walk(path): # for file in files: # ziph.write(os.path.join(root, file)) # zipdir('./my_folder', zipf) # zipf.close() import random import string import random try: from hashlib import sha1 as sha_constructor except ImportError: from django.utils.hashcompat import sha_constructor def generate_sha1(string, salt=None): """ Generates a sha1 hash for supplied string. :param string: The string that needs to be encrypted. :param salt: Optionally define your own salt. If none is supplied, will use a random string of 5 characters. :return: Tuple containing the salt and hash. """ string = str(string) if not salt: salt = str(sha_constructor(str(random.random())).hexdigest()[:5]) import hashlib # >> > sha = hashlib.sha256() # >> > sha.update('somestring'.encode()) # >> > sha.hexdigest() hash = sha_constructor((salt+string).encode()).hexdigest() return hash def randomString(stringLength=8): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(stringLength))
import { Runner } from '../runner/runner' import { ExecutionOptions } from './execution-options' type Fn<Result, Param> = (params: { result: Result; param: Param; executionOptions: ExecutionOptions }) => void type Id = number export abstract class UseCase<Result = void, Param = void> { abstract readonly: boolean abstract internalExecute(param: Param): Promise<Result> private static currentId = 0 private subscriptions = new Map<Id, Fn<Result, Param>>() subscribe(fn: Fn<Result, Param>): Id { const id = UseCase.currentId++ this.subscriptions.set(id, fn) return id } unsubscribe(id: Id) { this.subscriptions.delete(id) } async execute(param: Param, executionOptions: ExecutionOptions = { inlineError: false }): Promise<Result> { const value = (await Runner.run(this as any, executionOptions, param)) as Result this.subscriptions.forEach(x => x({ result: value, param, executionOptions })) return value } }
import os import datetime def rename_files(file_list): current_date = datetime.datetime.now().strftime("%Y%m%d") for filename in file_list: parts = filename.split('_') if len(parts) == 2 and parts[1].endswith('.bin'): new_filename = f"5MCP19_{current_date}.bin" os.rename(filename, new_filename) file_list = ['5MCP19_20210714.bin', '5MCP19_20210722.bin'] rename_files(file_list)
/*==================================================================*\ | EXIP - Embeddable EXI Processor in C | |--------------------------------------------------------------------| | This work is licensed under BSD 3-Clause License | | The full license terms and conditions are located in LICENSE.txt | \===================================================================*/ /** * @file streamRead.c * @brief Implementing the interface to a low-level EXI stream reader * * @date Aug 18, 2010 * @author <NAME> * @version 0.5 * @par[Revision] $Id$ */ #include "streamRead.h" #include "ioUtil.h" const unsigned char BIT_MASK[] = { (char) 0x00, // 0b00000000 (char) 0x01, // 0b00000001 (char) 0x03, // 0b00000011 (char) 0x07, // 0b00000111 (char) 0x0F, // 0b00001111 (char) 0x1F, // 0b00011111 (char) 0x3F, // 0b00111111 (char) 0x7F, // 0b01111111 (char) 0xFF }; // 0b11111111 errorCode readNextBit(EXIStream* strm, boolean* bit_val) { if(strm->buffer.bufContent <= strm->context.bufferIndx) // the whole buffer is parsed! read another portion { strm->context.bitPointer = 0; strm->context.bufferIndx = 0; strm->buffer.bufContent = 0; if(strm->buffer.ioStrm.readWriteToStream == NULL) return EXIP_BUFFER_END_REACHED; strm->buffer.bufContent = strm->buffer.ioStrm.readWriteToStream(strm->buffer.buf, strm->buffer.bufLen, strm->buffer.ioStrm.stream); if(strm->buffer.bufContent == 0) return EXIP_BUFFER_END_REACHED; } *bit_val = (strm->buffer.buf[strm->context.bufferIndx] & (1<<REVERSE_BIT_POSITION(strm->context.bitPointer))) != 0; moveBitPointer(strm, 1); DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" @%u:%u", (unsigned int) strm->context.bufferIndx, strm->context.bitPointer)); return EXIP_OK; } errorCode readBits(EXIStream* strm, unsigned char n, unsigned int* bits_val) { unsigned int numBytesToBeRead = 1 + ((n + strm->context.bitPointer - 1) / 8); unsigned int byteIndx = 1; unsigned char *buf; if(strm->buffer.bufContent < strm->context.bufferIndx + numBytesToBeRead) { // The buffer end is reached: there are fewer than n bits left unparsed errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; TRY(readEXIChunkForParsing(strm, numBytesToBeRead)); } buf = (unsigned char *) strm->buffer.buf + strm->context.bufferIndx; *bits_val = (buf[0] & BIT_MASK[8 - strm->context.bitPointer])<<((numBytesToBeRead-1)*8); while(byteIndx < numBytesToBeRead) { *bits_val += (unsigned int) (buf[byteIndx])<<((numBytesToBeRead-byteIndx-1)*8); byteIndx++; } *bits_val = *bits_val >> (numBytesToBeRead*8 - n - strm->context.bitPointer); DEBUG_MSG(INFO, DEBUG_STREAM_IO, (">> %d [0x%X] (%u bits)", *bits_val, *bits_val, n)); n += strm->context.bitPointer; strm->context.bufferIndx += n / 8; strm->context.bitPointer = n % 8; DEBUG_MSG(INFO, DEBUG_STREAM_IO, (" @%u:%u\n", (unsigned int) strm->context.bufferIndx, strm->context.bitPointer)); return EXIP_OK; }
import os def save_visualization(ypred, true_classes, image_paths): for id_val, (pred, true_class, img_path) in enumerate(zip(ypred, true_classes, image_paths)): root_name, _ = os.path.splitext(img_path) if pred == true_class: save_dir = 'visual_correct' else: save_dir = 'visual_wrong' save_path = os.path.join(save_dir, root_name + '_visual_' + save_dir + '_' + str(id_val) + '.png') # Copy or save the image to the appropriate directory using save_path # Example: shutil.copyfile(img_path, save_path) # or use a library like PIL to save the image
def fahrenheit_to_celsius(fahrenheit): celsius = (fahrenheit - 32) * 5/9 return celsius
<filename>src/java_8_in_action/stream_collector/CollectorHarness.java package java_8_in_action.stream_collector; import static java.util.stream.Collectors.partitioningBy; import java.util.List; import java.util.Map; import java.util.stream.IntStream; // 기본 컬렉터 vs 커스텀 컬렉터 성능 비교 public class CollectorHarness { public static void main(String[] args) { long fastest = Long.MAX_VALUE; for (int i = 0; i < 10; i++) { // 테스트를 10번 반복 long start = System.nanoTime(); //partitionPrimes(1_000_000); // 백만 개의 숫자를 소수와 비소수로 분할한다. (604ms) partitionPrimesWithCustomCollector(1_000_000); // (302ms) long duration = (System.nanoTime() - start) / 1_000_000; // duration을 밀리초 단위로 측정 if (duration < fastest) { // 가장 빨리 실행되었는지 확인. fastest = duration; } } System.out.println("Fastest execution done in " + fastest + "msecs"); } public static boolean isPrime(int candidate) { // 소수의 대상을 주어진 수의 제곱근 이하의 수로 제한함. int candidateRoot = (int) Math.sqrt((double) candidate); return IntStream.rangeClosed(2, candidateRoot) .noneMatch(i -> candidate % i == 0); // 2 부터 candidate 미만의 자연수를 생성함. // return IntStream.range(2, candidate) // .noneMatch(i -> candidate % i == 0); } // 기존 컬렉터로 사용한 메서드 public static Map<Boolean, List<Integer>> partitionPrimes (int n) { return IntStream.rangeClosed(2, n).boxed() .collect(partitioningBy(candidate -> isPrime(candidate))); } // 커스텀 컬렉터 (PrimeNumbersCollector)를 사용하는 메서드 public static Map<Boolean, List<Integer>> partitionPrimesWithCustomCollector(int n) { return IntStream.rangeClosed(2, n).boxed() .collect(new PrimeNumbersCollector()); } }
#!/usr/bin/env bash source env/bin/activate; python3 scraper.py;
<filename>src/main/java/ch/raiffeisen/openbank/party/persistency/model/PartyType.java package ch.raiffeisen.openbank.party.persistency.model; /** * Party type, in a coded form. * * @author <NAME> */ public enum PartyType { // Party that has delegated access. Delegate, // Party is a joint owner of the account. Joint, // Party is a sole owner of the account. Sole }
<filename>src/components/LocationInput/index.js import component from './LocationInput' import connector from './LocationInput.connector' export default connector(component)
#! /bin/sh set -e export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$PWD/lib" ./bin/nuggan -server ":$PORT" -server-config server.conf
#!/bin/sh build_time=$(date +%s) git_branch=$(git symbolic-ref --short -q HEAD) git_tag=$(git describe --tags --exact-match 2>/dev/null) git_commit_count=$(git rev-list HEAD --count) git_hash=$(git rev-parse --short HEAD) info_plist="${BUILT_PRODUCTS_DIR}/${EXECUTABLE_FOLDER_PATH}/Info.plist" /usr/libexec/PlistBuddy -c "Set :CFBundleVersion '${git_commit_count}'" "${info_plist}" /usr/libexec/PlistBuddy -c "Set :KKBuildTimeStamp '${build_time}'" "${info_plist}" /usr/libexec/PlistBuddy -c "Set :KKGitBranch '${git_branch}'" "${info_plist}" /usr/libexec/PlistBuddy -c "Set :KKGitTag '${git_tag}'" "${info_plist}" /usr/libexec/PlistBuddy -c "Set :KKGitCommitCount '${git_commit_count}'" "${info_plist}" /usr/libexec/PlistBuddy -c "Set :KKGitHash '${git_hash}'" "${info_plist}"
package com.multiteam.mt.proxy; public class ServerProxy extends CommonProxy { }
<reponame>oag221/vcaslib package algorithms.vcas; /* This is an implementation of the Camera object described in the paper "Constant-Time Snapshots with Applications to Concurrent Data Structures" <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> PPoPP 2021 Copyright (C) 2021 <NAME> This program is free software: you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import jdk.internal.vm.annotation.Contended; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import main.support.ThreadID; public class Camera { public static final int PADDING = 32; public static long[] dummyCounters = new long[ThreadID.MAX_THREADS*PADDING]; @Contended public volatile long timestamp; private static final AtomicLongFieldUpdater<Camera> timestampUpdater = AtomicLongFieldUpdater.newUpdater(Camera.class, "timestamp"); private static final ThreadLocal<Integer> backoffAmount = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return 1; } }; public static Camera camera = new Camera(); public Camera() { timestamp = 0; } private static void backoff(int amount) { if(amount == 0) return; int limit = amount; int tid = ThreadID.threadID.get(); for(int i = 0; i < limit; i++) dummyCounters[tid*PADDING] += i; } public static void set(long ts) { camera.timestamp = ts; } public static long takeSnapshot() { // return timestampUpdater.getAndIncrement(camera); long ts = camera.timestamp; int ba = backoffAmount.get(); //if(ba != 1) System.out.println(ba); backoff(ba); if(ts == camera.timestamp) { if(timestampUpdater.compareAndSet(camera, ts, ts+1)) ba /= 2; else ba *= 2; } if(ba < 1) ba = 1; if(ba > 512) ba = 512; backoffAmount.set(ba); return ts; } public static long getTimestamp() { return camera.timestamp; } }
<gh_stars>10-100 # frozen_string_literal: true module Twitch class Client ## API method for games module Games def get_games(options = {}) initialize_response Game, get('games', options) end def get_top_games(options = {}) initialize_response Game, get('games/top', options) end def get_game_analytics(options = {}) require_access_token do initialize_response GameAnalytic, get('analytics/games', options) end end end end end
class RegisterController < ApplicationController include RegisterHelper def create render(nothing: true, status: 405) && return unless request.content_type == 'application/json' render(nothing: true, status: 405) && return unless params.key?(:marketplace_url) render(nothing: true, status: 405) && return unless params.key?(:consumer_url) render(nothing: true, status: 405) && return unless params.key?(:name) render(nothing: true, status: 405) && return unless params.key?(:description) customer = {} customer['id'] = register_on(params[:marketplace_url], params[:consumer_url], params[:name], params[:description]) render json: customer end def delete if $list_of_threads.present? $list_of_threads.each do |thread| Thread.kill(thread) end $list_of_threads = [] end response_code = unregister render json: { 'status code from marketplace' => response_code }.as_json end end
public class GameCharacter { private double positionX; private double speedX; private double accelerationX; public GameCharacter(double initialPositionX, double initialSpeedX, double accelerationX) { this.positionX = initialPositionX; this.speedX = initialSpeedX; this.accelerationX = accelerationX; } public void updatePosition(double deltaTime) { positionX = positionX + speedX * deltaTime + 0.5 * accelerationX * Math.pow(deltaTime, 2); speedX = speedX + accelerationX * deltaTime; } public double getPositionX() { return positionX; } public double getSpeedX() { return speedX; } public double getAccelerationX() { return accelerationX; } public static void main(String[] args) { GameCharacter character = new GameCharacter(0, 5, 2); character.updatePosition(2); System.out.println("PositionX: " + character.getPositionX()); // Output: 20.0 System.out.println("SpeedX: " + character.getSpeedX()); // Output: 15.0 } }
#!/bin/bash #conda activate pytorch model=$1 splits=$(ls ../data/splits) for file in $splits do protocal=$(echo $file | awk 'BEGIN {FS = "_"} {print $1}') if [ $protocal = "template" ] then t1=$(echo $file | awk 'BEGIN {FS = "_"} {print $3}') t2=$(echo $file | awk 'BEGIN {FS = "_"} {print $4}') t3=$(echo $file | awk 'BEGIN {FS = "_"} {print $5}') t=$t1"_"$t2"_"$t3 fold=$(echo $file | awk 'BEGIN {FS = "_"} {print $7}') else t1=$(echo $file | awk 'BEGIN {FS = "_"} {print $3}') t2=$(echo $file | awk 'BEGIN {FS = "_"} {print $4}') #t3=$(echo $file | awk 'BEGIN {FS = "_"} {print $5}') t=$t1"_"$t2 fold=$(echo $file | awk 'BEGIN {FS = "_"} {print $6}') fi echo $protocal $t ${fold:0:1} python train.py --cfg configs/rpcin_within_pred.yaml --template $t --protocal $protocal --fold ${fold:0:1} --model $model done
<reponame>basselhossam/flowchart-designer-and-simulator<filename>Statements/SingleOperator.cpp #include "SingleOperator.h" #include <sstream> using namespace std; SingleOperator::SingleOperator(ApplicationManager * AM, string txt, Point l_cor, int width, int height, int t_width, int t_height, string LeftHS, string RightHS1, string op, string RightHS2) : Statement(AM, txt, l_cor, width, height, t_width, t_height) { LHS = LeftHS; RHS1 = RightHS1; OP = op; RHS2 = RightHS2; UpdateStatementText(); calc_l_corner(); pConn = NULL; //No connectors yet } void SingleOperator::setLHS(const string &L) { LHS = L; UpdateStatementText(); } void SingleOperator::setRHS1(const string &R1) { //missing RHS1 = R1; UpdateStatementText(); } void SingleOperator::setOperator(const string &p) { //missing if (p == "+" || p == "-" || p == "*" || p == "/") OP = p; UpdateStatementText(); } string SingleOperator::GetOperator()const{ return OP; } void SingleOperator::setRHS2(const string &R2) { //missing RHS2 = R2; UpdateStatementText(); } void SingleOperator::Draw(Output* pOut) const { //Call Output::DrawAssign function to draw assignment statement pOut->DrawAssign(l_corner, UI.ASSGN_WDTH, UI.ASSGN_HI, Text, Selected); } //This function should be called when LHS or RHS changes void SingleOperator::UpdateStatementText() { if (LHS == "") //No left handside ==>statement have no valid text yet Text = " = "; else { //Build the statement text: Left handside then equals then right handside ostringstream T; T << LHS << " = " << RHS1<<OP<<RHS2; Text = T.str(); } } bool SingleOperator::Edit(){ string lhs, rhs1, op, rhs2; pOut->ClearStatusBar(); pOut->PrintMessage("Enter the left hand side"); lhs = pIn->GetIdentifier(pOut); if (lhs == ""){ pOut->PrintMessage("Cancel !!"); return false; } pOut->ClearStatusBar(); pOut->PrintMessage("Enter the first operand"); rhs1 = pIn->GetString("",pOut); if (rhs1 == ""){ pOut->PrintMessage("Cancel !!"); return false; } pOut->ClearStatusBar(); pOut->PrintMessage("Enter the operator"); op = pIn->GetArithmaticOperator(pOut); if (op == ""){ pOut->PrintMessage("Cancel !!"); return false; } pOut->ClearStatusBar(); pOut->PrintMessage("Enter the first operand"); rhs2 = pIn->GetString("",pOut); if (rhs2 == ""){ pOut->PrintMessage("Cancel !!"); return false; } LHS = lhs; RHS1 = rhs1; OP = op; RHS2 = rhs2; UpdateStatementText(); pIn->set_Assign_Dim(Text, width, height, t_width, t_height); calc_l_corner(); SetInlet(); SetOutlet(); return true; } string SingleOperator::GetLHS()const { return LHS; } string SingleOperator::GetRHS1() const { return RHS1; } string SingleOperator::GetRHS2()const { return RHS2; } void SingleOperator::GenerateCode(ofstream &OutFile){ //we need to make a varible list to know if it's the first time being intialized or not //if the varible is exist in the varible list OutFile <<" "<< Text << ";\n"; SetGenerated(true); } void SingleOperator::calc_l_corner() { AppMan->GetInput()->calc_stat_corner(inlet, l_corner, width); } void SingleOperator::Save(ofstream &OutFile) { OutFile << "SNGLOP"<<" "<< ID << " " << l_corner.x << " " << l_corner.y<<" "<<LHS<<" "<<RHS1<<" "<<OP<<" "<<RHS2<<" "; OutFile << "\"" << comment << "\"" << endl; } void SingleOperator::Load(ifstream & Infile) { Infile >> ID >> l_corner.x >> l_corner.y >> LHS >> RHS1 >> OP >> RHS2; UpdateStatementText(); set_stat_dim(Text); SetInlet(); SetOutlet(); getline(Infile, comment); comment.erase(comment.begin()); comment.erase(comment.end()-1); } bool SingleOperator::check_range(Point p) { if (p.x >= l_corner.x && p.x <= l_corner.x + width && p.y >= l_corner.y && p.y <= l_corner.y + height) return true; else return false; } void SingleOperator::PrintInfo(Output * pOut) { pOut->PrintMessage(comment); } void SingleOperator::set_stat_dim(string str) { pIn->set_Assign_Dim(Text, width, height, t_width, t_height); } Connector* SingleOperator :: GetConnect(){ return pConn; } void SingleOperator :: SetConnect(Connector*p){ pConn = p; } bool SingleOperator::Simulate(){ double a ,b ; //For first operand if(!CheckValue(RHS1) && !CheckIdentifier(RHS1)) { pOut->ClearStatusBar(); pOut->PrintMessage("ERROR in First Operand !"); this->SetSelected(true); AppMan->SetSelectedStatement(this); return false; } if (CheckValue(RHS1)) { stringstream s; s<<RHS1; s>>a; s.str(""); s.clear(); } else if(CheckIdentifier(RHS1)) { if(AppMan->variables.find(RHS1)!=AppMan->variables.end()) a = AppMan->variables[RHS1]; else {pOut->ClearStatusBar(); pOut->PrintMessage("ERROR : First Operand Undeclared !"); this->SetSelected(true); AppMan->SetSelectedStatement(this); return false; } } //for second operand if(!CheckValue(RHS2) && !CheckIdentifier(RHS2)) { pOut->ClearStatusBar(); pOut->PrintMessage("ERROR in Second Operand !"); this->SetSelected(true); AppMan->SetSelectedStatement(this); return false; } if (CheckValue(RHS2)) { stringstream s; s<<RHS2; s>>b; s.str(""); s.clear(); } else if(CheckIdentifier(RHS2)) { if(AppMan->variables.find(RHS2)!=AppMan->variables.end()) b = AppMan->variables[RHS2]; else { pOut->ClearStatusBar(); pOut->PrintMessage("ERROR : Second Operand Undeclared !"); this->SetSelected(true); AppMan->SetSelectedStatement(this); return false; } } if(OP == "+") AppMan->variables[LHS]= a + b; else if (OP == "-") AppMan->variables[LHS]= a - b; else if(OP == "/") { if(b == 0) { pOut->ClearStatusBar(); pOut->PrintMessage("MATHS ERROR : Can't divide on zero !"); this->SetSelected(true); AppMan->SetSelectedStatement(this); return false; } AppMan->variables[LHS]= a / b; } else if(OP == "*") AppMan->variables[LHS]= a * b; return true; }
import {Helper} from "../gear/Helper"; export const pluginName = "gear-scene-status"; const rawParams = Helper.find(); /** * * @type {PluginParameters} */ export const PARAMS = Helper.parse(rawParams); export let Alias = {}; export const DIRECTORY = { status: "menu/status" }; /** * the bitmap type */ export const BITMAP_TYPE = Object.freeze({ SINGLE: 0, ANIMATED: 1, TILLING: 2 });
<reponame>mablack01/CoordinateFinder<filename>src/Direction.java /** * * @author <NAME> (<EMAIL>) * */ public enum Direction { NORTH(), EAST(), SOUTH(), WEST(); /** * Calculates the new coordinate direction given a command. * @param origin The original direction of a coordinate. * @param turn The direction command, either L or R. * @return The new direction of a coordinate. */ public static Direction setNextDirection(Direction origin, char turn) { switch(turn) { case 'L': if (origin == NORTH) return WEST; else if (origin == EAST) return NORTH; else if (origin == SOUTH) return EAST; else if (origin == WEST) return SOUTH; case 'R': if (origin == NORTH) return EAST; else if (origin == EAST) return SOUTH; else if (origin == SOUTH) return WEST; else if (origin == WEST) return NORTH; default: System.out.println("Invalid move detected, closing program."); System.exit(1); } return null; } }
<gh_stars>100-1000 import { createContext, ReactNode } from 'react'; export interface SVGDefsContextProps { addDef(id: string, node: ReactNode): void; removeDef(id: string): void; } const SVGDefsContext = createContext<SVGDefsContextProps>(undefined as any); export default SVGDefsContext;
package com.bn.tag; public class ShuijingThread extends Thread{ GameView gv; //GameView��������� boolean flag; //�߳��Ƿ�ִ�б�־λ //��Ϸ�Ƿ���б�־λ boolean whileflag=true; //int sleepSpan = AI_THREAD_SLEEP_SPAN; //��Ϸ����ʱ�߳�ִ��ʱ�� public ShuijingThread(GameView gv){ this.gv = gv; flag = false; //isGameOn = true; } public void run(){ //�������߳�ִ�зŷ� while(whileflag){ if(flag){ gv.alpha=gv.alpha-10; if(gv.alpha<0) { gv.alpha=200; gv.shuijing_D_Z_Flag=false; this.setFlag(false); } } try{ Thread.sleep(50); //�߳̿�תʱ�� } catch(Exception e){ e.printStackTrace(); } } } public void setFlag(boolean flag) { this.flag = flag; } public void setwhileflag(boolean whileflag) { this.whileflag=whileflag; } }
<filename>core/src/test/java/org/lint/azzert/context/ContextBuilderTest.java package org.lint.azzert.context; import org.junit.jupiter.api.Test; import org.lint.azzert.strategy.framework.JUnit4Strategy; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; class ContextBuilderTest { @Test void build() throws Exception { Context ctx = new ContextBuilder().build(); assertNotNull(ctx.getSupportedTestFrameworks()); assertTrue(ctx.getSupportedTestFrameworks().size() > 0, "Expected at least one test_framework defined in application-properties.json"); assertTrue(ctx.getSupportedTestFrameworks().containsKey(new JUnit4Strategy().getSupportedFramework()), "object of type JUnit4Strategy should've been loaded"); } }
/* * Copyright (c) Open Source Strategies, Inc. * * Opentaps 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. * * Opentaps 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 Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.domain.order; import java.math.BigDecimal; import java.util.List; /** * Interface for an order specification. When you add your own status codes and other * specification related flags and logic, extend this interface, extend the order domain, * and create your own version of the OrderStatus enumeration. */ public interface OrderSpecificationInterface { /* Logical methods to determine status of order. */ /** * Checks if the given <code>Order</code> is approved. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isApproved(Order order); /** * Checks if the given <code>Order</code> is completed. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isCompleted(Order order); /** * Checks if the given <code>Order</code> is cancelled. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isCancelled(Order order); /** * Checks if the given <code>Order</code> is created. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isCreated(Order order); /** * Checks if the given <code>Order</code> is rejected. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isRejected(Order order); /** * Checks if the given <code>Order</code> is sent. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isSent(Order order); /** * Checks if the given <code>Order</code> is processing. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isProcessing(Order order); /** * Checks if the given <code>Order</code> is on hold. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isOnHold(Order order); /** * Checks if the given <code>Order</code> is pickable. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isPickable(Order order); /* Logical methods to determine type of order. */ /** * Checks if the given <code>Order</code> is a sales order. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isSalesOrder(Order order); /** * Checks if the given <code>Order</code> is a purchase order. * @param order an <code>Order</code> value * @return a <code>Boolean</code> value */ public Boolean isPurchaseOrder(Order order); /* Logical methods to determine status of order item. */ /** * Checks if the given <code>OrderItem</code> is approved. * @param orderItem an <code>OrderItem</code> value * @return a <code>Boolean</code> value */ public Boolean isApproved(OrderItem orderItem); /** * Checks if the given <code>OrderItem</code> is completed. * @param orderItem an <code>OrderItem</code> value * @return a <code>Boolean</code> value */ public Boolean isCompleted(OrderItem orderItem); /** * Checks if the given <code>OrderItem</code> is cancelled. * @param orderItem an <code>OrderItem</code> value * @return a <code>Boolean</code> value */ public Boolean isCancelled(OrderItem orderItem); /** * Checks if the given <code>OrderItem</code> is created. * @param orderItem an <code>OrderItem</code> value * @return a <code>Boolean</code> value */ public Boolean isCreated(OrderItem orderItem); /** * Checks if the given <code>OrderItem</code> is rejected. * @param orderItem an <code>OrderItem</code> value * @return a <code>Boolean</code> value */ public Boolean isRejected(OrderItem orderItem); /** * Checks if the given <code>OrderItem</code> is performed. * @param orderItem an <code>OrderItem</code> value * @return a <code>Boolean</code> value */ public Boolean isPerformed(OrderItem orderItem); /** * Checks if the given <code>OrderItem</code> is a promo item. * @param orderItem an <code>OrderItem</code> value * @return a <code>Boolean</code> value */ public Boolean isPromo(OrderItem orderItem); /* For Return */ /** * Gets the type or <code>Return</code> applicable to the given <code>Order</code>. * @param order an <code>Order</code> value * @return the type of return */ public String getReturnType(Order order); /* Logical methods to determine status of return. */ /** * Checks if the given <code>Return</code> is cancelled. * @param returnObj a <code>Return</code> value * @return a <code>Boolean</code> value */ public Boolean isCancelled(Return returnObj); /** * Checks if the given <code>Return</code> is accepted. * @param returnObj a <code>Return</code> value * @return a <code>Boolean</code> value */ public Boolean isAccepted(Return returnObj); /** * Checks if the given <code>Return</code> is completed. * @param returnObj a <code>Return</code> value * @return a <code>Boolean</code> value */ public Boolean isCompleted(Return returnObj); /** * Checks if the given <code>Return</code> is requested. * @param returnObj a <code>Return</code> value * @return a <code>Boolean</code> value */ public Boolean isRequested(Return returnObj); /** * Checks if the given <code>Return</code> is received. * @param returnObj a <code>Return</code> value * @return a <code>Boolean</code> value */ public Boolean isReceived(Return returnObj); /** * Checks if the given <code>Return</code> is requiring manual refund. * @param returnObj a <code>Return</code> value * @return a <code>Boolean</code> value */ public Boolean isRequiringManualRefund(Return returnObj); /* Logical methods to determine the type of order adjustment. */ /** * Checks if the given <code>OrderAdjustment</code> is a sales tax. * @param adjustment an <code>OrderAdjustment</code> value * @return a <code>Boolean</code> value */ public Boolean isSalesTax(OrderAdjustment adjustment); /** * Checks if the given <code>OrderAdjustment</code> is a shipping charge. * @param adjustment an <code>OrderAdjustment</code> value * @return a <code>Boolean</code> value */ public Boolean isShippingCharge(OrderAdjustment adjustment); /* Logical methods to determine the status of payments. */ /** * Checks if the given <code>OrderPaymentPreference</code> is cancelled. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isCancelled(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is authorized. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isAuthorized(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is not authorized. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isNotAuthorized(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is declined. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isDeclined(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is received. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isReceived(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is not received. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isNotReceived(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is refunded. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isRefunded(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is settled. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isSettled(OrderPaymentPreference payment); /* Logical methods to determine the type of payments. */ /** * Checks if the given <code>OrderPaymentPreference</code> is a billing account payment. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isBillingAccountPayment(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is a cash on delivery payment. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isCashOnDeliveryPayment(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is a credit card payment. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isCreditCardPayment(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is a gift card payment. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isGiftCardPayment(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is an electronic transfer payment. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isElectronicFundTransferPayment(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is a paypal payment. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isPayPalPayment(OrderPaymentPreference payment); /** * Checks if the given <code>OrderPaymentPreference</code> is an offline payment. * @param payment an <code>OrderPaymentPreference</code> value * @return a <code>Boolean</code> value */ public Boolean isOfflinePayment(OrderPaymentPreference payment); /* Return lists of role type Ids. */ /** * Gets the list of party role types applicable for an order commission agent. * @return the list of party role types applicable */ public List<String> commissionAgentRoleTypeIds(); /** * Gets the list of party role types applicable for an order placing customer. * @return the list of party role types applicable */ public List<String> placingCustomerRoleTypeIds(); /** * Gets the list of party role types applicable for an order bill to customer. * @return the list of party role types applicable */ public List<String> billToCustomerRoleTypeIds(); /** * Gets the list of party role types applicable for an order supplier agent. * @return the list of party role types applicable */ public List<String> supplierAgentRoleTypeIds(); /** * Gets the list of party role types applicable for an order bill from vendor. * @return the list of party role types applicable */ public List<String> billFromVendorRoleTypeIds(); /** * Gets the list of party role types applicable for an order ship to customer. * @return the list of party role types applicable */ public List<String> shipToCustomerRoleTypeIds(); /** * Gets the list of party role types applicable for an order distributor. * @return the list of party role types applicable */ public List<String> distributorRoleTypeIds(); /** * Gets the list of party role types applicable for an order affiliate. * @return the list of party role types applicable */ public List<String> affiliateRoleTypeIds(); /* Logical methods to determine the status of shipments. */ /** * Checks if the given <code>Shipment</code> is input. * @param shipment an <code>Shipment</code> value * @return a <code>Boolean</code> value */ public Boolean isInput(Shipment shipment); /** * Checks if the given <code>Shipment</code> is scheduled. * @param shipment an <code>Shipment</code> value * @return a <code>Boolean</code> value */ public Boolean isScheduled(Shipment shipment); /** * Checks if the given <code>Shipment</code> is picked. * @param shipment an <code>Shipment</code> value * @return a <code>Boolean</code> value */ public Boolean isPicked(Shipment shipment); /** * Checks if the given <code>Shipment</code> is packed. * @param shipment an <code>Shipment</code> value * @return a <code>Boolean</code> value */ public Boolean isPacked(Shipment shipment); /** * Checks if the given <code>Shipment</code> is shipped. * @param shipment an <code>Shipment</code> value * @return a <code>Boolean</code> value */ public Boolean isShipped(Shipment shipment); /** * Checks if the given <code>Shipment</code> is delivered. * @param shipment an <code>Shipment</code> value * @return a <code>Boolean</code> value */ public Boolean isDelivered(Shipment shipment); /** * Checks if the given <code>Shipment</code> is cancelled. * @param shipment an <code>Shipment</code> value * @return a <code>Boolean</code> value */ public Boolean isCancelled(Shipment shipment); /* Shipping. */ /** * Gets the unknown shipping address contact mech id. * @return the unknown shipping address contact mech id */ public String getUnknownShippingAddress(); /* Scaling methods. */ /** * Gets the default scale used for rounding <code>BigDecimal</code>. * @return the scale */ public int getScale(); /** * Gets the tax calculation scale used for rounding <code>BigDecimal</code>. * The tax calculation is used for intermediate results and is larger than the tax finale scale. * @return the scale * @see #getTaxFinalScale */ public int getTaxCalculationScale(); /** * Gets the tax final scale used for rounding <code>BigDecimal</code>. * The tax final is used for final results. * @return the scale * @see #getTaxCalculationScale */ public int getTaxFinalScale(); /** * Gets the default rounding method used for rounding <code>BigDecimal</code>. * @return the rounding */ public int getRounding(); /** * Gets the tax rounding method used for rounding <code>BigDecimal</code>. * @return the rounding */ public int getTaxRounding(); /** * Rounds a <code>BigDecimal</code> using the default scale and rounding. * @param amount the amount to round * @return the rounded <code>BigDecimal</code> */ public BigDecimal defaultRounding(BigDecimal amount); /** * Rounds a <code>BigDecimal</code> using the tax calculation scale and rounding. * @param amount the amount to round * @return the rounded <code>BigDecimal</code> */ public BigDecimal taxCalculationRounding(BigDecimal amount); /** * Rounds a <code>BigDecimal</code> using the tax final scale and rounding. * @param amount the amount to round * @return the rounded <code>BigDecimal</code> */ public BigDecimal taxFinalRounding(BigDecimal amount); /** * Gets the stripped length that is used when displaying card numbers. * This is used for example to print out credit card number and not to reveal them completely. * @return the size of the number string that should be revealed */ public int cardsStrippedNumberLength(); }
from .wrapper import CSituationView, _BACKGROUND_COLOR
<reponame>phosphor-icons/phosphr-webcomponents /* GENERATED FILE */ import { html, svg, define } from "hybrids"; const PhChatCircle = { color: "currentColor", size: "1em", weight: "regular", mirrored: false, render: ({ color, size, weight, mirrored }) => html` <svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" fill="${color}" viewBox="0 0 256 256" transform=${mirrored ? "scale(-1, 1)" : null} > ${weight === "bold" && svg`<path d="M45.42853,176.99811A95.95978,95.95978,0,1,1,79.00228,210.5717l.00023-.001L45.84594,220.044a8,8,0,0,1-9.89-9.89l9.47331-33.15657Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/>`} ${weight === "duotone" && svg`<path d="M45.42853,176.99811A95.95978,95.95978,0,1,1,79.00228,210.5717l.00023-.001L45.84594,220.044a8,8,0,0,1-9.89-9.89l9.47331-33.15657Z" opacity="0.2"/> <path d="M45.42853,176.99811A95.95978,95.95978,0,1,1,79.00228,210.5717l.00023-.001L45.84594,220.044a8,8,0,0,1-9.89-9.89l9.47331-33.15657Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`} ${weight === "fill" && svg`<path d="M128.00146,24.002A104.02442,104.02442,0,0,0,36.814,178.041l-8.55468,29.91406a16.00544,16.00544,0,0,0,19.78125,19.78125l29.91406-8.54688A104.00785,104.00785,0,1,0,128.00146,24.002Z"/>`} ${weight === "light" && svg`<path d="M45.42853,176.99811A95.95978,95.95978,0,1,1,79.00228,210.5717l.00023-.001L45.84594,220.044a8,8,0,0,1-9.89-9.89l9.47331-33.15657Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="12"/>`} ${weight === "thin" && svg`<path d="M45.42853,176.99811A95.95978,95.95978,0,1,1,79.00228,210.5717l.00023-.001L45.84594,220.044a8,8,0,0,1-9.89-9.89l9.47331-33.15657Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/>`} ${weight === "regular" && svg`<path d="M45.42853,176.99811A95.95978,95.95978,0,1,1,79.00228,210.5717l.00023-.001L45.84594,220.044a8,8,0,0,1-9.89-9.89l9.47331-33.15657Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`} </svg> `, }; define("ph-chat-circle", PhChatCircle); export default PhChatCircle;
<gh_stars>0 #include <program.hpp> namespace gl { Program::Program() : m_id(glCreateProgram()) {} Program::Program(const std::set<ShaderPtr>& shaders) : Program() { for (const auto& shader : shaders) { attach_shader(shader); } link(); } Program::Program(Program&& other) noexcept : m_id(std::move(other.m_id)), m_shaders(std::move(other.m_shaders)) { other.m_id = INVALID_ID; other.m_shaders.clear(); } Program::~Program() { if (is_valid()) { detach_shaders(); glDeleteProgram(m_id); } } Program& Program::operator=(Program&& other) noexcept { if (this != &other) { if (is_valid()) { detach_shaders(); glDeleteProgram(m_id); } m_id = std::move(other.m_id); m_shaders = std::move(other.m_shaders); other.m_id = INVALID_ID; other.m_shaders.clear(); } return *this; } void Program::attach_shader(std::shared_ptr<Shader> shader) { m_shaders.insert_or_assign(shader->type(), shader); } void Program::detach_shaders() { for (const auto& [type, shader] : m_shaders) { glDetachShader(m_id, shader->id()); } m_shaders.clear(); } bool Program::link() { // attach the shaders and try to link the program for (const auto& [type, shader] : m_shaders) { glAttachShader(m_id, shader->id()); } glLinkProgram(m_id); // check for errors while linking GLint is_linked = get_parameter(GL_LINK_STATUS); if (is_linked != GL_TRUE) { GLint max_length = get_parameter(GL_INFO_LOG_LENGTH); std::vector<GLchar> info_log_vec(max_length); glGetProgramInfoLog(m_id, max_length, &max_length, &info_log_vec[0]); // log the linking error messages std::string info_log(std::begin(info_log_vec), std::end(info_log_vec)); throw std::runtime_error("Linking shader program failed:\n" + info_log); } // always detach shaders to clean up detach_shaders(); return is_linked == GL_TRUE; } void Program::use() const { glUseProgram(m_id); } void Program::unuse() { glUseProgram(0); } bool Program::is_valid() const { return glIsProgram(m_id) != 0; } GLuint Program::id() const { return m_id; } GLint Program::uniform_location(const std::string& name) const { return glGetUniformLocation(m_id, name.c_str()); } void Program::set_uniform_1i(GLint location, GLint value) { glProgramUniform1i(m_id, location, value); } void Program::set_uniform_1i(GLint location, const std::vector<GLint>& value) { glProgramUniform1iv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_2i(GLint location, const std::array<GLint, 2>& value) { glProgramUniform2i(m_id, location, value[0], value[1]); } void Program::set_uniform_2i(GLint location, const std::vector<GLint>& value) { glProgramUniform2iv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_3i(GLint location, const std::array<GLint, 3>& value) { glProgramUniform3i(m_id, location, value[0], value[1], value[2]); } void Program::set_uniform_3i(GLint location, const std::vector<GLint>& value) { glProgramUniform3iv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_4i(GLint location, const std::array<GLint, 4>& value) { glProgramUniform4i(m_id, location, value[0], value[1], value[2], value[3]); } void Program::set_uniform_4i(GLint location, const std::vector<GLint>& value) { glProgramUniform4iv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_1ui(GLint location, GLuint value) { glProgramUniform1ui(m_id, location, value); } void Program::set_uniform_1ui(GLint location, const std::vector<GLuint>& value) { glProgramUniform1uiv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_2ui(GLint location, const std::array<GLuint, 2>& value) { glProgramUniform2ui(m_id, location, value[0], value[1]); } void Program::set_uniform_2ui(GLint location, const std::vector<GLuint>& value) { glProgramUniform2uiv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_3ui(GLint location, const std::array<GLuint, 3>& value) { glProgramUniform3ui(m_id, location, value[0], value[1], value[2]); } void Program::set_uniform_3ui(GLint location, const std::vector<GLuint>& value) { glProgramUniform3uiv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_4ui(GLint location, const std::array<GLuint, 4>& value) { glProgramUniform4ui(m_id, location, value[0], value[1], value[2], value[3]); } void Program::set_uniform_4ui(GLint location, const std::vector<GLuint>& value) { glProgramUniform4uiv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_1f(GLint location, GLfloat value) { glProgramUniform1f(m_id, location, value); } void Program::set_uniform_1f(GLint location, const std::vector<GLfloat>& value) { glProgramUniform1fv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_2f(GLint location, const std::array<GLfloat, 2>& value) { glProgramUniform2f(m_id, location, value[0], value[1]); } void Program::set_uniform_2f(GLint location, const std::vector<GLfloat>& value) { glProgramUniform2fv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_3f(GLint location, const std::array<GLfloat, 3>& value) { glProgramUniform3f(m_id, location, value[0], value[1], value[2]); } void Program::set_uniform_3f(GLint location, const std::vector<GLfloat>& value) { glProgramUniform3fv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_4f(GLint location, const std::array<GLfloat, 4>& value) { glProgramUniform4f(m_id, location, value[0], value[1], value[2], value[3]); } void Program::set_uniform_4f(GLint location, const std::vector<GLfloat>& value) { glProgramUniform4fv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_1d(GLint location, GLdouble value) { glProgramUniform1d(m_id, location, value); } void Program::set_uniform_1d(GLint location, const std::vector<GLdouble>& value) { glProgramUniform1dv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_2d(GLint location, const std::array<GLdouble, 2>& value) { glProgramUniform2d(m_id, location, value[0], value[1]); } void Program::set_uniform_2d(GLint location, const std::vector<GLdouble>& value) { glProgramUniform2dv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_3d(GLint location, const std::array<GLdouble, 3>& value) { glProgramUniform3d(m_id, location, value[0], value[1], value[2]); } void Program::set_uniform_3d(GLint location, const std::vector<GLdouble>& value) { glProgramUniform3dv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } void Program::set_uniform_4d(GLint location, const std::array<GLdouble, 4>& value) { glProgramUniform4d(m_id, location, value[0], value[1], value[2], value[3]); } void Program::set_uniform_4d(GLint location, const std::vector<GLdouble>& value) { glProgramUniform4dv(m_id, location, static_cast<GLsizei>(value.size()), value.data()); } GLint Program::get_parameter(GLenum parameter) const { GLint result; glGetProgramiv(m_id, parameter, &result); return result; } } // namespace gl
RAMFS_COPY_BIN='osafeloader oseama otrx truncate' PART_NAME=firmware BCM53XX_FW_FORMAT= BCM53XX_FW_BOARD_ID= BCM53XX_FW_INT_IMG_FORMAT= BCM53XX_FW_INT_IMG_TRX_OFFSET= BCM53XX_FW_INT_IMG_EXTRACT_CMD= LXL_FLAGS_VENDOR_LUXUL=0x00000001 # $(1): file to read magic from # $(2): offset in bytes get_magic_long_at() { dd if="$1" skip=$2 bs=1 count=4 2>/dev/null | hexdump -v -e '1/1 "%02x"' } # $(1): file to read LE long number from # $(2): offset in bytes get_le_long_at() { echo $((0x$(dd if="$1" skip=$2 bs=1 count=4 2>/dev/null | hexdump -v -e '1/4 "%02x"'))) } platform_flash_type() { # On NAND devices "rootfs" is UBI volume, so won't be find in /proc/mtd grep -q "\"rootfs\"" /proc/mtd && { echo "serial" return } echo "nand" } platform_expected_image() { local machine=$(board_name) case "$machine" in "dlink,dir-885l") echo "seamaseal wrgac42_dlink.2015_dir885l"; return;; "luxul,abr-4500-v1") echo "lxl ABR-4500"; return;; "luxul,xap-810-v1") echo "lxl XAP-810"; return;; "luxul,xap-1410v1") echo "lxl XAP-1410"; return;; "luxul,xap-1440-v1") echo "lxl XAP-1440"; return;; "luxul,xap-1510v1") echo "lxl XAP-1510"; return;; "luxul,xap-1610-v1") echo "lxl XAP-1610"; return;; "luxul,xbr-4500-v1") echo "lxl XBR-4500"; return;; "luxul,xwc-1000") echo "lxl XWC-1000"; return;; "luxul,xwc-2000-v1") echo "lxl XWC-2000"; return;; "luxul,xwr-1200v1") echo "lxl XWR-1200"; return;; "luxul,xwr-3100v1") echo "lxl XWR-3100"; return;; "luxul,xwr-3150-v1") echo "lxl XWR-3150"; return;; "netgear,r6250v1") echo "chk U12H245T00_NETGEAR"; return;; "netgear,r6300v2") echo "chk U12H240T00_NETGEAR"; return;; "netgear,r7000") echo "chk U12H270T00_NETGEAR"; return;; "netgear,r7900") echo "chk U12H315T30_NETGEAR"; return;; "netgear,r8000") echo "chk U12H315T00_NETGEAR"; return;; "netgear,r8500") echo "chk U12H334T00_NETGEAR"; return;; "tplink,archer-c9-v1") echo "safeloader"; return;; esac } platform_identify() { local magic magic=$(get_magic_long "$1") case "$magic" in "48445230") BCM53XX_FW_FORMAT="trx" return ;; "2a23245e") local header_len=$((0x$(get_magic_long_at "$1" 4))) local board_id_len=$(($header_len - 40)) BCM53XX_FW_FORMAT="chk" BCM53XX_FW_BOARD_ID=$(dd if="$1" skip=40 bs=1 count=$board_id_len 2>/dev/null | hexdump -v -e '1/1 "%c"') BCM53XX_FW_INT_IMG_FORMAT="trx" BCM53XX_FW_INT_IMG_TRX_OFFSET="$header_len" BCM53XX_FW_INT_IMG_EXTRACT_CMD="dd skip=$header_len iflag=skip_bytes" return ;; "4c584c23") local hdr_len=$(get_le_long_at "$1" 8) local flags=$(get_le_long_at "$1" 12) [ $((flags & LXL_FLAGS_VENDOR_LUXUL)) -gt 0 ] && notify_firmware_no_backup BCM53XX_FW_FORMAT="lxl" BCM53XX_FW_BOARD_ID=$(dd if="$1" skip=16 bs=1 count=16 2>/dev/null | hexdump -v -e '1/1 "%c"') BCM53XX_FW_INT_IMG_FORMAT="trx" BCM53XX_FW_INT_IMG_TRX_OFFSET="$hdr_len" BCM53XX_FW_INT_IMG_EXTRACT_CMD="dd skip=$hdr_len iflag=skip_bytes" return ;; "5ea3a417") BCM53XX_FW_FORMAT="seamaseal" BCM53XX_FW_BOARD_ID=$(oseama info "$1" | grep "Meta entry:.*signature=" | sed "s/.*=//") BCM53XX_FW_INT_IMG_EXTRACT_CMD="oseama extract - -e 0" return ;; esac magic=$(get_magic_long_at "$1" 14) [ "$magic" = "55324e44" ] && { BCM53XX_FW_FORMAT="cybertan" BCM53XX_FW_BOARD_ID=$(dd if="$1" bs=1 count=4 2>/dev/null | hexdump -v -e '1/1 "%c"') BCM53XX_FW_INT_IMG_FORMAT="trx" BCM53XX_FW_INT_IMG_TRX_OFFSET="32" BCM53XX_FW_INT_IMG_EXTRACT_CMD="dd skip=32 iflag=skip_bytes" return } magic=$(get_magic_long_at "$1" 60) [ "$magic" = "4c584c23" ] && { notify_firmware_no_backup BCM53XX_FW_FORMAT="lxlold" BCM53XX_FW_BOARD_ID=$(dd if="$1" skip=48 bs=1 count=12 2>/dev/null | hexdump -v -e '1/1 "%c"') BCM53XX_FW_INT_IMG_FORMAT="trx" BCM53XX_FW_INT_IMG_TRX_OFFSET="64" BCM53XX_FW_INT_IMG_EXTRACT_CMD="dd skip=64 iflag=skip_bytes" return } if osafeloader info "$1" > /dev/null 2>&1; then BCM53XX_FW_FORMAT="safeloader" return fi } platform_other_check_image() { [ "$#" -gt 1 ] && return 1 local error=0 platform_identify "$1" [ -z "$BCM53XX_FW_FORMAT" ] && { echo "Invalid image type. Please use firmware specific for this device." notify_firmware_broken return 1 } echo "Found $BCM53XX_FW_FORMAT firmware for device $BCM53XX_FW_BOARD_ID" local expected_image="$(platform_expected_image)" local tmp_format=$BCM53XX_FW_FORMAT [ "$tmp_format" = "lxlold" ] && tmp_format="lxl" [ -n "$expected_image" -a -n "$BCM53XX_FW_BOARD_ID" -a "$expected_image" != "$tmp_format $BCM53XX_FW_BOARD_ID" ] && { echo "Firmware doesn't match device ($expected_image)" error=1 } case "$BCM53XX_FW_FORMAT" in "seamaseal") $(oseama info "$1" -e 0 | grep -q "Meta entry:.*type=firmware") || { echo "Seama seal doesn't contain firmware entity" error=1 } ;; "trx") if ! otrx check "$1"; then echo "Failed to find a valid TRX in firmware" notify_firmware_test_result "trx_valid" 0 error=1 else notify_firmware_test_result "trx_valid" 1 fi [ "$expected_image" == "safeloader" ] && { echo "This device expects SafeLoader format and may not work with TRX" error=1 } ;; *) case "$BCM53XX_FW_INT_IMG_FORMAT" in "trx") # Make sure that both ways of extracting TRX work. # platform_do_upgrade() may use any of them. if ! otrx check "$1" -o "$BCM53XX_FW_INT_IMG_TRX_OFFSET" || \ ! $BCM53XX_FW_INT_IMG_EXTRACT_CMD < $1 | otrx check -; then echo "Invalid (corrupted?) TRX firmware" notify_firmware_test_result "trx_valid" 0 error=1 else notify_firmware_test_result "trx_valid" 1 fi ;; esac ;; esac return $error } platform_check_image() { case "$(board_name)" in meraki,mr32) # Ideally, REQUIRE_IMAGE_METADATA=1 would suffice # but this would require converting all other # devices too. nand_do_platform_check meraki-mr32 "$1" return $? ;; *) platform_other_check_image "$1" return $? ;; esac return 1 } # $(1): TRX image or firmware containing TRX # $(2): offset of TRX in firmware (optional) platform_do_upgrade_nand_trx() { local dir="/tmp/sysupgrade-bcm53xx" local trx="$1" local offset="$2" # Extract partitions from trx rm -fR $dir mkdir -p $dir otrx extract "$trx" \ ${offset:+-o $offset} \ -1 $dir/kernel \ -2 $dir/root [ $? -ne 0 ] && { echo "Failed to extract TRX partitions." return } # Firmwares without UBI image should be flashed "normally" local root_type=$(identify $dir/root) [ "$root_type" != "ubi" ] && { echo "Provided firmware doesn't use UBI for rootfs." return } # Prepare TRX file with just a kernel that will replace current one local linux_length=$(grep "\"linux\"" /proc/mtd | sed "s/mtd[0-9]*:[ \t]*\([^ \t]*\).*/\1/") [ -z "$linux_length" ] && { echo "Unable to find \"linux\" partition size" exit 1 } linux_length=$((0x$linux_length)) local kernel_length=$(wc -c $dir/kernel | cut -d ' ' -f 1) [ $kernel_length -gt $linux_length ] && { echo "New kernel doesn't fit \"linux\" partition." return } rm -f /tmp/null.bin rm -f /tmp/kernel.trx touch /tmp/null.bin otrx create /tmp/kernel.trx \ -f $dir/kernel -b $(($linux_length + 28)) \ -f /tmp/null.bin [ $? -ne 0 ] && { echo "Failed to create simple TRX with new kernel." return } # Prepare UBI image (drop unwanted extra blocks) local ubi_length=0 while [ "$(dd if=$dir/root skip=$ubi_length bs=1 count=4 2>/dev/null)" = "UBI#" ]; do ubi_length=$(($ubi_length + 131072)) done truncate -s $ubi_length $dir/root [ $? -ne 0 ] && { echo "Failed to prepare new UBI image." return } # Flash mtd write /tmp/kernel.trx firmware || exit 1 nand_do_upgrade $dir/root } platform_do_upgrade_nand_seamaseal() { local dir="/tmp/sysupgrade-bcm53xx" local seamaseal="$1" local tmp # Extract Seama entity from Seama seal rm -fR $dir mkdir -p $dir oseama extract "$seamaseal" \ -e 0 \ -o $dir/seama.entity [ $? -ne 0 ] && { echo "Failed to extract Seama entity." return } local entity_size=$(wc -c $dir/seama.entity | cut -d ' ' -f 1) local ubi_offset=0 tmp=0 while [ 1 ]; do [ $tmp -ge $entity_size ] && break [ "$(dd if=$dir/seama.entity skip=$tmp bs=1 count=4 2>/dev/null)" = "UBI#" ] && { ubi_offset=$tmp break } tmp=$(($tmp + 131072)) done [ $ubi_offset -eq 0 ] && { echo "Failed to find UBI in Seama entity." return } local ubi_length=0 while [ "$(dd if=$dir/seama.entity skip=$(($ubi_offset + $ubi_length)) bs=1 count=4 2>/dev/null)" = "UBI#" ]; do ubi_length=$(($ubi_length + 131072)) done dd if=$dir/seama.entity of=$dir/kernel.seama bs=131072 count=$(($ubi_offset / 131072)) 2>/dev/null dd if=$dir/seama.entity of=$dir/root.ubi bs=131072 skip=$(($ubi_offset / 131072)) count=$(($ubi_length / 131072)) 2>/dev/null # Flash local kernel_size=$(sed -n 's/mtd[0-9]*: \([0-9a-f]*\).*"\(kernel\|linux\)".*/\1/p' /proc/mtd) mtd write $dir/kernel.seama firmware || exit 1 mtd ${kernel_size:+-c 0x$kernel_size} fixseama firmware nand_do_upgrade $dir/root.ubi } platform_img_from_safeloader() { local dir="/tmp/sysupgrade-bcm53xx" # Extract partitions from SafeLoader rm -fR $dir mkdir -p $dir osafeloader extract "$1" \ -p "os-image" \ -o $dir/os-image osafeloader extract "$1" \ -p "file-system" \ -o $dir/file-system mtd write $dir/file-system rootfs echo -n $dir/os-image } platform_other_do_upgrade() { platform_identify "$1" [ "$(platform_flash_type)" == "nand" ] && { # Try NAND-aware upgrade case "$BCM53XX_FW_FORMAT" in "seamaseal") platform_do_upgrade_nand_seamaseal "$1" ;; "trx") platform_do_upgrade_nand_trx "$1" ;; *) case "$BCM53XX_FW_INT_IMG_FORMAT" in "trx") platform_do_upgrade_nand_trx "$1" "$BCM53XX_FW_INT_IMG_TRX_OFFSET" ;; *) echo "NAND aware sysupgrade is unsupported for $BCM53XX_FW_FORMAT format" ;; esac ;; esac # Above calls exit on success. # If we got here something went wrong. echo "Writing whole image to NAND flash. All erase counters will be lost." } case "$BCM53XX_FW_FORMAT" in "safeloader") PART_NAME=os-image img=$(platform_img_from_safeloader "$1") default_do_upgrade "$img" ;; "seamaseal") default_do_upgrade "$1" "$BCM53XX_FW_INT_IMG_EXTRACT_CMD" ;; "trx") default_do_upgrade "$1" ;; *) case "$BCM53XX_FW_INT_IMG_FORMAT" in "trx") default_do_upgrade "$1" "$BCM53XX_FW_INT_IMG_EXTRACT_CMD" ;; esac ;; esac } platform_do_upgrade() { case "$(board_name)" in meraki,mr32) CI_KERNPART="part.safe" nand_do_upgrade "$1" ;; *) platform_other_do_upgrade "$1" ;; esac }
// Tag class to be implemented public class Tag { private Dictionary<string, string> memberDescriptions = new Dictionary<string, string>(); public static Tag Create<T>(string description) { // Create a new instance of the Tag class and set the tag description Tag tag = new Tag(); tag.Description = description; return tag; } public string Description { get; set; } public MemberInfo<TMember> Member<TMember>(Expression<Func<T, TMember>> memberSelector) { // Retrieve the member name from the lambda expression string memberName = ((MemberExpression)memberSelector.Body).Member.Name; // Create a new MemberInfo instance and set the member description MemberInfo<TMember> memberInfo = new MemberInfo<TMember>(memberName, this); memberDescriptions.TryGetValue(memberName, out string description); memberInfo.Description = description; return memberInfo; } public void SetMemberDescription<TMember>(Expression<Func<T, TMember>> memberSelector, string description) { string memberName = ((MemberExpression)memberSelector.Body).Member.Name; memberDescriptions[memberName] = description; } } // MemberInfo class to represent a member of the tag public class MemberInfo<TMember> { private Tag tag; public MemberInfo(string memberName, Tag tag) { MemberName = memberName; this.tag = tag; } public string MemberName { get; } public string Description { get; set; } }
OUT=./gen/go PROTOS=./protos # Importing the commons functions . ./test_commons.sh gen_go() { # shellcheck source=src/lib.sh mkdir -p ${OUT} rm -rf "${OUT:?}/*" protoc -I=${PROTOS} --go_out=plugins=grpc:${OUT} ${PROTOS}/* } gen_go check_file "${OUT}/cart.pb.go" "Go"