text
stringlengths
1
1.05M
SCRIPT_NAME=elf OUTPUT_FORMAT="elf32-s390" TEXT_START_ADDR=0x00400000 MAXPAGESIZE=0x1000 NONPAGED_TEXT_START_ADDR=0x00400000 ARCH="s390:31-bit" MACHINE= NOP=0x07070707 TEMPLATE_NAME=elf32 GENERATE_SHLIB_SCRIPT=yes
package com.designre.blog.service; import com.baomidou.mybatisplus.extension.service.IService; import com.designre.blog.model.dto.CategoryInfoDto; import com.designre.blog.model.entity.Category; import com.designre.blog.model.param.SaveCategoryParam; import java.util.List; public interface CategoryService extends IService<Category> { void delete(Integer id); Category createOrUpdate(SaveCategoryParam param); List<CategoryInfoDto> listCategoryInfo(boolean isFront); }
<filename>java/ql/test/library-tests/dependency-counts/Example.java import java.util.Set; import java.util.List; public interface Example <A> extends Set<List<A>> { public interface InnerExample extends Example<Set> { } }
#! /bin/bash # Display system date and time echo "Current date & time: $(date)" # Display system information echo "System: $(uname -a)" # Display user information echo "Logged in user: $(whoami)" # Display cpu information echo "CPU $(cat /proc/cpuinfo)" # Display memory information echo "Memory $(free -m)" # Display disk space echo "Disk Space $(df)"
import { AdapterContext } from '@chainlink/types' import { getEnv, buildUrlPath, buildUrl, baseEnvDefaults } from '../../src/lib/util' describe('utils', () => { let oldEnv beforeEach(() => { oldEnv = process.env }) afterEach(() => { process.env = oldEnv }) describe('getEnv', () => { it('fetches the correct environment variable', () => { process.env.TEST = 'test' const actual = getEnv('TEST') expect(actual).toEqual('test') }) it('ignores empty string environment variables', () => { process.env.TEST = '' const actual = getEnv('TEST') expect(actual).toBeUndefined() }) it('prefers user-specified env vars over bootstrap base defaults', () => { process.env.WS_ENABLED = 'true' const actual = getEnv('WS_ENABLED') expect(baseEnvDefaults.WS_ENABLED).toEqual('false') expect(actual).toEqual('true') }) it('prefers EA default overrides over bootstrap base defaults', () => { const adapterContext: AdapterContext = { envDefaultOverrides: { WS_ENABLED: 'true' } } const actual = getEnv('WS_ENABLED', undefined, adapterContext) expect(baseEnvDefaults.WS_ENABLED).toEqual('false') expect(actual).toEqual('true') }) it('prefers user-specified env vars over EA default overrides', () => { process.env.WS_ENABLED = 'true' const adapterContext: AdapterContext = { envDefaultOverrides: { WS_ENABLED: 'false' } } const actual = getEnv('WS_ENABLED', undefined, adapterContext) expect(actual).toEqual('true') }) it('defaults to bootstrap base defaults when user-specified env vars are undefined', () => { process.env.WS_ENABLED = '' const actual = getEnv('WS_ENABLED') expect(baseEnvDefaults.WS_ENABLED).toEqual('false') expect(actual).toEqual('false') }) it('defaults to EA default overrides when user-specified env vars are undefined but overrides are present', () => { process.env.WS_ENABLED = '' const adapterContext: AdapterContext = { envDefaultOverrides: { WS_ENABLED: 'true' } } const actual = getEnv('WS_ENABLED', undefined, adapterContext) expect(baseEnvDefaults.WS_ENABLED).toEqual('false') expect(actual).toEqual('true') }) }) describe(`buildUrlPath`, () => { it(`builds path with valid characters`, () => { const actual = buildUrlPath('/from/:from/to/:to', { from: 'ETH', to: 'USD', }) expect(actual).toEqual('/from/ETH/to/USD') }) it(`builds path with whitelisted & non-whitelisted characters`, () => { const actual = buildUrlPath( '/from/:from/to/:to', { from: 'E:T?H', to: 'U%S\\D !', }, ':%^ !', ) expect(actual).toEqual('/from/E:T%3FH/to/U%S%5CD !') }) it(`returns empty string from empty path`, () => { const actual = buildUrlPath('', { from: 'ETH', to: 'USD', message: 'hello_world' }) expect(actual).toEqual('') }) it(`builds path with no params`, () => { const actual = buildUrlPath('/from/to') expect(actual).toEqual('/from/to') }) it(`builds path with reserved characters`, () => { const actual = buildUrlPath('/from/:from/to/:to', { from: 'ETH:USD', to: 'USD/?ETH=USD', }) expect(actual).toEqual('/from/ETH%3AUSD/to/USD%2F%3FETH%3DUSD') }) it(`builds path with unsafe characters`, () => { const actual = buildUrlPath('/from/:from/to/:to', { from: 'ETH"USD"', to: '{U|S|D>', }) expect(actual).toEqual('/from/ETH%22USD%22/to/%7BU%7CS%7CD%3E') expect(decodeURI(actual)).toEqual('/from/ETH"USD"/to/{U|S|D>') }) it(`builds path with non-latin characters`, () => { const actual = buildUrlPath('/from/:from/to/:to', { from: 'abcÂÃ', to: '你好世界', }) expect(actual).toEqual('/from/abc%C3%82%C3%83/to/%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C') expect(decodeURI(actual)).toEqual('/from/abcÂÃ/to/你好世界') }) it(`builds path with ':' in string & values`, () => { const actual = buildUrlPath('/price/:from::to', { from: 'ETH', to: 'USD' }) expect(actual).toEqual('/price/ETH:USD') }) }) describe(`buildUrl`, () => { it(`builds URL with a given base, path & params`, () => { const baseWsURL = 'wss://example.com:8000' const asset = 'BTC' const metrics = 'hello' const key = 123456 const expected = `${baseWsURL}/timeseries-stream/asset-metrics/assets/${asset}/metrics/${metrics}/frequency/1s/api_key/${key}` const actual = buildUrl( baseWsURL, '/timeseries-stream/asset-metrics/assets/:assets/metrics/:metrics/frequency/:frequency/api_key/:api_key', { assets: asset, metrics: metrics, frequency: '1s', api_key: key, }, ) expect(actual).toEqual(expected) }) it(`builds URL with a given base & path only`, () => { const baseWsURL = 'wss://example.com:8000' const expected = `${baseWsURL}/timeseries-stream/asset-metrics` const actual = buildUrl(baseWsURL, '/timeseries-stream/asset-metrics') expect(actual).toEqual(expected) }) it(`builds URL with basic auth (key:secret)`, () => { const withApiKey = (url: string, key: string, secret: string) => buildUrl(url, '/client/:client', { client: `${key}:${secret}` }, ':') const expected = `wss://stream.tradingeconomics.com/client/keystring:secretstring` const actual = withApiKey('wss://stream.tradingeconomics.com', 'keystring', 'secretstring') expect(actual).toEqual(expected) }) }) })
<filename>src/App.tsx import './global.custom.scss'; import { useLocalStorageState, useMount } from 'ahooks'; import classNames from 'classnames'; import React from 'react'; import { connect } from 'react-redux'; import Footer from '@/components/Footer'; import Main from '@/components/Main'; import Nav from '@/components/Nav'; import s from './App.scss'; import BackToTop from './components/BackToTop'; import { setMode } from './redux/actions'; import { storeState } from './redux/interface'; interface Props { mode?: number; setMode?: Function; } const App: React.FC<Props> = ({ mode, setMode }) => { const bgClasses = [s.bg0, s.bg1, s.bg2]; const [localMode] = useLocalStorageState('localMode'); useMount(() => { if (localMode !== undefined) { setMode?.(localMode); } }); return ( <div className={classNames(s.AppBox, bgClasses[mode!])}> <Nav /> <Main /> <Footer /> <BackToTop /> </div> ); }; export default connect( (state: storeState) => ({ mode: state.mode }), { setMode } )(App);
package managers; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; import java.sql.PreparedStatement; import model.Boss; import model.Constants.DKPEventType; import model.Constants; import model.Constants.Difficulty; import model.Constants.WOWCharacterClass; import model.DKPEvent; import model.Item; import model.NotEnoughDKPException; import model.WOWCharacter; public class MySQLManager extends AbstractManager { private Connection conn = null; private Statement stmt = null; private Statement charStmt = null; private Statement eventStmt = null; private Statement itemStmt = null; private PreparedStatement insertCharacter = null; private PreparedStatement insertDKPEvent = null; private PreparedStatement insertItem = null; public MySQLManager() { } private void startConnection() throws ClassNotFoundException, SQLException { Class.forName(ConnectionConstants.JDBC_DRIVER); conn = DriverManager.getConnection(ConnectionConstants.DB_URL, ConnectionConstants.USER, ConnectionConstants.PASSWD); } private void closeConnection() { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } if (insertCharacter != null) { insertCharacter.close(); } if (insertDKPEvent != null) { insertDKPEvent.close(); } if (insertItem != null) { insertItem.close(); } if (charStmt != null) { charStmt.close(); } if (eventStmt != null) { eventStmt.close(); } if (itemStmt != null) { itemStmt.close(); } } catch (SQLException e) { e.printStackTrace(); } } @Override public void saveData(List<WOWCharacter> characters) { // Clear database clearDatabase(); // save data try { startConnection(); stmt = conn.createStatement(); List<DKPEvent> eventList; int nextCharacterId; int nextDKPEventId; int nextItemId; nextCharacterId = getNextAutoIncrementId(stmt, "wowcharacter"); nextDKPEventId = getNextAutoIncrementId(stmt, "dkpevent"); nextItemId = getNextAutoIncrementId(stmt, "item"); for (WOWCharacter c : characters) { // Save character saveCharacter(c); ++nextCharacterId; // Save all dkp event under this character eventList = c.getEventList(); boolean firstEvent = true; boolean hasItem; for (DKPEvent e : eventList) { if (e.getItem() != null) { saveItem(e.getItem()); ++nextItemId; hasItem = true; } else { hasItem = false; } saveDKPEvent(e, nextCharacterId - 1, firstEvent ? -1 : nextDKPEventId - 1, hasItem ? nextItemId - 1 : -1); } } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } finally { closeConnection(); } } @Override public List<WOWCharacter> loadData() { List<WOWCharacter> characters = new LinkedList<WOWCharacter>(); try { startConnection(); stmt = conn.createStatement(); charStmt = conn.createStatement(); eventStmt = conn.createStatement(); itemStmt = conn.createStatement(); ResultSet rs = charStmt .executeQuery("SELECT * FROM `wowcharacter`"); ResultSet dkpeventRs; String cName; String cRealm; WOWCharacterClass cClass; int cid; WOWCharacter tmpC; while (rs.next()) { cName = rs.getString("name"); cRealm = rs.getString("realm"); cid = rs.getInt("id"); cClass = WOWCharacterClass.valueOf(rs.getString("class")); tmpC = new WOWCharacter(cName, cRealm, cClass); // get all dkp event for this character dkpeventRs = eventStmt .executeQuery("SELECT * FROM `dkpevent` WHERE `charId`=" + cid + " ORDER BY `lastId`"); addEventToCharacter(dkpeventRs, tmpC); characters.add(tmpC); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { closeConnection(); } return characters; } private void addEventToCharacter(ResultSet rs, WOWCharacter c) throws SQLException { DKPEvent e; if (rs.next()) { int score = rs.getInt("score"); DKPEventType type = DKPEventType.valueOf(rs.getString("type")); String bossName = rs.getString("bossName"); Boss boss = null; if (!bossName.equals("-")) { boss = Constants.bossMap.get(rs.getString("bossName")); } Difficulty difficulty = Difficulty.valueOf(rs .getString("difficulty")); String description = rs.getString("description"); int itemId = rs.getInt("itemId"); Item item = null; if (itemId != -1) { item = loadItem(itemId); } e = new DKPEvent(score, type, description, c, item, boss, difficulty); try { c.addDKPEvent(e); } catch (NotEnoughDKPException e1) { // This shouldn't happen e1.printStackTrace(); } addEventToCharacter(rs, c); } } private Item loadItem(int itemId) throws SQLException { ResultSet rs = itemStmt.executeQuery("SELECT * FROM `item` WHERE `id`=" + itemId + ""); if (rs.next()) { int inGameId = rs.getInt("inGameId"); String name = rs.getString("name"); return new Item(inGameId, name); } else { return null; } } private void saveCharacter(WOWCharacter c) throws SQLException { insertCharacter = conn .prepareStatement(ConnectionConstants.INSERT_CHARACTER); insertCharacter.setString(1, c.getName()); insertCharacter.setString(2, c.getRealm()); insertCharacter.setString(3, c.getWOWCharacterClass().name()); insertCharacter.executeUpdate(); } private void saveItem(Item e) throws SQLException { insertItem = conn.prepareStatement(ConnectionConstants.INSERT_ITEM); insertItem.setString(1, e.getName()); insertItem.setInt(2, 0); insertItem.executeUpdate(); } private void saveDKPEvent(DKPEvent e, int charId, int lastId, int itemId) throws SQLException { // if the value of lastId or itemId happened to be negative number, // then means no last event or no item for this event. insertDKPEvent = conn .prepareStatement(ConnectionConstants.INSERT_DKPEVENT); insertDKPEvent.setInt(1, charId); insertDKPEvent.setInt(2, lastId); insertDKPEvent.setInt(3, itemId); insertDKPEvent.setString(4, e.getType().name()); insertDKPEvent.setString(5, e.getBoss() == null ? "-" : e.getBoss() .getName()); insertDKPEvent.setString(6, e.getBoss() == null ? "-" : e.getBoss() .getRaid()); insertDKPEvent.setInt(7, e.getScore()); insertDKPEvent.setString(8, e.getDescription()); insertDKPEvent.setString(9, e.getDifficulty().name()); insertDKPEvent.executeUpdate(); } private int getNextAutoIncrementId(Statement st, String tableName) throws SQLException { // assume connection has already been started String sql = "SHOW TABLE STATUS LIKE \"" + tableName + "\""; ResultSet rs = st.executeQuery(sql); if (rs.next()) { return rs.getInt("Auto_increment"); } else { return -1; } } public void clearDatabase() { try { startConnection(); stmt = conn.createStatement(); String sql = "TRUNCATE `wowcharacter`"; stmt.executeUpdate(sql); sql = "TRUNCATE `item`"; stmt.executeUpdate(sql); sql = "TRUNCATE `dkpevent`"; stmt.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { closeConnection(); } } }
#! /bin/bash set -ex # Get the height parameter from the command line argument. height=${1-0} addr=$(cat t1/8000/ag-cosmos-helper-address) hex=$(ag-cosmos-helper keys parse $addr --output=json | jq -r '.bytes') b64=$(echo $hex | xxd -r -p | base64 | tr '+/' '-_') # echo $b64 # Query the bank balance of (potentially) an empty account server=http://localhost:1317 url="$server/bank/balances/$addr?height=$height" #url="$server/agoric/swingset/egress/$b64" #url=$server/agoric/swingset/storage/data/activityhash # Display the output of a single request: curl "$url" # Run the Apache Benchmark: ab -n 16000 -c 5 "$url" { sleep 1; : NOTE: This will time out because of rate limiting; } & # This one hangs (because of rate limiting at around 16350 requests since the # last one started): ab -n 3000 -c 5 "$url"
def update_production_schedule(values, workorder): if 'date_planned_finished' in values: planned_finish_date = values['date_planned_finished'] workorder.production_id.with_context(force_date=True).write({ 'date_planned_finished': fields.Datetime.to_datetime(planned_finish_date) })
def process_command(command): if command == "start": print("Starting the process") elif command == "build": print("Building the project") else: print("Error: Invalid command") # Main program while True: user_input = input("Enter a command: ") process_command(user_input)
<filename>cmd/gocve/cli/list.go<gh_stars>1-10 // +build linux,amd64 darwin,amd64 package cli import ( "fmt" "log" dbWrapper "github.com/jimmyislive/gocve/internal/pkg/db" "github.com/spf13/cobra" "github.com/spf13/viper" ) var listCmd = &cobra.Command{ Use: "list", Short: "Lists all cve ids", Long: `Lists all cve ids`, Run: func(cmd *cobra.Command, args []string) { v := viper.New() cfg, err := initConfig(v) if err != nil { log.Fatal(err) } records := dbWrapper.ListCVE(cfg) for i := 0; i < len(records); i++ { max := len(records[i][1]) if max > 100 { max = 100 } fmt.Println(records[i][0], "\t", records[i][1][:max]) } }, }
<filename>redis/src/test/java/org/grain/redis/RedisManagerTest.java //package org.grain.redis; // //import static org.junit.Assert.assertEquals; // //import org.junit.BeforeClass; //import org.junit.Test; // //public class RedisManagerTest { // // @BeforeClass // public static void setUpBeforeClass() throws Exception { // RedisManager.init("127.0.0.1", 6379, null); // } // // @Test // public void testSetStringValue() { // RedisManager.setStringValue("111", "222"); // String str = RedisManager.getStringValue("111"); // assertEquals(true, (str != null && str.equals("222"))); // } // // @Test // public void testSetObjValue() { // RedisTest test = new RedisTest("3333", "4444"); // RedisManager.setObjValue("3333", test); // RedisTest test1 = (RedisTest) RedisManager.getObjValue("3333"); // assertEquals(true, test1 != null); // } // //}
<filename>public/assets/admin_asset/js/app/charts/easy-pie.js (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"./lib/charts/js/easy-pie/main.js":[function(require,module,exports){ require('./_easy-pie'); },{"./_easy-pie":"/Code/html/themes/themekit/lib/charts/js/easy-pie/_easy-pie.js"}],"/Code/html/themes/themekit/lib/charts/js/easy-pie/_easy-pie.js":[function(require,module,exports){ (function ($) { "use strict"; var skin = require('../lib/_skin')(); /** * jQuery plugin wrapper for compatibility with Angular UI.Utils: jQuery Passthrough */ $.fn.tkEasyPie = function () { if (! this.length) return; if (!$.fn.easyPieChart) return; var color = config.skins[ skin ][ 'primary-color' ]; if (this.is('.info')) color = colors[ 'info-color' ]; if (this.is('.danger')) color = colors[ 'danger-color' ]; if (this.is('.success')) color = colors[ 'success-color' ]; if (this.is('.warning')) color = colors[ 'warning-color' ]; if (this.is('.inverse')) color = colors[ 'inverse-color' ]; this.easyPieChart({ barColor: color, animate: ($('html').is('.ie') ? false : 3000), lineWidth: 4, size: 50 }); }; $.each($('.easy-pie'), function (k, v) { $(this).tkEasyPie(); }); })(jQuery); },{"../lib/_skin":"/Code/html/themes/themekit/lib/charts/js/lib/_skin.js"}],"/Code/html/themes/themekit/lib/charts/js/lib/_skin.js":[function(require,module,exports){ module.exports = (function () { var skin = $.cookie('skin'); if (typeof skin == 'undefined') { skin = 'default'; } return skin; }); },{}]},{},["./lib/charts/js/easy-pie/main.js"]);
<filename>src/example-components/BlocksComposed/BlocksComposed3/index.js<gh_stars>0 import React, { useState } from 'react'; import clsx from 'clsx'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Card, CardContent, Button, Tooltip, TextField } from '@material-ui/core'; import PerfectScrollbar from 'react-perfect-scrollbar'; import avatar3 from '../../../assets/images/avatars/avatar3.jpg'; import avatar7 from '../../../assets/images/avatars/avatar7.jpg'; import people2 from '../../../assets/images/stock-photos/people-2.jpg'; import people1 from '../../../assets/images/stock-photos/people-1.jpg'; export default function LivePreviewExample() { const [activeTab, setActiveTab] = useState('1'); const toggle = (tab) => { if (activeTab !== tab) setActiveTab(tab); }; const [inputBg, setInputBg] = useState(false); const toggleInputBg = () => setInputBg(!inputBg); return ( <> <Card className="card-box mb-spacing-6-x2"> <div className="card-header"> <div className="card-header--title"> <small>Messenger</small> <b>Talking to Kate</b> </div> <div className="card-header--actions"> <Tooltip title="Send new message" arrow placement="top"> <Button className="btn-neutral-first btn-pill p-0 d-40 btn-icon btn-animated-icon"> <span> <FontAwesomeIcon icon={['fas', 'plus']} className="font-size-sm" /> </span> </Button> </Tooltip> </div> </div> <CardContent> <div className="scroll-area-lg shadow-overflow"> <PerfectScrollbar> <div className="chat-wrapper"> <div className="chat-item p-2 mb-2"> <div className="align-box-row"> <div className="avatar-icon-wrapper avatar-icon-lg align-self-start"> <div className="avatar-icon rounded border-0"> <img alt="..." src={avatar7} /> </div> </div> <div> <div className="chat-box bg-first text-white"> <p>Hello, John.</p> <p>This is Kenny. How are you?</p> </div> <small className="mt-2 d-block text-black-50"> <FontAwesomeIcon icon={['far', 'clock']} className="mr-1 opacity-5" /> 11:01 AM | Yesterday </small> </div> </div> </div> <div className="chat-item chat-item-reverse p-2 mb-2"> <div className="align-box-row flex-row-reverse"> <div className="avatar-icon-wrapper avatar-icon-lg align-self-start"> <div className="avatar-icon rounded border-0"> <img alt="..." src={avatar3} /> </div> </div> <div> <div className="chat-box bg-first text-white"> <p>Hey, Kate.</p> <p>I'm attaching the pictures you requested below:</p> <Card className="mt-3 mb-2 pt-2 pb-2 text-center"> <div> <a href="#/" onClick={(e) => e.preventDefault()}> <img alt="..." className="img-fluid rounded m-1 shadow-sm" src={people1} width="54" /> </a> <a href="#/" onClick={(e) => e.preventDefault()}> <img alt="..." className="img-fluid rounded m-1 shadow-sm" src={people2} width="54" /> </a> </div> </Card> </div> <small className="mt-2 d-block text-black-50"> <FontAwesomeIcon icon={['far', 'clock']} className="mr-1 opacity-5" /> 11:01 AM | Yesterday </small> </div> </div> </div> <div className="chat-item p-2 mb-2"> <div className="align-box-row"> <div className="avatar-icon-wrapper avatar-icon-lg align-self-start"> <div className="avatar-icon rounded border-0"> <img alt="..." src={avatar7} /> </div> </div> <div> <div className="chat-box bg-first text-white"> <p>Thanks.</p> <p>Really appreciate it!</p> </div> <small className="mt-2 d-block text-black-50"> <FontAwesomeIcon icon={['far', 'clock']} className="mr-1 opacity-5" /> 11:01 AM | Yesterday </small> </div> </div> </div> <div className="chat-item p-2 mb-2"> <div className="align-box-row"> <div className="avatar-icon-wrapper avatar-icon-lg align-self-start"> <div className="avatar-icon rounded border-0"> <img alt="..." src={avatar7} /> </div> </div> <div> <div className="chat-box bg-first text-white"> <p>Bye for now, talk to you later.</p> </div> <small className="mt-2 d-block text-black-50"> <FontAwesomeIcon icon={['far', 'clock']} className="mr-1 opacity-5" /> 11:01 AM | Yesterday </small> </div> </div> </div> <div className="chat-item chat-item-reverse p-2 mb-2"> <div className="align-box-row flex-row-reverse"> <div className="avatar-icon-wrapper avatar-icon-lg align-self-start"> <div className="avatar-icon rounded border-0"> <img alt="..." src={avatar3} /> </div> </div> <div> <div className="chat-box bg-first text-white"> <p>Almost forgot about your tasks.</p> <p> <b>Check the links below:</b> </p> <Card className="bg-premium-dark p-1 mt-3 mb-2"> <div className="text-center py-2"> <Tooltip title="Menu example"> <Button className="btn-link p-0 btn-icon bg-ripe-malin d-inline-block text-center text-white font-size-xl d-40 rounded-circle border-0 m-2" id="MenuExampleTooltip111"> <FontAwesomeIcon icon={['far', 'gem']} className="font-size-sm" /> </Button> </Tooltip> <Tooltip title="Menu example"> <Button className="btn-link p-0 btn-icon bg-grow-early d-inline-block text-center text-white font-size-xl d-40 rounded-circle border-0 m-2" id="MenuExampleTooltip118"> <FontAwesomeIcon icon={['far', 'building']} className="font-size-sm" /> </Button> </Tooltip> <Tooltip title="Menu example"> <Button className="btn-link p-0 btn-icon bg-arielle-smile d-inline-block text-center text-white font-size-xl d-40 rounded-circle border-0 m-2" id="MenuExampleTooltip125"> <FontAwesomeIcon icon={['far', 'chart-bar']} className="font-size-sm" /> </Button> </Tooltip> </div> </Card> </div> <small className="mt-2 d-block text-black-50"> <FontAwesomeIcon icon={['far', 'clock']} className="mr-1 opacity-5" /> 11:03 AM | Yesterday </small> </div> </div> </div> </div> </PerfectScrollbar> </div> </CardContent> <div className="card-footer p-0"> <div className={clsx( 'd-block d-md-flex text-center text-md-left transition-base align-items-center justify-content-between py-3 px-4', { 'bg-secondary': !inputBg } )}> <div> <Button size="small" className={clsx( 'btn-neutral-dark d-inline-flex mr-2 btn-pill px-3 py-1', { active: activeTab === '1' } )} onClick={() => { toggle('1'); }}> <span className="btn-wrapper--label font-size-xs text-uppercase"> Create Post </span> </Button> <Button size="small" className={clsx( 'btn-neutral-dark d-inline-flex btn-pill px-3 py-1', { active: activeTab === '3' } )} onClick={() => { toggle('3'); }}> <span className="btn-wrapper--label font-size-xs text-uppercase"> Event </span> </Button> </div> <div className="text-black-50 pt-3 pt-md-0 font-size-sm"> Posting as <b className="text-black"><NAME></b> </div> </div> <div className="divider" /> <div className={clsx( 'd-flex align-items-center transition-base px-4 py-3', { 'bg-secondary': inputBg } )}> <div className="avatar-icon-wrapper avatar-initials avatar-icon-lg mr-3"> <div className="avatar-icon text-white bg-second">H</div> <div className="badge badge-success badge-position badge-position--bottom-center badge-circle" title="Badge bottom center"> Online </div> </div> <TextField variant="outlined" size="medium" className="bg-white w-100" classes={{ root: 'input-border-0' }} id="input-with-icon-textfield225-1" placeholder="Write your message here..." onFocus={toggleInputBg} onBlur={toggleInputBg} /> </div> <div className="divider" /> <div className="d-flex align-items-center justify-content-between px-4 py-3"> <div> <Button size="small" className="btn-neutral-warning d-inline-flex mr-2 btn-transition-none btn-pill py-1"> <span className="btn-wrapper--icon"> <FontAwesomeIcon icon={['far', 'file-audio']} /> </span> <span className="btn-wrapper--label font-size-xs font-weight-bold text-uppercase"> Audio </span> </Button> <Button size="small" className="btn-neutral-first d-inline-flex mr-2 btn-transition-none btn-pill py-1"> <span className="btn-wrapper--icon"> <FontAwesomeIcon icon={['far', 'file-video']} /> </span> <span className="btn-wrapper--label font-size-xs font-weight-bold text-uppercase"> Video </span> </Button> <Button size="small" className="btn-neutral-danger d-inline-flex mr-2 btn-transition-none btn-pill py-1"> <span className="btn-wrapper--icon"> <FontAwesomeIcon icon={['far', 'file-excel']} /> </span> <span className="btn-wrapper--label font-size-xs font-weight-bold text-uppercase"> Doc </span> </Button> </div> <div> <Button className="d-inline-flex font-weight-bold font-size-sm text-uppercase btn-primary"> <span className="btn-wrapper--icon"> <FontAwesomeIcon icon={['far', 'envelope']} /> </span> <span className="btn-wrapper--label font-size-xs font-weight-bold text-uppercase"> Send </span> </Button> </div> </div> </div> </Card> </> ); }
if [[ $zabbix_username == "" ]] || [[ $zabbix_password == "" ]]; then echo "Please set vars for zabbix_username and zabbix_password" exit 1 fi if [[ $local_network_ip == "" ]] || [[ $local_network_interface == "" ]] || [[ $zabbix_postgres_ip == "" ]] then echo "Please set vars for both local_network_ip and local_network_interface" exit 1 fi # Extra variables for playbook extra_vars="\ role_sysctl_task=router_sysctl \ zabbix_username=$zabbix_username \ zabbix_password=$zabbix_password \ unbound_address=127.0.0.1 \ local_network_ip=$local_network_ip \ local_network_interface=$local_network_interface \ zabbix_postgres_ip=$zabbix_postgres_ip" # Bootstrap the system ftp -V -o - https://github.com/findelabs/openbsd-ansible-deploy/raw/master/bootstraps/bootstrap_raw.sh | sh # Run playbook cd /root/git/openbsd-ansible-deploy/ && ansible-playbook install.yml --tags=users,system,vnstatd,unbound,sysctl,zabbix-web --extra-vars="$extra_vars"
/* * 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 sdb; import java.lang.reflect.Method; import org.apache.jena.sdb.SDB ; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class sdbscript { private static Logger log = LoggerFactory.getLogger(sdbscript.class) ; public static void main(String... a) { SDB.init(); if ( a.length == 0 ) a = new String[]{ "script.rb" } ; staticByReflection("org.jruby.Main", "main", a) ; } private static void staticByReflection(String className, String methodName, String[] args) { Class<?> cmd = null ; try { cmd = Class.forName(className) ; } catch (ClassNotFoundException ex) { log.error(String.format("Class not found: %s", className)) ; return ; } Method method = null ; try { method = cmd.getMethod(methodName, new Class[]{args.getClass()}) ; } catch (NoSuchMethodException ex) { log.error(String.format("Class '%s' found but not the method '%s'", className, methodName)) ; return ; } try { method.invoke(null, (Object)args) ; } catch (Exception ex) { log.error(String.format("Exception invoking '%s.%s'", className, methodName), ex) ; return ; } } }
/** * Author: <NAME> <<EMAIL>> * Copyright (c) 2020 Gothel Software e.K. * Copyright (c) 2020 ZAFENA AB * * 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. */ package direct_bt.tinyb; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.tinyb.AdapterSettings; import org.tinyb.BluetoothAdapter; import org.tinyb.BluetoothAddressType; import org.tinyb.BluetoothDevice; import org.tinyb.BluetoothException; import org.tinyb.BluetoothGattCharacteristic; import org.tinyb.BluetoothGattDescriptor; import org.tinyb.BluetoothGattService; import org.tinyb.BluetoothManager; import org.tinyb.BluetoothNotification; import org.tinyb.BluetoothObject; import org.tinyb.BluetoothType; import org.tinyb.EIRDataTypeSet; import org.tinyb.HCIStatusCode; import org.tinyb.HCIWhitelistConnectType; import org.tinyb.AdapterStatusListener; import org.tinyb.TransportType; public class DBTAdapter extends DBTObject implements BluetoothAdapter { private static final boolean DEBUG = DBTManager.DEBUG; private static AtomicInteger globThreadID = new AtomicInteger(0); private static int discoverTimeoutMS = 100; private final String address; private final String name; private final Object discoveryLock = new Object(); private final Object discoveredDevicesLock = new Object(); private final Object userCallbackLock = new Object(); private BluetoothNotification<Boolean> userDiscoverableNotificationCB = null; private final AtomicBoolean isDiscoverable = new AtomicBoolean(false); private BluetoothNotification<Boolean> userDiscoveringNotificationCB = null; private final AtomicBoolean isDiscovering = new AtomicBoolean(false); private BluetoothNotification<Boolean> userPoweredNotificationCB = null; private final AtomicBoolean isPowered = new AtomicBoolean(false); private BluetoothNotification<Boolean> userPairableNotificationCB = null; private final AtomicBoolean isPairable = new AtomicBoolean(false); private final List<BluetoothDevice> discoveredDevices = new ArrayList<BluetoothDevice>(); /* pp */ DBTAdapter(final long nativeInstance, final String address, final String name) { super(nativeInstance, compHash(address, name)); this.address = address; this.name = name; addStatusListener(this.statusListener, null); } @Override public synchronized void close() { if( !isValid() ) { return; } // mute all listener first removeAllStatusListener(); disableDiscoverableNotifications(); disableDiscoveringNotifications(); disablePairableNotifications(); disablePoweredNotifications(); stopDiscovery(); final List<BluetoothDevice> devices = getDevices(); for(final Iterator<BluetoothDevice> id = devices.iterator(); id.hasNext(); ) { final DBTDevice d = (DBTDevice) id.next(); d.close(); } // done in native dtor: removeDevicesImpl(); discoveredDevices.clear(); super.close(); } @Override public boolean equals(final Object obj) { if (obj == null || !(obj instanceof DBTAdapter)) { return false; } final DBTAdapter other = (DBTAdapter)obj; return address.equals(other.address) && name.equals(other.name); } @Override public String getAddress() { return address; } @Override public String getName() { return name; } @Override public BluetoothType getBluetoothType() { return class_type(); } static BluetoothType class_type() { return BluetoothType.ADAPTER; } @Override public BluetoothDevice find(final String name, final String address, final long timeoutMS) { return (DBTDevice) findInCache(name, address, BluetoothType.DEVICE); } @Override public BluetoothDevice find(final String name, final String address) { return find(name, address, 0); } @Override public native boolean isDeviceWhitelisted(final String address); @Override public boolean addDeviceToWhitelist(final String address, final BluetoothAddressType address_type, final HCIWhitelistConnectType ctype, final short conn_interval_min, final short conn_interval_max, final short conn_latency, final short timeout) { return addDeviceToWhitelist(address, address_type.value, ctype.value, conn_interval_min, conn_interval_max, conn_latency, timeout); } private native boolean addDeviceToWhitelist(final String address, final int address_type, final int ctype, final short conn_interval_min, final short conn_interval_max, final short conn_latency, final short timeout); @Override public boolean addDeviceToWhitelist(final String address, final BluetoothAddressType address_type, final HCIWhitelistConnectType ctype) { return addDeviceToWhitelist(address, address_type.value, ctype.value); } private native boolean addDeviceToWhitelist(final String address, final int address_type, final int ctype); @Override public boolean removeDeviceFromWhitelist(final String address, final BluetoothAddressType address_type) { return removeDeviceFromWhitelist(address, address_type.value); } private native boolean removeDeviceFromWhitelist(final String address, final int address_type); /* Unsupported */ @Override public long getBluetoothClass() { throw new UnsupportedOperationException(); } // FIXME @Override public final BluetoothAdapter clone() { throw new UnsupportedOperationException(); } // FIXME @Override public String getInterfaceName() { throw new UnsupportedOperationException(); } // FIXME @Override public long getDiscoverableTimeout() { throw new UnsupportedOperationException(); } // FIXME @Override public void setDiscoverableTimout(final long value) { throw new UnsupportedOperationException(); } // FIXME @Override public long getPairableTimeout() { throw new UnsupportedOperationException(); } // FIXME @Override public void setPairableTimeout(final long value) { throw new UnsupportedOperationException(); } // FIXME @Override public String getModalias() { throw new UnsupportedOperationException(); } // FIXME @Override public String[] getUUIDs() { throw new UnsupportedOperationException(); } // FIXME /* Java callbacks */ @Override public boolean getPowered() { return isPowered.get(); } @Override public void enablePoweredNotifications(final BluetoothNotification<Boolean> callback) { synchronized(userCallbackLock) { userPoweredNotificationCB = callback; } } @Override public void disablePoweredNotifications() { synchronized(userCallbackLock) { userPoweredNotificationCB = null; } } @Override public boolean getDiscoverable() { return isDiscoverable.get(); } @Override public void enableDiscoverableNotifications(final BluetoothNotification<Boolean> callback) { synchronized(userCallbackLock) { userDiscoverableNotificationCB = callback; } } @Override public void disableDiscoverableNotifications() { synchronized(userCallbackLock) { userDiscoverableNotificationCB = null; } } @Override public boolean getDiscovering() { return isDiscovering.get(); } @Override public void enableDiscoveringNotifications(final BluetoothNotification<Boolean> callback) { synchronized(userCallbackLock) { userDiscoveringNotificationCB = callback; } } @Override public void disableDiscoveringNotifications() { synchronized(userCallbackLock) { userDiscoveringNotificationCB = null; } } @Override public boolean getPairable() { return isPairable.get(); } @Override public void enablePairableNotifications(final BluetoothNotification<Boolean> callback) { synchronized(userCallbackLock) { userPairableNotificationCB = callback; } } @Override public void disablePairableNotifications() { synchronized(userCallbackLock) { userPairableNotificationCB = null; } } @Override public String toString() { if( !isValid() ) { return "Adapter" + "\u271D" + "["+address+", '"+name+"']"; } return toStringImpl(); } /* Native callbacks */ /* Native functionality / properties */ private native String toStringImpl(); @Override public native void setPowered(boolean value); @Override public native String getAlias(); @Override public native void setAlias(final String value); @Override public native void setDiscoverable(boolean value); @Override public native BluetoothDevice connectDevice(String address, String addressType); @Override public native void setPairable(boolean value); @Override public native boolean isEnabled(); /* internal */ @Override protected native void deleteImpl(long nativeInstance); /* discovery */ @Override public boolean startDiscovery() throws BluetoothException { return startDiscovery(true); } @Override public boolean startDiscovery(final boolean keepAlive) throws BluetoothException { synchronized( discoveryLock ) { // Ignoring 'isDiscovering', as native implementation also handles change of 'keepAlive'. // The discoveredDevices shall always get cleared. removeDevices(); return startDiscoveryImpl(keepAlive); // event callbacks will be generated by implementation } } private native boolean startDiscoveryImpl(boolean keepAlive) throws BluetoothException; @Override public boolean stopDiscovery() throws BluetoothException { synchronized( discoveryLock ) { if( isDiscovering.get() ) { return stopDiscoveryImpl(); // event callbacks will be generated by implementation } return true; } } private native boolean stopDiscoveryImpl() throws BluetoothException; @Override public List<BluetoothDevice> getDevices() { synchronized(discoveredDevicesLock) { return new ArrayList<BluetoothDevice>(discoveredDevices); } } // std::vector<std::shared_ptr<direct_bt::HCIDevice>> discoveredDevices = adapter.getDiscoveredDevices(); private native List<BluetoothDevice> getDiscoveredDevicesImpl(); @Override public int removeDevices() throws BluetoothException { final int cj = removeDiscoveredDevices(); final int cn = removeDevicesImpl(); if( cj != cn ) { if( DEBUG ) { System.err.println("DBTAdapter::removeDevices: Inconsistent discovered device count: Native "+cn+", callback "+cj); } } return cn; } private native int removeDevicesImpl() throws BluetoothException; private int removeDiscoveredDevices() { synchronized(discoveredDevicesLock) { final int n = discoveredDevices.size(); discoveredDevices.clear(); return n; } } /* pp */ boolean removeDiscoveredDevice(final BluetoothDevice device) { synchronized(discoveredDevicesLock) { return discoveredDevices.remove(device); } } @Override public native boolean addStatusListener(final AdapterStatusListener l, final BluetoothDevice deviceMatch); @Override public native boolean removeStatusListener(final AdapterStatusListener l); @Override public native int removeAllStatusListener(); @Override public void setDiscoveryFilter(final List<UUID> uuids, final int rssi, final int pathloss, final TransportType transportType) { final List<String> uuidsFmt = new ArrayList<>(uuids.size()); for (final UUID uuid : uuids) { uuidsFmt.add(uuid.toString()); } setDiscoveryFilter(uuidsFmt, rssi, pathloss, transportType.ordinal()); } @SuppressWarnings("unchecked") public void setRssiDiscoveryFilter(final int rssi) { setDiscoveryFilter(Collections.EMPTY_LIST, rssi, 0, TransportType.AUTO); } private native void setDiscoveryFilter(List<String> uuids, int rssi, int pathloss, int transportType); //////////////////////////////////// private final AdapterStatusListener statusListener = new AdapterStatusListener() { @Override public void adapterSettingsChanged(final BluetoothAdapter a, final AdapterSettings oldmask, final AdapterSettings newmask, final AdapterSettings changedmask, final long timestamp) { if( DEBUG ) { System.err.println("Adapter.StatusListener.SETTINGS_CHANGED: "+oldmask+" -> "+newmask+", changed "+changedmask+" on "+a); } { if( changedmask.isSet(AdapterSettings.SettingType.POWERED) ) { final boolean _isPowered = newmask.isSet(AdapterSettings.SettingType.POWERED); if( isPowered.compareAndSet(!_isPowered, _isPowered) ) { synchronized(userCallbackLock) { if( null != userPoweredNotificationCB ) { userPoweredNotificationCB.run(_isPowered); } } } } } { if( changedmask.isSet(AdapterSettings.SettingType.DISCOVERABLE) ) { final boolean _isDiscoverable = newmask.isSet(AdapterSettings.SettingType.DISCOVERABLE); if( isDiscoverable.compareAndSet(!_isDiscoverable, _isDiscoverable) ) { synchronized(userCallbackLock) { if( null != userDiscoverableNotificationCB ) { userDiscoverableNotificationCB.run( _isDiscoverable ); } } } } } { if( changedmask.isSet(AdapterSettings.SettingType.BONDABLE) ) { final boolean _isPairable = newmask.isSet(AdapterSettings.SettingType.BONDABLE); if( isPairable.compareAndSet(!_isPairable, _isPairable) ) { synchronized(userCallbackLock) { if( null != userPairableNotificationCB ) { userPairableNotificationCB.run( _isPairable ); } } } } } } @Override public void discoveringChanged(final BluetoothAdapter adapter, final boolean enabled, final boolean keepAlive, final long timestamp) { if( DEBUG ) { System.err.println("Adapter.StatusListener.DISCOVERING: enabled "+enabled+", keepAlive "+keepAlive+" on "+adapter); } if( !enabled && keepAlive ) { // Don't update isDiscovering:=false and don't notify user IF keepAlive! return; } if( isDiscovering.compareAndSet(!enabled, enabled) ) { synchronized(userCallbackLock) { if( null != userDiscoveringNotificationCB ) { userDiscoveringNotificationCB.run(enabled); } } } } @Override public void deviceFound(final BluetoothDevice device, final long timestamp) { if( DEBUG ) { System.err.println("Adapter.StatusListener.FOUND: "+device+" on "+device.getAdapter()); } synchronized(discoveredDevicesLock) { discoveredDevices.add(device); } } @Override public void deviceUpdated(final BluetoothDevice device, final EIRDataTypeSet updateMask, final long timestamp) { if( DEBUG ) { System.err.println("Adapter.StatusListener.UPDATED: "+updateMask+" of "+device+" on "+device.getAdapter()); } // nop on discoveredDevices } @Override public void deviceConnected(final BluetoothDevice device, final short handle, final long timestamp) { if( DEBUG ) { System.err.println("Adapter.StatusListener.CONNECTED: "+device+" on "+device.getAdapter()); } } @Override public void deviceDisconnected(final BluetoothDevice device, final HCIStatusCode reason, final short handle, final long timestamp) { if( DEBUG ) { System.err.println("Adapter.StatusListener.DISCONNECTED: Reason "+reason+", old handle 0x"+Integer.toHexString(handle)+": "+device+" on "+device.getAdapter()); } } }; /** * Returns the matching {@link DBTObject} from the internal cache if found, * otherwise {@code null}. * <p> * The returned {@link DBTObject} may be of type * <ul> * <li>{@link DBTDevice}</li> * <li>{@link DBTGattService}</li> * <li>{@link DBTGattCharacteristic}</li> * <li>{@link DBTGattDescriptor}</li> * </ul> * or alternatively in {@link BluetoothObject} space * <ul> * <li>{@link BluetoothType#DEVICE} -> {@link BluetoothDevice}</li> * <li>{@link BluetoothType#GATT_SERVICE} -> {@link BluetoothGattService}</li> * <li>{@link BluetoothType#GATT_CHARACTERISTIC} -> {@link BluetoothGattCharacteristic}</li> * <li>{@link BluetoothType#GATT_DESCRIPTOR} -> {@link BluetoothGattDescriptor}</li> * </ul> * </p> * @param name name of the desired {@link BluetoothType#DEVICE device}. * Maybe {@code null}. * @param identifier EUI48 address of the desired {@link BluetoothType#DEVICE device} * or UUID of the desired {@link BluetoothType#GATT_SERVICE service}, * {@link BluetoothType#GATT_CHARACTERISTIC characteristic} or {@link BluetoothType#GATT_DESCRIPTOR descriptor} to be found. * Maybe {@code null}, in which case the first object of the desired type is being returned - if existing. * @param type specify the type of the object to be found, either * {@link BluetoothType#DEVICE device}, * {@link BluetoothType#GATT_SERVICE service}, {@link BluetoothType#GATT_CHARACTERISTIC characteristic} * or {@link BluetoothType#GATT_DESCRIPTOR descriptor}. * {@link BluetoothType#NONE none} means anything. */ /* pp */ DBTObject findInCache(final String name, final String identifier, final BluetoothType type) { final boolean anyType = BluetoothType.NONE == type; final boolean deviceType = BluetoothType.DEVICE == type; final boolean serviceType = BluetoothType.GATT_SERVICE == type; final boolean charType = BluetoothType.GATT_CHARACTERISTIC== type; final boolean descType = BluetoothType.GATT_DESCRIPTOR == type; if( !anyType && !deviceType && !serviceType && !charType && !descType ) { return null; } synchronized(discoveredDevicesLock) { if( null == name && null == identifier && ( anyType || deviceType ) ) { // special case for 1st valid device if( discoveredDevices.size() > 0 ) { return (DBTDevice) discoveredDevices.get(0); } return null; // no device } for(int devIdx = discoveredDevices.size() - 1; devIdx >= 0; devIdx-- ) { final DBTDevice device = (DBTDevice) discoveredDevices.get(devIdx); if( ( anyType || deviceType ) ) { if( null != name && null != identifier && device.getName().equals(name) && device.getAddress().equals(identifier) ) { return device; } if( null != identifier && device.getAddress().equals(identifier) ) { return device; } if( null != name && device.getName().equals(name) ) { return device; } } if( anyType || serviceType || charType || descType ) { final DBTObject dbtObj = device.findInCache(identifier, type); if( null != dbtObj ) { return dbtObj; } } } return null; } } }
/* * Dit bestand is een onderdeel van AWV DistrictCenter. * Copyright (c) AWV Agentschap <NAME>, <NAME> */ package be.vlaanderen.awv.atom.java; import be.vlaanderen.awv.atom.Entry; import be.vlaanderen.awv.atom.Feed; import be.vlaanderen.awv.atom.Link; import be.vlaanderen.awv.atom.Url; import lombok.Data; import scala.Some; import scala.collection.JavaConverters; import scala.collection.immutable.List; import java.util.ArrayList; /** * Representation of an atom feed. * * @param <T> entry data type */ @Data public class AtomFeedTo<T> { private String id; private String base; // base URL private String title; private String updated; private FeedLinkTo[] links; private AtomEntryTo<T>[] entries; /** * Converts to an object usable by Atomium. * * @return atomium feed */ public Feed<T> toAtomium() { return new Feed<T>( id, new Url(base), new Some(title), updated, toFeedLinks(links), toFeedEntries(entries) ); } private List<Link> toFeedLinks(FeedLinkTo[] linkTos) { java.util.List<Link> list = new ArrayList<Link>(); for (FeedLinkTo link : linkTos) { list.add(link.toAtomium()); } return JavaConverters.asScalaBufferConverter(list).asScala().toList(); } private List<Entry<T>> toFeedEntries(AtomEntryTo[] entryTos) { java.util.List<Entry<T>> list = new ArrayList<Entry<T>>(); for (AtomEntryTo entry : entryTos) { list.add(entry.toAtomium()); } return JavaConverters.asScalaBufferConverter(list).asScala().toList(); } }
import React, {useState} from 'react'; import {StyleSheet, View, Text, TextInput, Button} from 'react-native'; export default function App() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const authenticate = async () => { // code to authenticate user }; return ( <View style={styles.container}> <Text>Username:</Text> <TextInput style={styles.input} value={username} onChangeText={(value) => setUsername(value)} /> <Text>Password:</Text> <TextInput style={styles.input} value={password} onChangeText={(value) => setPassword(value)} secureTextEntry /> <Button title="Authenticate" onPress={authenticate} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, input: { borderColor: '#000', borderBottomWidth: 1, width: 250, height: 50, padding: 10, fontSize: 20, }, });
<reponame>wojnosystems/vsql //Copyright 2019 <NAME> // // 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. package vresult import ( "github.com/stretchr/testify/mock" "github.com/wojnosystems/vsql/ulong" ) type ResulterMock struct { mock.Mock } func (m *ResulterMock) RowsAffected() (ulong.ULong, error) { a := m.Called() return a.Get(0).(ulong.ULong), a.Error(1) } type InsertResulterMock struct { ResulterMock } func (m *InsertResulterMock) LastInsertId() (ulong.ULong, error) { a := m.Called() return a.Get(0).(ulong.ULong), a.Error(1) }
package ml.cluster; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.Map; import java.util.Random; import ml.data.Attribute; import ml.data.DataInstance; public class KMeans { public Random rng; DistanceFunction distFn; List<Cluster> clusters; public KMeans(DistanceFunction distFunction) { this.rng = new Random(Long.getLong("seed", System.currentTimeMillis())); this.distFn = distFunction; } public KMeans(DistanceFunction distFunction, List<Cluster> clusters) { this.rng = new Random(Long.getLong("seed", System.currentTimeMillis())); this.distFn = distFunction; this.clusters = clusters; } public List<Cluster> getClusters() { return clusters; } /** * Clusters all of the given data points. * * @param data data points. * @param k the number of final clusters. * @param attributeList data point attribute list. */ public void cluster(List<DataInstance> data, int k, List<Attribute> attributeList) { BitSet allDataMask = new BitSet(data.size()); allDataMask.set(0, data.size(), true); cluster(data, allDataMask, k, attributeList, true); } public void cluster(List<DataInstance> data, int k, List<Attribute> attributeList, boolean calcSSE) { BitSet allDataMask = new BitSet(data.size()); allDataMask.set(0, data.size(), true); cluster(data, allDataMask, k, attributeList, calcSSE); } /** * Clusters data points identified by mask bit vector. * * @param data data points. * @param mask bit vector used identify which data instance need to be clustered. * @param k the number of final clusters. * @param attributeList data point attribute list. */ public void cluster(final List<DataInstance> data, final BitSet mask, final int k, final List<Attribute> attributeList, boolean calcSSE) { // create a shadow array for data to store cluster membership int[] clusterMembership = new int[data.size()]; for (int i = mask.nextSetBit(0); i > -1; i = mask.nextSetBit(i + 1)) { clusterMembership[i] = -1; } // pick k random data points and set them as centroid if (clusters == null) { clusters = initialCentroids(data, mask, k); } boolean clusterMemberShipChange = true; do { // assigned data points to clusters clusterMemberShipChange = assignToCentroids(data, mask, clusterMembership, attributeList); // recompute centroid recomputeCentroids(data, mask, clusterMembership, attributeList); } while (clusterMemberShipChange);// while stop condition not fulfilled if (calcSSE) { calcSSE(data, mask, clusterMembership, attributeList); } finalizeClusterMemebership(clusterMembership, mask); } /** * Creates initial cluster centroids. * * @param data all data points. * @param mask bit vector used identify which data instance need to be clustered. * @param k the number of final clusters. * @return List of initial cluster centroids. */ private List<Cluster> initialCentroids(List<DataInstance> data, BitSet mask, int k) { List<Cluster> centroids = new ArrayList<Cluster>(k); int c = 0; BitSet dupDetect = new BitSet(mask.cardinality()); while (c < k) { int offset = rng.nextInt(mask.cardinality()); if (dupDetect.get(offset)) { continue; } dupDetect.set(offset); c++; int start = mask.nextSetBit(0); int i = start; for (; i > -1 && i < start + offset; i = mask.nextSetBit(i + 1)); centroids.add(new Cluster(c, new DataInstance(data.get(i)))); } return centroids; } /** * Assigns data points, identified by mask, to the cluster with closest centroid. * * @param data all data points * @param mask bit vector used identify which data instance need to be clustered. * @param clusterMembership contains the cluster ID of all points in data. * @param attributeList * @return */ private boolean assignToCentroids(final List<DataInstance> data, final BitSet mask, final int[] clusterMembership, final List<Attribute> attributeList) { boolean clusterMemebershipChange = false; for (int i = mask.nextSetBit(0); i > -1; i = mask.nextSetBit(i + 1)) { double minD = Double.POSITIVE_INFINITY; int prevCluster = clusterMembership[i]; for (int c = 0; c < clusters.size(); c++) { double dist = distFn.distance(data.get(i), clusters.get(c).getCentroid(), attributeList); if (dist < minD) { clusterMembership[i] = c; minD = dist; } } if (prevCluster != clusterMembership[i]) { clusterMemebershipChange = true; } } return clusterMemebershipChange; } /** * Recomputes the cluster centroids. * * @param centroids * @param data * @param mask * @param clusterMembership * @param attributeList */ private void recomputeCentroids(final List<DataInstance> data, final BitSet mask, final int[] clusterMembership, final List<Attribute> attributeList) { // Initialize all of the new cluster centroids to 0 List<Cluster> newC = new ArrayList<Cluster>(); int[] count = new int[clusters.size()]; for (int c = 0; c < clusters.size(); c++) { DataInstance di = new DataInstance(); newC.add(new Cluster(c, di)); for (Map.Entry<Integer, Object> me : data.get(0).getAttributes() .entrySet()) { di.setAttributeValueAt(me.getKey(), 0.0); } } // Calculate the distance sum for each centroid to its member data points. for (int i = mask.nextSetBit(0); i > -1; i = mask.nextSetBit(i + 1)) { count[clusterMembership[i]]++; // for each continues attribute in update sum for (Map.Entry<Integer, Object> me : data.get(0).getAttributes() .entrySet()) { int attribIndex = me.getKey(); // Skip Non-Continuous attributes if (attributeList.get(attribIndex).getType() != Attribute.Type.CONTINUOUS) { continue; } double prevAttrSum = (Double) newC.get(clusterMembership[i]).getCentroid() .getAttributeValueAt(attribIndex); newC.get(clusterMembership[i]) .getCentroid() .setAttributeValueAt( attribIndex, prevAttrSum + (Double) data.get(i).getAttributeValueAt(attribIndex)); } } // For each centroid update each attributes average for (int c = 0; c < clusters.size(); c++) { for (Map.Entry<Integer, Object> me : data.get(0).getAttributes() .entrySet()) { int attributeIndex = me.getKey(); clusters .get(c) .getCentroid() .setAttributeValueAt( attributeIndex, (count[c] == 0 ? 0 : (Double) newC.get(c).getCentroid() .getAttributeValueAt(attributeIndex) / count[c])); } } } /** * Calculates SSE for each cluster. * * @param data all data points * @param mask bit vector used identify which data instance need to be clustered. * @param clusterMembership contains the cluster ID of all points in data. * @param attributeList */ private void calcSSE(List<DataInstance> data, BitSet mask, int[] clusterMembership, List<Attribute> attributeList) { double[] sse = new double[this.clusters.size()]; for (int i = mask.nextSetBit(0); i > -1; i = mask.nextSetBit(i + 1)) { int cId = clusterMembership[i]; sse[cId] += Math.pow(distFn.distance(clusters.get(cId).getCentroid(), data.get(i), attributeList), 2); } for (int c = 0; c < clusters.size(); c++) { clusters.get(c).setSse(sse[c]); } } /** * Represents cluster membership as bit vector. * @param clusterMembership * @param mask */ private void finalizeClusterMemebership(int[] clusterMembership, BitSet mask) { for (Cluster c : clusters) { c.getMembers().clear(); } for (int i = mask.nextSetBit(0); i > -1; i = mask.nextSetBit(i + 1)) { int cId = clusterMembership[i]; clusters.get(cId).getMembers().set(i); } } }
<gh_stars>0 import { ContainerModule } from 'inversify'; import { ProxyProvider } from './jsonrpc/proxy-provider'; import { ConnnectionFactory, ConnnectionFactoryImpl } from '../common/jsonrpc/connection-factory'; import { Dispatcher } from '../common/jsonrpc/dispatcher-protocol'; import { ServiceDispatcher } from './jsonrpc/service-dispatcher'; import { ClientProvider, Client } from './client'; import { HttpClient } from './client/http-client'; import { FCClient } from './client/fc-client'; import { ConfigProvider } from '../common/config-provider'; import { ConfigProviderImpl } from './config-provider'; import { RPC } from '../common/annotation/rpc-inject'; export const CoreFrontendModule = new ContainerModule(bind => { bind(ClientProvider).toSelf().inSingletonScope(); bind(FCClient).toSelf().inSingletonScope(); bind(Client).to(HttpClient).inSingletonScope(); bind(Client).toService(FCClient); bind(Dispatcher).to(ServiceDispatcher).inSingletonScope(); bind(ConnnectionFactory).to(ConnnectionFactoryImpl).inSingletonScope(); bind(ProxyProvider).toSelf().inSingletonScope(); bind(ConfigProvider).to(ConfigProviderImpl).inSingletonScope(); bind(RPC).toDynamicValue(ctx => { const namedMetadata = ctx.currentRequest.target.getNamedTag(); const path = namedMetadata!.value.toString(); return ProxyProvider.createProxy(ctx.container, path); }); });
<gh_stars>0 #include <common.h> #include <game.h> #include <g3dhax.h> #include <sfx.h> const char* TMarcNameList [] = { "topman", NULL }; class daTopman : public dEn_c { int onCreate(); int onDelete(); int onExecute(); int onDraw(); mHeapAllocator_c allocator; nw4r::g3d::ResFile resFile; m3d::mdl_c bodyModel; m3d::anmChr_c chrAnimation; int timer; char damage; char isDown; float XSpeed; u32 cmgr_returnValue; bool isBouncing; char isInSpace; char fromBehind; char isWaiting; char backFire; int directionStore; public: static dActor_c *build(); void bindAnimChr_and_setUpdateRate(const char* name, int unk, float unk2, float rate); void updateModelMatrices(); bool calculateTileCollisions(); void playerCollision(ActivePhysics *apThis, ActivePhysics *apOther); void yoshiCollision(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat3_StarPower(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat14_YoshiFire(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCatD_Drill(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat7_GroundPoundYoshi(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat9_RollingObject(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat1_Fireball_E_Explosion(ActivePhysics *apThis, ActivePhysics *apOther); // bool collisionCat2_IceBall_15_YoshiIce(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat13_Hammer(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCatA_PenguinMario(ActivePhysics *apThis, ActivePhysics *apOther); void _vf148(); void _vf14C(); bool CreateIceActors(); void addScoreWhenHit(void *other); USING_STATES(daTopman); DECLARE_STATE(Walk); DECLARE_STATE(Turn); DECLARE_STATE(Wait); DECLARE_STATE(KnockBack); DECLARE_STATE(Die); }; const SpriteData TopmanSpriteData = { ProfileId::Topman, 8, -8 , 0 , 0, 0x100, 0x100, 0, 0, 0, 0, 0 }; Profile TopmanProfile(&daTopman::build, SpriteId::Topman, &TopmanSpriteData, ProfileId::TARZAN_ROPE, ProfileId::Topman, "Topman", TMarcNameList); dActor_c *daTopman::build() { void *buffer = AllocFromGameHeap1(sizeof(daTopman)); return new(buffer) daTopman; } /////////////////////// // Externs and States /////////////////////// extern "C" void *EN_LandbarrelPlayerCollision(dEn_c* t, ActivePhysics *apThis, ActivePhysics *apOther); //FIXME make this dEn_c->used... extern "C" char usedForDeterminingStatePress_or_playerCollision(dEn_c* t, ActivePhysics *apThis, ActivePhysics *apOther, int unk1); extern "C" int SmoothRotation(short* rot, u16 amt, int unk2); CREATE_STATE(daTopman, Walk); CREATE_STATE(daTopman, Turn); CREATE_STATE(daTopman, Wait); CREATE_STATE(daTopman, KnockBack); CREATE_STATE(daTopman, Die); // begoman_attack2" // wobble back and forth tilted forwards // begoman_attack3" // Leaned forward, antennae extended // begoman_damage" // Bounces back slightly // begoman_damage2" // Stops spinning and wobbles to the ground like a top // begoman_stand" // Stands still, waiting // begoman_wait" // Dizzily Wobbles // begoman_wait2" // spins around just slightly // begoman_attack" // Rocks backwards, and then attacks to an upright position, pulsing out his antennae //////////////////////// // Collision Functions //////////////////////// // Collision callback to help shy guy not die at inappropriate times and ruin the dinner void daTopman::playerCollision(ActivePhysics *apThis, ActivePhysics *apOther) { char hitType; hitType = usedForDeterminingStatePress_or_playerCollision(this, apThis, apOther, 0); if(hitType == 1 || hitType == 2) { // regular jump or mini jump this->_vf220(apOther->owner); } else if(hitType == 3) { // spinning jump or whatever? this->_vf220(apOther->owner); } else if(hitType == 0) { EN_LandbarrelPlayerCollision(this, apThis, apOther); if (this->pos.x > apOther->owner->pos.x) { this->backFire = 1; } else { this->backFire = 0; } doStateChange(&StateID_KnockBack); } // fix multiple player collisions via megazig deathInfo.isDead = 0; this->flags_4FC |= (1<<(31-7)); this->counter_504[apOther->owner->which_player] = 0; } void daTopman::yoshiCollision(ActivePhysics *apThis, ActivePhysics *apOther) { this->playerCollision(apThis, apOther); } bool daTopman::collisionCatD_Drill(ActivePhysics *apThis, ActivePhysics *apOther) { this->dEn_c::playerCollision(apThis, apOther); this->_vf220(apOther->owner); deathInfo.isDead = 0; this->flags_4FC |= (1<<(31-7)); this->counter_504[apOther->owner->which_player] = 0; return true; } bool daTopman::collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther) { this->collisionCatD_Drill(apThis, apOther); return true; } bool daTopman::collisionCat7_GroundPoundYoshi(ActivePhysics *apThis, ActivePhysics *apOther) { this->collisionCatD_Drill(apThis, apOther); return true; } bool daTopman::collisionCat9_RollingObject(ActivePhysics *apThis, ActivePhysics *apOther) { backFire = apOther->owner->direction ^ 1; // doStateChange(&StateID_KnockBack); doStateChange(&StateID_Die); return true; } bool daTopman::collisionCat3_StarPower(ActivePhysics *apThis, ActivePhysics *apOther){ doStateChange(&StateID_Die); return true; } bool daTopman::collisionCat13_Hammer(ActivePhysics *apThis, ActivePhysics *apOther) { doStateChange(&StateID_Die); return true; } bool daTopman::collisionCatA_PenguinMario(ActivePhysics *apThis, ActivePhysics *apOther){ backFire = apOther->owner->direction ^ 1; doStateChange(&StateID_KnockBack); return true; } bool daTopman::collisionCat14_YoshiFire(ActivePhysics *apThis, ActivePhysics *apOther){ backFire = apOther->owner->direction ^ 1; doStateChange(&StateID_KnockBack); return true; } bool daTopman::collisionCat1_Fireball_E_Explosion(ActivePhysics *apThis, ActivePhysics *apOther) { backFire = apOther->owner->direction ^ 1; doStateChange(&StateID_KnockBack); return true; } // void daTopman::collisionCat2_IceBall_15_YoshiIce(ActivePhysics *apThis, ActivePhysics *apOther) { // doStateChange(&StateID_DieFall); // } // These handle the ice crap void daTopman::_vf148() { dEn_c::_vf148(); doStateChange(&StateID_Die); } void daTopman::_vf14C() { dEn_c::_vf14C(); doStateChange(&StateID_Die); } DoSomethingCool my_struct; extern "C" void sub_80024C20(void); extern "C" void __destroy_arr(void*, void(*)(void), int, int); //extern "C" __destroy_arr(struct DoSomethingCool, void(*)(void), int cnt, int bar); bool daTopman::CreateIceActors() { struct DoSomethingCool my_struct = { 0, this->pos, {2.5, 2.5, 2.5}, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; this->frzMgr.Create_ICEACTORs( (void*)&my_struct, 1 ); __destroy_arr( (void*)&my_struct, sub_80024C20, 0x3C, 1 ); return true; } void daTopman::addScoreWhenHit(void *other) {} bool daTopman::calculateTileCollisions() { // Returns true if sprite should turn, false if not. HandleXSpeed(); HandleYSpeed(); doSpriteMovement(); cmgr_returnValue = collMgr.isOnTopOfTile(); collMgr.calculateBelowCollisionWithSmokeEffect(); if (isBouncing) { stuffRelatingToCollisions(0.1875f, 1.0f, 0.5f); if (speed.y != 0.0f) isBouncing = false; } float xDelta = pos.x - last_pos.x; if (xDelta >= 0.0f) direction = 0; else direction = 1; if (collMgr.isOnTopOfTile()) { // Walking into a tile branch if (cmgr_returnValue == 0) isBouncing = true; if (speed.x != 0.0f) { //playWmEnIronEffect(); } speed.y = 0.0f; // u32 blah = collMgr.s_80070760(); // u8 one = (blah & 0xFF); // static const float incs[5] = {0.00390625f, 0.0078125f, 0.015625f, 0.0234375f, 0.03125f}; // x_speed_inc = incs[one]; max_speed.x = (direction == 1) ? -0.8f : 0.8f; } else { x_speed_inc = 0.0f; } // Bouncing checks if (_34A & 4) { Vec v = (Vec){0.0f, 1.0f, 0.0f}; collMgr.pSpeed = &v; if (collMgr.calculateAboveCollision(collMgr.outputMaybe)) speed.y = 0.0f; collMgr.pSpeed = &speed; } else { if (collMgr.calculateAboveCollision(collMgr.outputMaybe)) speed.y = 0.0f; } collMgr.calculateAdjacentCollision(0); // Switch Direction if (collMgr.outputMaybe & (0x15 << direction)) { if (collMgr.isOnTopOfTile()) { isBouncing = true; } return true; } return false; } void daTopman::bindAnimChr_and_setUpdateRate(const char* name, int unk, float unk2, float rate) { nw4r::g3d::ResAnmChr anmChr = this->resFile.GetResAnmChr(name); this->chrAnimation.bind(&this->bodyModel, anmChr, unk); this->bodyModel.bindAnim(&this->chrAnimation, unk2); this->chrAnimation.setUpdateRate(rate); } int daTopman::onCreate() { this->deleteForever = true; // Model creation allocator.link(-1, GameHeaps[0], 0, 0x20); this->resFile.data = getResource("topman", "g3d/begoman_spike.brres"); nw4r::g3d::ResMdl mdl = this->resFile.GetResMdl("begoman"); bodyModel.setup(mdl, &allocator, 0x224, 1, 0); SetupTextures_Map(&bodyModel, 0); // Animations start here nw4r::g3d::ResAnmChr anmChr = this->resFile.GetResAnmChr("begoman_wait"); this->chrAnimation.setup(mdl, anmChr, &this->allocator, 0); allocator.unlink(); // Stuff I do understand this->scale = (Vec){0.2, 0.2, 0.2}; // this->pos.y = this->pos.y + 30.0; // X is vertical axis this->rot.x = 0; // X is vertical axis this->rot.y = 0xD800; // Y is horizontal axis this->rot.z = 0; // Z is ... an axis >.> this->direction = 1; // Heading left. this->speed.x = 0.0; this->speed.y = 0.0; this->max_speed.x = 0.8; this->x_speed_inc = 0.0; this->XSpeed = 0.8; this->isInSpace = this->settings & 0xF; this->isWaiting = (this->settings >> 4) & 0xF; this->fromBehind = 0; ActivePhysics::Info HitMeBaby; HitMeBaby.xDistToCenter = 0.0; HitMeBaby.yDistToCenter = 12.0; HitMeBaby.xDistToEdge = 14.0; HitMeBaby.yDistToEdge = 12.0; HitMeBaby.category1 = 0x3; HitMeBaby.category2 = 0x0; HitMeBaby.bitfield1 = 0x4F; HitMeBaby.bitfield2 = 0xffbafffe; HitMeBaby.unkShort1C = 0; HitMeBaby.callback = &dEn_c::collisionCallback; this->aPhysics.initWithStruct(this, &HitMeBaby); this->aPhysics.addToList(); // Tile collider // These fucking rects do something for the tile rect spriteSomeRectX = 28.0f; spriteSomeRectY = 32.0f; _320 = 0.0f; _324 = 16.0f; static const lineSensor_s below(12<<12, 4<<12, 0<<12); static const pointSensor_s above(0<<12, 12<<12); static const lineSensor_s adjacent(6<<12, 9<<12, 14<<12); collMgr.init(this, &below, &above, &adjacent); collMgr.calculateBelowCollisionWithSmokeEffect(); cmgr_returnValue = collMgr.isOnTopOfTile(); if (collMgr.isOnTopOfTile()) isBouncing = false; else isBouncing = true; // State Changers bindAnimChr_and_setUpdateRate("begoman_wait2", 1, 0.0, 1.0); if (this->isWaiting == 0) { doStateChange(&StateID_Walk); } else { doStateChange(&StateID_Wait); } this->onExecute(); return true; } int daTopman::onDelete() { return true; } int daTopman::onExecute() { acState.execute(); updateModelMatrices(); float rect[] = {0.0, 0.0, 38.0, 38.0}; int ret = this->outOfZone(this->pos, (float*)&rect, this->currentZoneID); if(ret) { this->Delete(1); } return true; } int daTopman::onDraw() { bodyModel.scheduleForDrawing(); return true; } void daTopman::updateModelMatrices() { matrix.translation(pos.x, pos.y - 2.0, pos.z); matrix.applyRotationYXZ(&rot.x, &rot.y, &rot.z); bodyModel.setDrawMatrix(matrix); bodyModel.setScale(&scale); bodyModel.calcWorld(false); } /////////////// // Walk State /////////////// void daTopman::beginState_Walk() { this->max_speed.x = (this->direction) ? -this->XSpeed : this->XSpeed; this->speed.x = (direction) ? -0.8f : 0.8f; this->max_speed.y = (this->isInSpace) ? -2.0 : -4.0; this->speed.y = (this->isInSpace) ? -2.0 : -4.0; this->y_speed_inc = (this->isInSpace) ? -0.09375 : -0.1875; } void daTopman::executeState_Walk() { if (!this->isOutOfView()) { nw4r::snd::SoundHandle *handle = PlaySound(this, SE_BOSS_JR_CROWN_JR_RIDE); if (handle) handle->SetVolume(0.5f, 0); } bool ret = calculateTileCollisions(); if (ret) { doStateChange(&StateID_Turn); } bodyModel._vf1C(); if(this->chrAnimation.isAnimationDone()) { this->chrAnimation.setCurrentFrame(0.0); } } void daTopman::endState_Walk() { this->timer += 1; } /////////////// // Turn State /////////////// void daTopman::beginState_Turn() { this->direction ^= 1; this->speed.x = 0.0; } void daTopman::executeState_Turn() { bodyModel._vf1C(); if(this->chrAnimation.isAnimationDone()) { this->chrAnimation.setCurrentFrame(0.0); } u16 amt = (this->direction == 0) ? 0x2800 : 0xD800; int done = SmoothRotation(&this->rot.y, amt, 0x800); if(done) { this->doStateChange(&StateID_Walk); } } void daTopman::endState_Turn() { } /////////////// // Wait State /////////////// void daTopman::beginState_Wait() { this->max_speed.x = 0; this->speed.x = 0; this->max_speed.y = (this->isInSpace) ? -2.0 : -4.0; this->speed.y = (this->isInSpace) ? -2.0 : -4.0; this->y_speed_inc = (this->isInSpace) ? -0.09375 : -0.1875; } void daTopman::executeState_Wait() { if (!this->isOutOfView()) { nw4r::snd::SoundHandle *handle = PlaySound(this, SE_BOSS_JR_CROWN_JR_RIDE); if (handle) handle->SetVolume(0.5f, 0); } bool ret = calculateTileCollisions(); if (ret) { doStateChange(&StateID_Turn); } bodyModel._vf1C(); if(this->chrAnimation.isAnimationDone()) { this->chrAnimation.setCurrentFrame(0.0); } } void daTopman::endState_Wait() { } /////////////// // Die State /////////////// void daTopman::beginState_Die() { dEn_c::dieFall_Begin(); bindAnimChr_and_setUpdateRate("begoman_damage2", 1, 0.0, 1.0); this->timer = 0; } void daTopman::executeState_Die() { bodyModel._vf1C(); PlaySound(this, SE_EMY_MECHAKOOPA_DAMAGE); if(this->chrAnimation.isAnimationDone()) { this->kill(); this->Delete(this->deleteForever); } } void daTopman::endState_Die() { } /////////////// // Knockback State /////////////// void daTopman::beginState_KnockBack() { bindAnimChr_and_setUpdateRate("begoman_damage", 1, 0.0, 0.75); directionStore = direction; speed.x = (backFire) ? XSpeed*5.0f : XSpeed*-5.0f; max_speed.x = speed.x; } void daTopman::executeState_KnockBack() { bool ret = calculateTileCollisions(); this->speed.x = this->speed.x / 1.1; bodyModel._vf1C(); if(this->chrAnimation.isAnimationDone()) { if (this->isWaiting == 0) { OSReport("Done being knocked back, going back to Walk state\n"); doStateChange(&StateID_Walk); } else { OSReport("Done being knocked back, going back to Wait state\n"); doStateChange(&StateID_Wait); } } } void daTopman::endState_KnockBack() { direction = directionStore; bindAnimChr_and_setUpdateRate("begoman_wait2", 1, 0.0, 1.0); }
<gh_stars>0 # frozen_string_literal: true Sequel.migration do up do run 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp"' create_table :events, id: false do column :id, :uuid, index: true column :data, :jsonb, default: "{}", index: {type: :gin} String :type, index: true DateTime :created_at, index: true, default: ::Sequel::CURRENT_TIMESTAMP end run "CREATE INDEX events_data_index_pathops ON events USING gin (data jsonb_path_ops)" run "GRANT ALL PRIVILEGES ON events TO #{ENV.fetch("POSTGRES_USER")}" end down do drop_table :events run 'DROP EXTENSION "uuid-ossp"' end end
Model: import tensorflow as tf from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences tokenizer = Tokenizer() tokenizer.fit_on_texts(sentence_list) word_index = tokenizer.word_index # Create input sequences using list of tokens input_sequences = [] for line in sentence_list: token_list = tokenizer.texts_to_sequences([line])[0] for i in range(1, len(token_list)): n_gram_sequence = token_list[:i+1] input_sequences.append(n_gram_sequence) # Pad sequences max_sequence_len = max([len(x) for x in input_sequences]) input_sequences = np.array(pad_sequences(input_sequences, maxlen=max_sequence_len, padding='pre')) # Create predictors and label predictors, label = input_sequences[:,:-1],input_sequences[:,-1] # Convert the label to one-hot encoded label = tf.keras.utils.to_categorical(label, num_classes=len(word_index)+1) # Create the model model = Sequential() model.add(Embedding(len(word_index)+1, 10, input_length=max_sequence_len-1)) model.add(LSTM(128)) model.add(Dense(len(word_index)+1, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(predictors, label, epochs=100, verbose=2)
<!DOCTYPE html> <html> <head> <title>Navigation</title> </head> <body> <h1>Navigation</h1> <div> <a href="page1.html"><button>Page 1</button></a> <a href="page2.html"><button>Page 2</button></a> <a href="page3.html"><button>Page 3</button></a> </div> </body> </html>
<filename>src/logging/index.ts export interface Logger { debug(message: string): void; info(message: string): void; warn(message: string): void; error(message: string): void; } export interface LoggerFactory { (namespace?: string): Logger; }
#!/bin/bash mpirun -n 16 ./mpi_wordcount data-wordcount/in/
import os import csv import random STORE_HEIGHT = int(os.getenv('STORE_HEIGHT', 10)) STORE_WIDTH = int(os.getenv('STORE_WIDTH', 6)) CUSTOMERS_AVERAGE_IN_STORE = int(os.getenv('CUSTOMERS_AVERAGE_IN_STORE', 6)) CUSTOMERS_LIST_FILE = os.getenv('CUSTOMERS_LIST_FILE', 'customers.csv') def read_customer_list(file_name): with open(file_name, 'r') as file: reader = csv.reader(file) customer_list = [row for row in reader] return customer_list def simulate_customer_movement(customer_list, store_height, store_width): for customer in customer_list: current_position = (random.randint(0, store_height-1), random.randint(0, store_width-1)) print(f"Customer {customer[0]} is at position {current_position}") for _ in range(5): # Simulate 5 movements for each customer direction = random.choice(['up', 'down', 'left', 'right']) if direction == 'up' and current_position[0] > 0: current_position = (current_position[0] - 1, current_position[1]) elif direction == 'down' and current_position[0] < store_height - 1: current_position = (current_position[0] + 1, current_position[1]) elif direction == 'left' and current_position[1] > 0: current_position = (current_position[0], current_position[1] - 1) elif direction == 'right' and current_position[1] < store_width - 1: current_position = (current_position[0], current_position[1] + 1) print(f"Customer {customer[0]} moved {direction} to position {current_position}") customer_list = read_customer_list(CUSTOMERS_LIST_FILE) simulate_customer_movement(customer_list, STORE_HEIGHT, STORE_WIDTH)
#!/bin/bash # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. 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. # # Runs Beeswax server. set -o errexit if [ -z "$HADOOP_HOME" ]; then echo "\$HADOOP_HOME must be specified" 1>&2 exit 1 fi if [ -z "$HIVE_CONF_DIR" ]; then echo "\$HIVE_CONF_DIR must be specified" 1>&2 exit 1 fi BEESWAX_ROOT=$(dirname $0) BEESWAX_JAR=$BEESWAX_ROOT/java-lib/BeeswaxServer.jar BEESWAX_HIVE_LIB=$BEESWAX_ROOT/hive/lib echo \$HADOOP_HOME=$HADOOP_HOME export HADOOP_CLASSPATH=$(find $BEESWAX_HIVE_LIB -name "*.jar" | tr "\n" :) if [ -n "$HADOOP_EXTRA_CLASSPATH_STRING" ]; then export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$HADOOP_EXTRA_CLASSPATH_STRING fi export HADOOP_OPTS="-Dlog4j.configuration=log4j.properties" echo \$HADOOP_CLASSPATH=$HADOOP_CLASSPATH echo \$HADOOP_OPTS=$HADOOP_OPTS # Use HADOOP_CONF_DIR to preprend to classpath, to avoid fb303 conflict, # and to force hive-default to correspond to the Hive version we have. # Because we are abusing HADOOP_CONF_DIR, we have to emulate its default # behavior here as well. if [ -z "$HADOOP_CONF_DIR" ]; then HADOOP_CONF_DIR="$HADOOP_HOME/conf" fi if [ -f $HADOOP_CONF_DIR/hadoop-env.sh ]; then . $HADOOP_CONF_DIR/hadoop-env.sh fi export HADOOP_CONF_DIR=$HIVE_CONF_DIR:${BEESWAX_HIVE_LIB}/hive-default-xml-0.6.0.jar:${HADOOP_CONF_DIR}:$(find $BEESWAX_HIVE_LIB -name "thrift-fb303-0.5.0.jar" | head -1) echo \$HADOOP_CONF_DIR=$HADOOP_CONF_DIR # Note: I've had trouble running this with just "java -jar" with the classpath # determined with a seemingly appropriate find command. echo CWD=$(pwd) echo Executing $HADOOP_HOME/bin/hadoop jar $BEESWAX_JAR "$@" exec $HADOOP_HOME/bin/hadoop jar $BEESWAX_JAR "$@"
#!/bin/bash cp ${RECIPE_DIR}/condabuildinfo.cmake . mkdir -p build cd build ${BUILD_PREFIX}/bin/cmake \ -DCMAKE_INSTALL_PREFIX=${PREFIX} \ -DCMAKE_BUILD_TYPE=Release \ -DIS_CONDA_BUILD=True \ -DCONDA_PREFIX=${CONDA_PREFIX} \ -DIS_PYTHON_BUILD=True \ -DPYTHON_TARGET_VERSION=${PY_VER} \ -DPYTHON_SITE_PACKAGES=${SP_DIR} \ -DBOOST_ROOT=${BUILD_PREFIX} \ -DXMS_VERSION="${XMS_VERSION}" ${SRC_DIR} make -j${CPU_COUNT} make install cd .. cp ./build/_xms*.so ./_package/xms/grid/ ${PYTHON} -m pip install ./_package --no-deps --ignore-installed -vvv
/* * Copyright 2022. http://devonline.academy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package academy.devonline.java.home_section031_polymorphism.structures255; /** * @author devonline * @link http://devonline.academy/java */ public class LinkedList extends BaseDataStructure{ private Item first; private Item last; @Override public void add(int value) { Item item = new Item(value); if (first == null) { first = last = item; } else { last.next = item; last = item; } count++; } @Override public void add(LinkedList secondList) { if (secondList.count > 0) { if (first == null) { first = secondList.first; } else { last.next = secondList.first; } last = secondList.last; count += secondList.count; } } @Override public int[] toArray() { int[] result = new int[count]; int index = 0; Item current = first; while (current != null) { result[index++] = current.value; current = current.next; } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder().append('['); Item current = first; while (current != null) { builder.append(current.value); if (current.next != null) { builder.append(", "); } current = current.next; } return builder.append(']').toString(); } @Override public void clear() { first = null; last = null; super.clear(); } @Override public boolean remove(int value) { Pair pair = findPair(value); if (pair != null) { if (pair.current == first && pair.current == last) { first = null; last = null; } else if (pair.current == first) { first = pair.current.next; } else { pair.previous.next = pair.current.next; if (pair.current == last) { last = pair.previous; } } count--; return true; } return false; } private Pair findPair(int value) { Item previous = first; Item current = first; while (current != null) { if (current.value == value) { return new Pair(previous, current); } else { previous = current; current = current.next; } } return null; } @Override public boolean contains(int value) { return findPair(value) != null; } /** * @author devonline * @link http://devonline.academy/java */ private static class Pair { private Item previous; private Item current; private Pair(Item previous, Item current) { this.previous = previous; this.current = current; } } /** * @author devonline * @link http://devonline.academy/java */ private static class Item { private int value; private Item next; private Item(int value) { this.value = value; } } }
<reponame>mehdisamavat65/artfactory-frontend import gql from "graphql-tag"; export const GET_ALL_USER_ADMIN = gql` query { getAllUserAdmin { id name mobile active access { admin teacher departemant course gallery offer website online live } } } `; export const GET_ALL_TEACER = gql` query { getAllTeacher { id name mobile password picture resume active } } `; export const GET_ALL_DEPARTEMANT = gql` query { getAllDepartemant { id name color active subDepartemant { id name active } } } `;
#!/bin/bash cd "$(dirname "${BASH_SOURCE[0]}")" \ && . "../../utils.sh" # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - print_in_purple "\n Trackpad & Mouse\n\n" execute "defaults write -g com.apple.trackpad.scaling -int 5 && \ defaults write -g com.apple.mouse.scaling -float 5" \ "Increase tracking speed" execute "defaults write com.apple.AppleMultitouchMouse MouseButtonMode -string TwoButton && \ defaults write com.apple.driver.AppleBluetoothMultitouch.mouse MouseButtonMode -string TwoButton" \ "Enable secondary mouse click"
#!/bin/bash # Invocation: script.sh 'bucketname' '30 days ago' # See more date input formats: https://www.gnu.org/software/coreutils/manual/html_node/date-invocation.html#date-invocation aws s3 ls s3://$1 | while read -r line; do createDate=`echo $line|awk {'print $1" "$2'}` createDate=`date -d"$createDate" +%s` olderThan=`date -d"$2" +%s` if [[ $createDate -lt $olderThan ]] then fileName=`echo $line|awk {'print $4'}` echo "$fileName" if [[ $fileName != "" ]] then aws s3 rm "s3://$1/$fileName" fi fi done;
package net.ninjacat.omg.omql; import net.ninjacat.omg.conditions.AlwaysTrueCondition; import net.ninjacat.omg.conditions.Condition; import net.ninjacat.omg.conditions.Conditions; import net.ninjacat.omg.errors.OmqlParsingException; import net.ninjacat.omg.errors.TypeConversionException; import org.immutables.value.Value; import org.junit.Test; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class QueryCompilerTest { private static final List<Class<?>> SOURCES = io.vavr.collection.List.of( Person.class, JetPilot.class ).asJava(); @Test public void shouldConvertSimpleQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age > 25", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .property("age").gt(25) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertSimpleMatchQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("match Person where age > 25", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .property("age").gt(25) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertGteQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from JetPilot where age >= 25", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .or(c -> c .property("age").gt(25) .property("age").eq(25) ) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertLteQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from JetPilot where age <= 25", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .or(c -> c .property("age").lt(25) .property("age").eq(25) ) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertNeqQuery1() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age <> 25", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .property("age").neq(25) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertNeqQuery2() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age != 25", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .property("age").neq(25) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertSimpleAndQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age < 25 and name = 'Iñigo'", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .and(c -> c .property("age").lt(25) .property("name").eq("Iñigo")) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertSimpleOrQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age > 25 or name = 'Iñigo'", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .or(c -> c .property("age").gt(25) .property("name").eq("Iñigo")) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertSimpleAndOrQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age > 25 or name = 'Iñigo' and status=\"Searching\"", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .or(c -> c .property("age").gt(25) .and(a -> a .property("name").eq("Iñigo") .property("status").eq("Searching") ) ) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertMultiAndQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age > 25 and name = 'Iñigo' and status=\"Searching\"", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .and(c -> c .and(a -> a .property("age").gt(25) .property("name").eq("Iñigo") ) .property("status").eq("Searching") ) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertSimpleRegexQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where name ~= '^Iñigo .*'", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .property("name").regex("^Iñigo .*") .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertInQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age in (1,2,3)", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .property("age").in(io.vavr.collection.HashSet.of(1, 2, 3).toJavaSet()) .build(); assertThat(condition, is(expected)); } @Test public void shouldConvertSubQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where friend in (select * from Person where age > 18)", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher() .property("friend").match(m -> m .property("age").gt(18)) .build(); assertThat(condition, is(expected)); } @Test public void shouldParseQueryWithoutWhere() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = AlwaysTrueCondition.INSTANCE; assertThat(condition, is(expected)); } @Test public void shouldParseQueryWithBoolean() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from JetPilot where canFly = true", SOURCES); final Condition condition = queryCompiler.getCondition(); final Condition expected = Conditions.matcher().property("canFly").eq(true).build(); assertThat(condition, is(expected)); } @Test(expected = OmqlParsingException.class) public void shouldFailToParseQuery() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where friend is unlike others", SOURCES); queryCompiler.getCondition(); } @Test(expected = TypeConversionException.class) public void shouldFailWhenInContainsDifferentTypes() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age in (21, 22, 'old enough')", SOURCES); queryCompiler.getCondition(); } @Test(expected = OmqlParsingException.class) public void shouldFailWhenRegexOnNonString() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where age ~= 20", SOURCES); queryCompiler.getCondition(); } @Test(expected = OmqlParsingException.class) public void shouldFailOnSyntaxError1() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where name = 'jack", SOURCES); queryCompiler.getCondition(); } @Test(expected = OmqlParsingException.class) public void shouldFailOnSyntaxError2() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where name in ('jack', 'john'", SOURCES); queryCompiler.getCondition(); } @Test(expected = OmqlParsingException.class) public void shouldFailOnSyntaxError3() { final QueryCompiler queryCompiler = QueryCompiler.of("select * from Person where name in (not a list or subquery)", SOURCES); queryCompiler.getCondition(); } @Value.Immutable public interface Person { int age(); String name(); String status(); } @Value.Immutable public interface JetPilot { int age(); String callsign(); boolean canFly(); } }
#!/usr/bin/env bats load ./common @test "--container-mounts absolute directory" { run_srun --container-mounts=/home:/test-mnt --container-image=ubuntu:18.04 findmnt /test-mnt } @test "--container-mounts regular file" { run_srun --container-mounts="${BASH_SOURCE[0]}:/script.bats" --container-image=ubuntu:18.04 cat /script.bats } @test "--container-mounts character device file" { run_srun --container-mounts="/dev/null:/null" --container-image=ubuntu:18.04 bash -c '[ -c /null ]' } @test "--container-mounts current working directory" { run_srun --container-mounts=./:/test-mnt --container-image=ubuntu:18.04 findmnt /test-mnt } @test "--container-mounts multiple entries" { run_srun --container-mounts=./:/test-mnt,/dev/null:/null,/home:/host/home --container-image=ubuntu:18.04 sh -c 'findmnt /test-mnt && findmnt /null && findmnt /host/home' } @test "--container-mounts /etc/shadow" { if [ "$(id -u)" -eq 0 ]; then skip "test requires non-root" fi # We should be able to bind-mount, but not access the file. run_srun --container-mounts=/etc/shadow:/shadow --container-image=ubuntu:18.04 sh -c 'findmnt /shadow' run_srun_unchecked --container-mounts=/etc/shadow:/shadow --container-image=ubuntu:18.04 cat /shadow [ "${status}" -ne 0 ] grep -q 'Permission denied' <<< "${output}" } @test "--container-mounts read-only directory" { run_srun_unchecked --container-mounts=/tmp:/mnt:ro --container-image=ubuntu:18.04 touch /mnt/foo [ "${status}" -ne 0 ] grep -q 'Read-only file system' <<< "${output}" } @test "--container-mounts multiple flags: unbindable+ro" { run_srun_unchecked --container-mounts=/tmp:/mnt:unbindable+ro --container-image=ubuntu:18.04 touch /mnt/foo [ "${status}" -ne 0 ] grep -q 'Read-only file system' <<< "${output}" run_srun --container-mounts=/tmp:/mnt:unbindable+ro --container-image=ubuntu:18.04 findmnt -o PROPAGATION /mnt grep -q 'unbindable' <<< "${lines[-1]}" } @test "--container-mounts path escape attempt" { run_srun_unchecked --container-mounts=/home:../home --container-image=ubuntu:18.04 true [ "${status}" -ne 0 ] grep -q -i 'cross-device link' <<< "${output}" } @test "--container-mounts short-form" { run_srun --container-image=ubuntu:18.04 bash -c '! findmnt /var/lib' run_srun --container-mounts=/var/lib --container-image=ubuntu:18.04 findmnt /var/lib }
#!/usr/bin/env python # file: tk-threaded.pyw # vim:fileencoding=utf-8:fdm=marker:ft=python # # Copyright © 2022 <NAME> <<EMAIL>> # SPDX-License-Identifier: MIT # Created: 2022-02-02T21:40:48+0100 # Last modified: 2022-02-04T16:39:32+0100 """Example tkinter script showing the use of a thread.""" import os import sys import threading import time import tkinter as tk import tkinter.font as tkfont import types __version__ = "2022.02.02" # Namespace for widgets that need to be accessed by callbacks. widgets = types.SimpleNamespace() # State that needs to be accessed by callbacks. state = types.SimpleNamespace() def create_widgets(root, w): """ Create the window and its widgets. Arguments: root: the root window. w: SimpleNamespace to store widgets. """ # General commands and bindings root.wm_title("tkinter threading v" + __version__) root.columnconfigure(2, weight=1) root.rowconfigure(3, weight=1) root.resizable(False, False) # First row tk.Label(root, text="Thread status: ").grid(row=0, column=0, sticky="ew") w.runstatus = tk.Label(root, text="not running", width=12) w.runstatus.grid(row=0, column=1, sticky="ew") # Second row tk.Label(root, text="Timer: ").grid(row=1, column=0, sticky="ew") w.counter = tk.Label(root, text="0 s") w.counter.grid(row=1, column=1, sticky="ew") # Third row w.gobtn = tk.Button(root, text="Go", command=do_start) w.gobtn.grid(row=2, column=0, sticky="ew") w.stopbtn = tk.Button(root, text="Stop", command=do_stop, state=tk.DISABLED) w.stopbtn.grid(row=2, column=1, sticky="ew") def initialize_state(s): """ Initialize the global state. Arguments: s: SimpleNamespace to store application state. """ s.worker = None s.run = False s.counter = 0 def worker(): """ Function that is run in a separate thread. This function *does* update tkinter widgets. In Python 3, this should be safe if a tkinter is used that is built with threads. """ # Initialization widgets.runstatus["text"] = "running" # Work while state.run: time.sleep(0.25) state.counter += 0.25 widgets.counter["text"] = f"{state.counter:.2f} s" # Finalization state.counter = 0.0 widgets.counter["text"] = f"{state.counter:g} s" widgets.runstatus["text"] = "not running" def do_start(): """Callback for the “Go” button""" widgets.gobtn["state"] = tk.DISABLED widgets.stopbtn["state"] = tk.NORMAL state.run = True state.worker = threading.Thread(target=worker) state.worker.start() def do_stop(): """Callback for the “Stop” button""" widgets.gobtn["state"] = tk.NORMAL widgets.stopbtn["state"] = tk.DISABLED state.run = False state.worker = None # Main program starts here. if __name__ == "__main__": # Detach from the command line on UNIX systems. if os.name == "posix": if os.fork(): sys.exit() # Initialize global state initialize_state(state) # Create the GUI window. root = tk.Tk(None) # Set the font default_font = tkfont.nametofont("TkDefaultFont") default_font.configure(size=12) root.option_add("*Font", default_font) create_widgets(root, widgets) root.mainloop()
package db import ( "context" "net/http" "strings" "github.com/pkg/errors" "github.com/uclaacm/teach-la-go-backend/httpext" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "cloud.google.com/go/firestore" "github.com/labstack/echo/v4" ) // User is a struct representation of a user document. // It provides functions for converting the struct // to firebase-digestible types. type User struct { Classes []string `firestore:"classes" json:"classes"` DisplayName string `firestore:"displayName" json:"displayName"` MostRecentProgram string `firestore:"mostRecentProgram" json:"mostRecentProgram"` PhotoName string `firestore:"photoName" json:"photoName"` Programs []string `firestore:"programs" json:"programs"` UID string `json:"uid"` } // ToFirestoreUpdate returns the database update // representation of its UserData struct. func (u *User) ToFirestoreUpdate() []firestore.Update { f := []firestore.Update{ {Path: "mostRecentProgram", Value: u.MostRecentProgram}, } switch { case u.DisplayName != "": f = append(f, firestore.Update{Path: "displayName", Value: u.DisplayName}) case u.PhotoName != "": f = append(f, firestore.Update{Path: "photoName", Value: u.PhotoName}) case len(u.Programs) != 0: f = append(f, firestore.Update{Path: "programs", Value: firestore.ArrayUnion(u.Programs)}) } return f } // GetUser acquires the userdoc with the given uid. // // Query Parameters: // - uid string: UID of user to get // // Returns: Status 200 with marshalled User and programs. func (d *DB) GetUser(c echo.Context) error { resp := struct { UserData User `json:"userData"` Programs map[string]Program `json:"programs"` }{ UserData: User{}, Programs: make(map[string]Program), } // get user uid := c.QueryParam("uid") if uid == "" { return c.String(http.StatusBadRequest, "uid is a required query parameter") } // get user data err := d.RunTransaction(c.Request().Context(), func(ctx context.Context, tx *firestore.Transaction) error { ref := d.Collection(usersPath).Doc(c.QueryParam("uid")) doc, err := tx.Get(ref) if err != nil { return err } return doc.DataTo(&resp.UserData) }) if err != nil { if status.Code(err) == codes.NotFound { return c.String(http.StatusNotFound, "user does not exist") } return c.String(http.StatusInternalServerError, errors.Wrap(err, "failed to get user data").Error()) } // get programs, if requested if c.QueryParam("programs") != "" { for _, p := range resp.UserData.Programs { currentProg := Program{} progTXErr := d.RunTransaction(c.Request().Context(), func(ctx context.Context, tx *firestore.Transaction) error { doc, err := tx.Get(d.Collection(programsPath).Doc(p)) if err != nil { return err } return doc.DataTo(&currentProg) }) if progTXErr != nil { if status.Code(progTXErr) == codes.NotFound { return c.String(http.StatusNotFound, "could not retrieve user programs, invalid reference") } return c.String(http.StatusInternalServerError, errors.Wrap(progTXErr, "failed to get user's programs").Error()) } resp.Programs[p] = currentProg } } return c.JSON(http.StatusOK, &resp) } // UpdateUser updates the doc with specified UID's fields // to match those of the request body. // // Request Body: // { // "uid": [REQUIRED] // [User object fields] // } // // Returns: Status 200 on success. func (d *DB) UpdateUser(c echo.Context) error { // unmarshal request body into an User struct. requestObj := User{} if err := httpext.RequestBodyTo(c.Request(), &requestObj); err != nil { return err } uid := requestObj.UID if uid == "" { return c.String(http.StatusBadRequest, "a uid is required") } if len(requestObj.Programs) != 0 { return c.String(http.StatusBadRequest, "program list cannot be updated via /program/update") } err := d.RunTransaction(c.Request().Context(), func(ctx context.Context, tx *firestore.Transaction) error { ref := d.Collection(usersPath).Doc(uid) return tx.Update(ref, requestObj.ToFirestoreUpdate()) }) if err != nil { if status.Code(err) == codes.NotFound { return c.String(http.StatusNotFound, "user could not be found") } return c.String(http.StatusInternalServerError, errors.Wrap(err, "failed to update user data").Error()) } return c.String(http.StatusOK, "user updated successfully") } // CreateUser creates a new user object corresponding to either // the provided UID or a random new one if none is provided // with the default data. // // Request Body: // { // "uid": string <optional> // } // // Returns: Status 200 with a marshalled User struct on success. func (d *DB) CreateUser(c echo.Context) error { var body struct { UID string `json:"uid"` } if err := httpext.RequestBodyTo(c.Request(), &body); err != nil { return c.String(http.StatusInternalServerError, errors.Wrap(err, "failed to marshal request body").Error()) } // create new doc for user if necessary ref := d.Collection(usersPath).NewDoc() if body.UID != "" { ref = d.Collection(usersPath).Doc(body.UID) } // create structures to be used as default data newUser, newProgs := defaultData() newUser.UID = ref.ID err := d.RunTransaction(c.Request().Context(), func(ctx context.Context, tx *firestore.Transaction) error { // if the user exists, then we have a problem. userSnap, _ := tx.Get(ref) if userSnap.Exists() { return errors.Errorf("user document with uid '%s' already initialized", body.UID) } // create all new programs and associate them to the user. for _, prog := range newProgs { // create program in database. newProg := d.Collection(programsPath).NewDoc() if err := tx.Create(newProg, prog); err != nil { return err } // establish association in user doc. newUser.Programs = append(newUser.Programs, newProg.ID) } // set MRP and return newUser.MostRecentProgram = newUser.Programs[0] return tx.Create(ref, newUser) }) if err != nil { if strings.Contains(err.Error(), "user document with uid '") { return c.String(http.StatusBadRequest, err.Error()) } return c.String(http.StatusInternalServerError, errors.Wrap(err, "failed to create user").Error()) } return c.JSON(http.StatusCreated, &newUser) } // DeleteUser deletes an user along with all their programs // from the database. // // Request Body: // { // "uid": REQUIRED // } // // Returns: status 200 on deletion. func (d *DB) DeleteUser(c echo.Context) error { var req struct { UID string `json:"uid"` } if err := httpext.RequestBodyTo(c.Request(), &req); err != nil { return c.String(http.StatusInternalServerError, errors.Wrap(err, "failed to read request body").Error()) } if req.UID == "" { return c.String(http.StatusBadRequest, "uid is required") } userRef := d.Collection(usersPath).Doc(req.UID) err := d.RunTransaction(c.Request().Context(), func(ctx context.Context, tx *firestore.Transaction) error { userSnap, err := tx.Get(userRef) if err != nil { return err } usr := User{} if err := userSnap.DataTo(&usr); err != nil { return err } for _, prog := range usr.Programs { progRef := d.Collection(programsPath).Doc(prog) // if we can't find a program, then it's not a problem. if err := tx.Delete(progRef); err != nil && status.Code(err) != codes.NotFound { return err } } return tx.Delete(userRef) }) if err != nil { if status.Code(err) == codes.NotFound { return c.String(http.StatusNotFound, "could not find user") } return c.String(http.StatusInternalServerError, errors.Wrap(err, "failed to delete user").Error()) } return c.String(http.StatusOK, "user deleted successfully") }
<reponame>Haarmees/azure-devops-intellij // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.alm.plugin.idea.tfvc.core.tfs; import com.microsoft.alm.plugin.idea.IdeaAbstractTest; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class TfsRevisionNumberTest extends IdeaAbstractTest { @Test public void testTryParse_Happy() { TfsRevisionNumber actualNumber = new TfsRevisionNumber(1, "fileName", "2016-09-14T16:10:08.487-0400"); TfsRevisionNumber parsedNumber = TfsRevisionNumber.tryParse(actualNumber.asString()); assertEquals(actualNumber.getChangesetString(), parsedNumber.getChangesetString()); assertEquals(actualNumber.getFileName(), parsedNumber.getFileName()); assertEquals(actualNumber.getModificationDate(), parsedNumber.getModificationDate()); } @Test public void testTryParse_MalformedNumber() { TfsRevisionNumber parsedNumber = TfsRevisionNumber.tryParse("fileName"); assertNull(parsedNumber); parsedNumber = TfsRevisionNumber.tryParse("1/fileName/"); assertNull(parsedNumber); parsedNumber = TfsRevisionNumber.tryParse("1/fileName//"); assertNull(parsedNumber); parsedNumber = TfsRevisionNumber.tryParse("1/fileName/number/extra"); assertNull(parsedNumber); } }
#!/bin/bash # Shell Checker # Author: Arya Narotama (4WSec) # Team: Anon Cyber Team - anoncyberteam.or.id # Github: github.com/aryanrtm # Instagram: instagram.com/aryanrtm_ # 07-2019 - 4WSec # Date time=$(date +%d_%m_%y) # Color GR='\033[92m'; # Green YW='\033[93m'; # Yellow RD='\033[91m'; # Red NT='\033[97m'; # Netral # Add Words Here word1="Shell"; word2="wso"; word3="b374k"; word4="IndoXploit"; word5="backdoor"; word6="cyber"; # User Agent UserAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36"; function banner () { printf " ⚡ \e[1;92mShell Checker by 4WSec ⚡\e[0m\n\n" } function shell_checker () { local req=$(curl -s -L "${URL}" -I \ --user-agent "${UserAgent}" \ -w %{http_code} -m 5 | grep "200 OK"); if [[ $req == 200 ]] || [[ $req =~ '200 OK' ]]; then printf " ${GR}[LIVE] ${YW}-> ${NT}${URL}\n" echo " [LIVE] $URL" | uniq | sort >> shell_live_$time.txt elif [[ $req =~ "${word1}" ]] || [[ $req =~ "${word2}" ]] || [[ $req =~ "${word3}" ]] || [[ $req =~ "${word4}" ]] || [[ $req =~ "${word5}" ]] || [[ $req =~ "${word6}" ]]; then printf " ${GR}[LIVE] ${YW}-> ${NT}${URL}\n" echo " [LIVE] $URL" | uniq | sort >> shell_live_$time.txt else printf " ${RD}[DIE] ${YW}-> ${NT}${URL}\n" fi } banner printf " ${NT}[${RD}+${NT}] ${YW}Enter List Shell: ${NT}"; read list; if [ ! -f $list ]; then printf " ${NT}[${RD}!${NT}] ${RD}File Not Found ...\n" exit 0 fi printf " ${NT}[${RD}+${NT}] ${YW}Enter Threads (Default 20): ${NT}"; read threads; if [[ $threads == "" ]]; then threads=20; fi printf "\n ---------------------------------------\n\n" IFS=$'\r\n' con=1; for URL in $(cat $list); do fast=$(expr $con % $threads); if [[ $fast == 0 && $con > 0 ]]; then sleep 3 fi shell_checker & con=$[$con+1]; done wait
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { IonicModule } from '@ionic/angular'; import { InviteFriendPageRoutingModule } from './invite-friend-routing.module'; import { InviteFriendPage } from './invite-friend.page'; @NgModule({ imports: [ CommonModule, FormsModule, IonicModule, InviteFriendPageRoutingModule ], declarations: [InviteFriendPage] }) export class InviteFriendPageModule {}
require "rails_helper" RSpec.describe MissingDataCalculator, type: :model do describe "no data calculations" do subject(:department_test) { FactoryGirl.build(:department) } subject(:delivery_organistion_test) { FactoryGirl.build(:delivery_organistion, department: department_test) } it "can calculate when no data available" do calc = MissingDataCalculator.new(department_test, TimePeriod.default) expect(calc.missing_data).to eq([]) end end describe "missing data calculations" do subject(:department) { FactoryGirl.build(:department) } subject(:delivery_organisation) { FactoryGirl.build(:delivery_organisation, department: department) } subject(:service) { FactoryGirl.build(:service, delivery_organisation: delivery_organisation, natural_key: "a", name: "test") } it "can calculate with published metrics" do metrics = FactoryGirl.build(:monthly_service_metrics, service: service, published: true, phone_transactions: 100, calls_received_perform_transaction: 100, calls_received: 100, month: YearMonth.new(2018, 2)) metrics.save calc = MissingDataCalculator.new( department, TimePeriod.new(Date.new(2018, 1, 1), Date.new(2018, 3, 1)) ) # We expect only 1 service to appear with missing data expect(calc.missing_data.length).to eq(1) # We expect there to be complains about all the metrics expect(calc.missing_data[0].metrics.length).to eq(13) end it "can format months_missing string for consecutive months missing data within the same year" do metrics = FactoryGirl.build(:monthly_service_metrics, service: service, published: true, online_transactions: 100, month: YearMonth.new(2017, 12)) metrics.save calc = MissingDataCalculator.new( department, TimePeriod.new(Date.new(2017, 10, 1), Date.new(2018, 3, 1)) ) expect(calc.missing_data[0].metrics[0][:months_missing]).to eq("October to November 2017, January to February 2018") end it "can format months_missing string for consecutive months missing data across years" do metrics = FactoryGirl.build(:monthly_service_metrics, service: service, published: true, phone_transactions: 100, calls_received_perform_transaction: 100, calls_received: 100, month: YearMonth.new(2018, 2)) metrics.save calc = MissingDataCalculator.new( department, TimePeriod.new(Date.new(2017, 10, 1), Date.new(2018, 3, 1)) ) expect(calc.missing_data[0].metrics[1][:months_missing]).to eq("October 2017 to January 2018") end it "can format months_missing string where both consecutive month and individual month data is missing" do metrics = FactoryGirl.build(:monthly_service_metrics, service: service, published: true, paper_transactions: 100, month: YearMonth.new(2018, 1)) metrics.save calc = MissingDataCalculator.new( department, TimePeriod.new(Date.new(2017, 10, 1), Date.new(2018, 3, 1)) ) expect(calc.missing_data[0].metrics[2][:months_missing]).to eq("October to December 2017, February 2018") end it "can format months_missing string when only non consecutive month data is missing" do metrics = FactoryGirl.build(:monthly_service_metrics, service: service, published: true, online_transactions: 100, month: YearMonth.new(2017, 10),) metrics.save metrics = FactoryGirl.build(:monthly_service_metrics, service: service, published: true, online_transactions: 100, month: YearMonth.new(2017, 12),) metrics.save calc = MissingDataCalculator.new( department, TimePeriod.new(Date.new(2017, 9, 1), Date.new(2017, 12, 1)) ) expect(calc.missing_data[0].metrics[0][:months_missing]).to eq("September 2017, November 2017") end end end
package clocktest_test import ( "testing" "time" "github.com/stellar/go/support/clock" "github.com/stellar/go/support/clock/clocktest" "github.com/stretchr/testify/assert" ) // TestNewFixed tests that the time returned from the fixed clocks Now() // function is equal to the time given when creating the clock. func TestFixedSource_Now(t *testing.T) { timeNow := time.Date(2015, 9, 30, 17, 15, 54, 0, time.UTC) c := clock.Clock{Source: clocktest.FixedSource(timeNow)} assert.Equal(t, timeNow, c.Now()) } // TestNewFixed_compose tests that FixedSource can be used easily to change // time during a test. func TestFixedSource_compose(t *testing.T) { timeNow := time.Date(2015, 9, 30, 17, 15, 54, 0, time.UTC) c := clock.Clock{Source: clocktest.FixedSource(timeNow)} assert.Equal(t, timeNow, c.Now()) c.Source = clocktest.FixedSource(timeNow.AddDate(0, 0, 1)) assert.Equal(t, timeNow.AddDate(0, 0, 1), c.Now()) }
<filename>Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-5/Chapter05P11/test/junit/SalesAmountRevisedTest.java package junit; import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import main.SalesAmountRevised; /** * @author <NAME> * */ @RunWith(Parameterized.class) public class SalesAmountRevisedTest { private double amount; private double expected; public SalesAmountRevisedTest(double salesAmount, double expectedResult) { this.amount = salesAmount; this.expected = expectedResult; } @Parameters public static Collection<Object[]> commissionsList() { return Arrays.asList(new Object[][] { { 210833.35, 25000.00 }, { 10000, 900.0 }, { 95000, 11100.0 } }); } @Test public void testComputeCommission() { assertEquals(expected, SalesAmountRevised.computeCommission(amount), 0.01); } }
#!/bin/bash echo "Please enter a password:" read password if [ "$password" == "CorrectPassword" ]; then echo "Access granted" else echo "Incorrect password" fi
<reponame>joaoferr/Aula-03-Modulo-02 import express from 'express'; import { promises } from 'fs'; import moment from 'moment'; const { writeFile, readFile } = promises; import { addGrade, updateGrade, deleteGrade, findGrade, sumGrade, avgGrade, sortGrade, } from '../controllers/gradesControllers.js'; const router = express.Router(); router.get('/addGrade', async (req, res) => { try { let grades = req.body; res.send(await addGrade(grades)); } catch (err) { res.sendStatus(400).send({ error: err.message }); } }); router.get('/updateGrade', async (req, res) => { try { let grades = req.body; res.send(await updateGrade(grades)); } catch (err) { res.sendStatus(400).send({ error: err.message }); } }); router.get('/deleteGrade', async (req, res) => { try { let grades = req.body; res.send(await deleteGrade(grades)); } catch (err) { res.sendStatus(400).send({ error: err.message }); } }); router.get('/findGrade', async (req, res) => { try { let grades = req.body; res.send(await findGrade(grades)); } catch (err) { res.sendStatus(400).send({ error: err.message }); } }); router.get('/sumGrade', async (req, res) => { try { let grades = req.body; res.send(await sumGrade(grades)); } catch (err) { res.sendStatus(400).send({ error: err.message }); } }); router.get('/avgGrade', async (req, res) => { try { let grades = req.body; res.send(await avgGrade(grades)); } catch (err) { res.sendStatus(400).send({ error: err.message }); } }); router.get('/sortGrade', async (req, res) => { try { let grades = req.body; res.send(await sortGrade(grades)); } catch (err) { res.sendStatus(400).send({ error: err.message }); } }); export default router;
<gh_stars>1-10 import * as React from 'react'; import { Route, Switch, Redirect } from 'react-router-dom'; import { compose } from 'redux'; import { userIsNotLogged, userIsLogged, userDidNotAcceptTOS, userDidNotConfirmSecurityNotice } from 'modules/shared/checkAuth'; import { routes } from './constants'; import { Module } from '../../shared/types/app'; import { ChangePasswordLayout, ConfirmEmailLayout, LogoutLayout, TermsOfServiceLayout, ThankYouLayout, } from './view/containers'; import { layouts } from './view/layouts'; import SecurityNoticeLayout from './view/containers/SecurityNoticeLayout/SecurityNoticeLayout'; const userIsLoggedAndDidNotAcceptTOS = compose(userIsLogged, userDidNotAcceptTOS); const userIsLoggedAndDidNotReadSecurityNotice = compose(userIsLogged, userDidNotConfirmSecurityNotice); class AuthModule extends Module { public getRoutes() { return [ ( <Route key={routes.auth.getElementKey()} path={routes.auth.getPath()}> <Switch> <Route key={routes.auth.login.getElementKey()} path={routes.auth.login.getPath()} component={userIsNotLogged(layouts[routes.auth.login.getPath()] as any)} /> <Route key={routes.auth.register.getElementKey()} path={routes.auth.register.getPath()} component={userIsNotLogged(layouts[routes.auth.register.getPath()] as any)} /> <Route key={routes.auth['reset-password'].getElementKey()} path={routes.auth['reset-password'].getPath()} component={userIsNotLogged(layouts[routes.auth['reset-password'].getPath()] as any)} /> <Route key={routes.auth['thank-you'].getElementKey()} path={routes.auth['thank-you'].getPath()} component={userIsNotLogged(ThankYouLayout as any)} /> <Route key={routes.auth.tos.getElementKey()} path={routes.auth.tos.getPath()} component={userIsLoggedAndDidNotAcceptTOS(TermsOfServiceLayout as any)} /> <Route key={routes.auth['security-notice'].getElementKey()} path={routes.auth['security-notice'].getPath()} component={userIsLoggedAndDidNotReadSecurityNotice(SecurityNoticeLayout as any)} /> <Route key={routes.auth.logout.getElementKey()} path={routes.auth.logout.getPath()} component={LogoutLayout} /> <Route key={routes.auth['confirm-email'].getElementKey()} path={routes.auth['confirm-email'].getPath()} component={ConfirmEmailLayout} /> <Route key={routes.auth['restore-password'].getElementKey()} path={routes.auth['restore-password'].getPath()} component={ChangePasswordLayout} /> <Redirect exact from={routes.auth.getPath()} to={routes.auth.login.getPath()} /> </Switch> </Route> ), ]; } } export default AuthModule;
package com.hummer.core.jni; public class JSStaticFunction { String name; JSCallAsFunction callback; int attributes; public JSStaticFunction(String name, JSCallAsFunction callback, int attributes){ this.name = name; this.callback = callback; this.attributes = attributes; } }
<reponame>jedesah/scrooge<filename>scrooge-linter/src/main/scala/com/twitter/scrooge/linter/Linter.scala /* * Copyright 2014 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.scrooge.linter import com.twitter.finagle.NoStacktrace import com.twitter.logging.{ConsoleHandler, Formatter} import com.twitter.scrooge.ast._ import com.twitter.scrooge.frontend.{FileParseException, Importer, ThriftParser} import java.io.File import java.util.logging.{Logger, LogRecord, LogManager, Level} import scala.collection.mutable.ArrayBuffer object LintLevel extends Enumeration { type LintLevel = Value val Warning, Error = Value } import LintLevel._ case class LintMessage(msg: String, level: LintLevel = Warning) trait LintRule extends (Document => Iterable[LintMessage]) object LintRule { def all(rules: Seq[LintRule] = DefaultRules): LintRule = new LintRule { def apply(doc: Document): Seq[LintMessage] = rules flatMap { r => r(doc) } } val DefaultRules = Seq( Namespaces, RelativeIncludes, CamelCase, RequiredFieldDefault, Keywords ) object Namespaces extends LintRule { // All IDLs have a scala and a java namespace def apply(doc: Document) = { Seq("scala", "java").collect { case lang if doc.namespace(lang).isEmpty => LintMessage("Missing namespace: %s.".format(lang), Error) } } } object RelativeIncludes extends LintRule { // No relative includes def apply(doc: Document) = { doc.headers.collect { case Include(f, d) if f.contains("..") => LintMessage("Relative include path found: %s.".format(f), Error) } } } object CamelCase extends LintRule { // Struct names are UpperCamelCase. // Field names are lowerCamelCase. def apply(doc: Document) = { val messages = new ArrayBuffer[LintMessage] doc.defs.foreach { case struct: StructLike => if (!isTitleCase(struct.originalName)) { messages += LintMessage("Struct name %s is not UpperCamelCase. Should be: %s.".format( struct.originalName, Identifier.toTitleCase(struct.originalName))) } struct.fields.foreach { f => if (!isCamelCase(f.originalName)) { messages += LintMessage("Field name %s.%s is not lowerCamelCase. Should be: %s.".format( struct.originalName, f.originalName, Identifier.toCamelCase(f.originalName))) } } case _ => } messages } private[this] def isCamelCase(name: String): Boolean = { Identifier.toCamelCase(name) == name } private[this] def isTitleCase(name: String): Boolean = { Identifier.toTitleCase(name) == name } } object RequiredFieldDefault extends LintRule { // No default values for required fields def apply(doc: Document) = { doc.defs.collect { case struct: StructLike => struct.fields.collect { case f if f.requiredness == Requiredness.Required && f.default.nonEmpty => LintMessage("Required field %s.%s has a default value. Make it optional or remove the default.".format( struct.originalName, f.originalName), Error) } }.flatten } } object Keywords extends LintRule { // Struct and field names should not be keywords in Scala, Java, Ruby, Python, PHP. def apply(doc: Document) = { val messages = new ArrayBuffer[LintMessage] val identifiers = doc.defs.collect { case struct: StructLike => languageKeywords.foreach { case (lang, keywords) => if (keywords.contains(struct.originalName)) { messages += LintMessage( "Struct name %s is a %s keyword. Avoid using keywords as identifiers.".format( struct.originalName, lang)) } } val fieldNames = struct.fields.map(_.originalName).toSet for { (lang, keywords) <- languageKeywords intersection = keywords.intersect(fieldNames) if intersection.nonEmpty } messages += LintMessage("Fields in struct %s: %s are %s keywords. Avoid using keywords as identifiers.".format( struct.originalName, intersection.mkString(", "), lang)) } messages } private[this] val languageKeywords: Map[String, Set[String]] = Map( "scala" -> Set("abstract", "case", "catch", "class", "def", "do", "else", "extends", "false", "final", "finally", "for", "forSome", "if", "implicit", "import", "lazy", "match", "new", "null", "object", "override", "package", "private", "protected", "return", "sealed", "super", "this", "throw", "trait", "try", "true", "type", "val", "var", "while", "with", "yield"), "java" -> Set("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while"), "ruby" -> Set("BEGIN", "END", "__ENCODING__", "__END__", "__FILE__", "__LINE__", "alias", "and", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield"), "php" -> Set("__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "finally", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor", "yield"), "python" -> Set("and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield") ) // Returns a list of languages in which id is a keyword. private[this] def checkKeyword(id: String): Iterable[String] = { languageKeywords.collect { case (lang, keywords) if keywords.contains(id) => lang } } } } object ErrorLogLevel extends Level("LINT-ERROR", 999) object WarningLogLevel extends Level("LINT-WARN", 998) class Linter(cfg: Config, rules: Seq[LintRule] = LintRule.DefaultRules) { LogManager.getLogManager.reset private[this] val log = Logger.getLogger("linter") private[this] val formatter = new Formatter() { override def format(record: LogRecord) = "%s: %s%s".format(record.getLevel.getName, formatText(record), lineTerminator) } log.addHandler(new ConsoleHandler(formatter, None)) def error(msg: String) = log.log(ErrorLogLevel, msg) def warning(msg: String) = log.log(WarningLogLevel, msg) // Lint a document, returning the number of lint errors found. def apply( doc: Document ) : Int = { val messages = LintRule.all(rules)(doc) messages.foreach { case LintMessage(msg, Error) => error(msg) case LintMessage(msg, Warning) => warning(msg) } val errorCount = messages.count(_.level == Error) val warnCount = messages.count(_.level == Warning) if (errorCount + warnCount > 0) { warning("%d warnings and %d errors found".format(messages.size - errorCount, errorCount)) } errorCount } // Lint cfg.files and return the total number of lint errors found. def lint(): Int = { val importer = Importer(new File(".")) val parser = new ThriftParser(importer, cfg.strict, defaultOptional = false, skipIncludes = true) val errorCounts = cfg.files.map { inputFile => log.info("\n+ Linting %s".format(inputFile)) try { val doc0 = parser.parseFile(inputFile) apply(doc0) } catch { case e: FileParseException if (cfg.ignoreErrors) => e.printStackTrace() 1 } } errorCounts.sum } }
<reponame>Hannah-Abi/python-pro-21<gh_stars>0 # Write your solution here g1 = int(input("Please type in the first number: ")) g2 = int(input("Please type in the another number: ")) if (g1 > g2): print(f"The greater number was: {g1}") elif (g1 < g2): print(f"The greater number was: {g2}") else: print("The numbers are equal!")
// 1668. 트로피 진열 // 2020.03.29 // 탐색 #include<iostream> #include<vector> using namespace std; int main() { int n; cin >> n; vector<int> height(n); for (int i = 0; i < n; i++) { cin >> height[i]; } // 트러피가 1개일때는 왼쪽 오른쪽 모두 1 if (n == 1) { cout << 1 << endl << 1 << endl; } else { // 왼쪽에서 볼때 int top = height[0]; int left = 1; for (int i = 1; i < n; i++) { if (height[i] > top) { left++; top = height[i]; } } // 오른쪽에서 볼때 top = height[n - 1]; int right = 1; for (int i = n - 2; i >= 0; i--) { if (height[i] > top) { right++; top = height[i]; } } cout << left << endl << right << endl; } return 0; }
<reponame>lykmapipo/bipsms<filename>src/FakeTransport/fixtures/log.js 'use strict'; //dependencies var _ = require('lodash'); var { v4: uuidv4 } = require('uuid'); var moment = require('moment'); var randomNumber = require('random-number'); var sentDays = randomNumber({ min: -30, max: -15 }); var doneDays = randomNumber({ min: -14, max: -1 }); module.exports = exports = function (options, done) { //sms delivery report template var template = { bulkId: uuidv4(), messageId: uuidv4(), to: String(randomNumber({ min: 11111111111, max: 99999999999, integer: true })), from: String(randomNumber({ min: 11111111111, max: 99999999999, integer: true })), sentAt: moment(new Date()).add(sentDays, 'days'), doneAt: moment(new Date()).add(doneDays, 'days'), smsCount: randomNumber({ min: 0, max: 1 }), mccMnc: 22801, price: { pricePerMessage: options.pricePerMessage, currency: options.currency }, status: { id: 5, groupId: 3, groupName: 'DELIVERED', name: 'DELIVERED_TO_HANDSET', description: 'Message delivered to handset' }, error: { groupId: 0, groupName: 'OK', id: 0, name: 'NO_ERROR', description: 'No Error', permanent: false } }; var response; //prepare single message delivery report if (options.messageId) { var report = _.merge({}, template, { messageId: options.messageId, bulkId: options.bulkId }); response = { results: [report] }; } //prepare multi message delivery report else { var limit = options.limit || 50; var reports = _.range(0, limit).map(function () { return _.merge({}, template, { bulkId: options.bulkId }); }); response = { results: reports }; } done(null, response); };
osascript -e 'display notification "Set up a No Internet block today" with title "Focus Time" sound name "Pop"'
TERMUX_PKG_HOMEPAGE=https://sourceforge.net/projects/gpg-crypter/ TERMUX_PKG_DESCRIPTION="A graphical front-end to GnuPG(GPG) using the GTK3 toolkit and libgpgme" TERMUX_PKG_LICENSE="GPL-2.0" TERMUX_PKG_MAINTAINER="@termux" TERMUX_PKG_VERSION=0.4.1 TERMUX_PKG_REVISION=19 TERMUX_PKG_SRCURL=https://downloads.sourceforge.net/gpg-crypter/gpg-crypter-${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_SHA256=1f7e2b27bf4a27ecbb07bce9cd40d1c08477a3bd065ba7d1a75d1732e4bdc023 TERMUX_PKG_DEPENDS="atk, gdk-pixbuf, glib, gpgme, gtk3, libandroid-shmem, libassuan, libcairo, libgpg-error, pango, pinentry-gtk" TERMUX_PKG_RM_AFTER_INSTALL="lib/locale" termux_step_pre_configure() { export LIBS="-landroid-shmem" }
import torch def matrix_multiplication(A, B): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') A = torch.tensor(A).to(device) B = torch.tensor(B).to(device) return torch.matmul(A, B).cpu().numpy()
#!/bin/bash set -euo pipefail if [ ! -d node_modules ]; then npm install fi npm run build
<reponame>smagill/opensphere-desktop /** * HUD GUI layout management. */ package io.opensphere.core.hud.framework.layout;
# requires gsutil (sudo snap install google-cloud-sdk) #echo Downloading... mkdir quickdraw_background quickdraw_evaluation gsutil -m cp gs://quickdraw_dataset/full/simplified/*.ndjson quickdraw_background echo Unpacking... python rasterize.py quickdraw_background -n 1000 mv quickdraw_background/*.ndjson quickdraw_evaluation/ python rasterize.py quickdraw_evaluation -n 20 echo Processing... python preprocess.py quickdraw_background python preprocess.py quickdraw_evaluation echo Cleaning up... rm -r quickdraw_evaluation/*.ndjson
#!/usr/bin/env bash # # Copyright (c) 2020 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # MODEL_DIR=${MODEL_DIR-$PWD} MPI_NUM_PROCESSES=${MPI_NUM_PROCESSES:=1} TRAIN_STEPS=${TRAIN_STEPS:=100} if [ -z "${OUTPUT_DIR}" ]; then echo "The required environment variable OUTPUT_DIR has not been set" exit 1 fi # Create the output directory in case it doesn't already exist mkdir -p ${OUTPUT_DIR} if [ -z "${DATASET_DIR}" ]; then echo "The required environment variable DATASET_DIR has not been set" exit 1 fi if [ ! -d "${DATASET_DIR}" ]; then echo "The DATASET_DIR '${DATASET_DIR}' does not exist" exit 1 fi if [ -z "${TF_MODELS_DIR}" ]; then echo "The required environment variable TF_MODELS_DIR has not been set." echo "Set this variable to point to a clone of the tensorflow/models repository." exit 1 fi if [ ! -d "${TF_MODELS_DIR}" ]; then echo "The TF_MODELS_DIR '${TF_MODELS_DIR}' does not exist" echo "Set this variable to point to a clone of the tensorflow/models repository." exit 1 fi # Run training with one mpi process source "${MODEL_DIR}/quickstart/common/utils.sh" _command python ${MODEL_DIR}/benchmarks/launch_benchmark.py \ --data-location ${DATASET_DIR} \ --output-dir ${OUTPUT_DIR} \ --checkpoint ${OUTPUT_DIR} \ --model-source-dir ${TF_MODELS_DIR} \ --model-name ssd-resnet34 \ --framework tensorflow \ --precision bfloat16 \ --mode training \ --num-train-steps ${TRAIN_STEPS} \ --batch-size=100 \ --weight_decay=1e-4 \ --num_warmup_batches=20 \ --mpi_num_processes=${MPI_NUM_PROCESSES} \ --mpi_num_processes_per_socket=1
<filename>uvicore/support/str.py<gh_stars>10-100 import re def ucbreakup(value: str): """Breakup words with by - _ or camel and uppercase first letter of each word stripping non alphanumeric""" #dashes = re.compile('_|-') delimiter = '_' uppers = re.compile(r'(?<!^)(?=[A-Z])') nonalphanumeric = re.compile('[^0-9a-zA-Z\ _-]+') dashes = re.compile('\ |_|-') #value = dashes.sub(delimiter, value) value = uppers.sub(' ', value) value = nonalphanumeric.sub('', value) value = dashes.sub(' ', value) value = ucwords(value) #value = value.replace(' ', '') #value = uppers.sub(' ', value) return value def ucwords(value: str): """Uppercase first letter of each word but leaves rest of the word alone (keeps existing case)""" words = [] for word in value.split(' '): if word: words.append(word[0].upper() + word[1:]) return ' '.join(words) def ucfirst(value: str): """Uppercase first letter in sentence and leaves rest alone""" return value[0].upper() + value[1:] def title(value: str): """Uppsercase first letter of each word and forces lowercase on the rest of the word""" return value.title() def snake(value: str, delimiter: str = '_'): """Convert string to snake case foo_bar""" return slug(value, '_') def kebab(value: str): """Convert string to kebab case foo-bar""" #return snake(value, '-') return slug(value, '-') def studly(value: str): """Convert string to studly/pascal case FooBar""" value = ucbreakup(value) return value.replace(' ', '') def camel(value: str): """Convert string to camel case fooBar""" value = studly(value) #value = ucbreakup(value) value = value[0].lower() + value[1:] return value def slug(value: str, delimiter: str = '-'): """Slugify a string""" value = ucbreakup(value) return value.replace(' ', delimiter).lower() def words(value: str, length: int = 100, end: str = '...'): words = value.split(' ') if len(words) > length: return ' '.join(words[0:length]) + str(end) return value
#!/bin/sh # # Copyright (c) 2008 David Aguilar # test_description='git submodule sync These tests exercise the "git submodule sync" subcommand. ' . ./test-lib.sh test_expect_success setup ' echo file >file && git add file && test_tick && git commit -m upstream && git clone . super && git clone super submodule && ( cd submodule && git submodule add ../submodule sub-submodule && test_tick && git commit -m "sub-submodule" ) && ( cd super && git submodule add ../submodule submodule && test_tick && git commit -m "submodule" ) && git clone super super-clone && ( cd super-clone && git submodule update --init --recursive ) && git clone super empty-clone && ( cd empty-clone && git submodule init ) && git clone super top-only-clone && git clone super relative-clone && ( cd relative-clone && git submodule update --init --recursive ) && git clone super recursive-clone && ( cd recursive-clone && git submodule update --init --recursive ) ' test_expect_success 'change submodule' ' ( cd submodule && echo second line >>file && test_tick && git commit -a -m "change submodule" ) ' reset_submodule_urls () { local root root=$(pwd) && ( cd super-clone/submodule && git config remote.origin.url "$root/submodule" ) && ( cd super-clone/submodule/sub-submodule && git config remote.origin.url "$root/submodule" ) } test_expect_success 'change submodule url' ' ( cd super && cd submodule && git checkout master && git pull ) && mv submodule moved-submodule && ( cd moved-submodule && git config -f .gitmodules submodule.sub-submodule.url ../moved-submodule && test_tick && git commit -a -m moved-sub-submodule ) && ( cd super && git config -f .gitmodules submodule.submodule.url ../moved-submodule && test_tick && git commit -a -m moved-submodule ) ' test_expect_success '"git submodule sync" should update submodule URLs' ' ( cd super-clone && git pull --no-recurse-submodules && git submodule sync ) && test -d "$( cd super-clone/submodule && git config remote.origin.url )" && test ! -d "$( cd super-clone/submodule/sub-submodule && git config remote.origin.url )" && ( cd super-clone/submodule && git checkout master && git pull ) && ( cd super-clone && test -d "$(git config submodule.submodule.url)" ) ' test_expect_success '"git submodule sync --recursive" should update all submodule URLs' ' ( cd super-clone && ( cd submodule && git pull --no-recurse-submodules ) && git submodule sync --recursive ) && test -d "$( cd super-clone/submodule && git config remote.origin.url )" && test -d "$( cd super-clone/submodule/sub-submodule && git config remote.origin.url )" && ( cd super-clone/submodule/sub-submodule && git checkout master && git pull ) ' test_expect_success 'reset submodule URLs' ' reset_submodule_urls super-clone ' test_expect_success '"git submodule sync" should update submodule URLs - subdirectory' ' ( cd super-clone && git pull --no-recurse-submodules && mkdir -p sub && cd sub && git submodule sync >../../output ) && grep "\\.\\./submodule" output && test -d "$( cd super-clone/submodule && git config remote.origin.url )" && test ! -d "$( cd super-clone/submodule/sub-submodule && git config remote.origin.url )" && ( cd super-clone/submodule && git checkout master && git pull ) && ( cd super-clone && test -d "$(git config submodule.submodule.url)" ) ' test_expect_success '"git submodule sync --recursive" should update all submodule URLs - subdirectory' ' ( cd super-clone && ( cd submodule && git pull --no-recurse-submodules ) && mkdir -p sub && cd sub && git submodule sync --recursive >../../output ) && grep "\\.\\./submodule/sub-submodule" output && test -d "$( cd super-clone/submodule && git config remote.origin.url )" && test -d "$( cd super-clone/submodule/sub-submodule && git config remote.origin.url )" && ( cd super-clone/submodule/sub-submodule && git checkout master && git pull ) ' test_expect_success '"git submodule sync" should update known submodule URLs' ' ( cd empty-clone && git pull && git submodule sync && test -d "$(git config submodule.submodule.url)" ) ' test_expect_success '"git submodule sync" should not vivify uninteresting submodule' ' ( cd top-only-clone && git pull && git submodule sync && test -z "$(git config submodule.submodule.url)" && git submodule sync submodule && test -z "$(git config submodule.submodule.url)" ) ' test_expect_success '"git submodule sync" handles origin URL of the form foo' ' ( cd relative-clone && git remote set-url origin foo && git submodule sync && ( cd submodule && #actual fails with: "cannot strip off url foo test "$(git config remote.origin.url)" = "../submodule" ) ) ' test_expect_success '"git submodule sync" handles origin URL of the form foo/bar' ' ( cd relative-clone && git remote set-url origin foo/bar && git submodule sync && ( cd submodule && #actual foo/submodule test "$(git config remote.origin.url)" = "../foo/submodule" ) && ( cd submodule/sub-submodule && test "$(git config remote.origin.url)" != "../../foo/submodule" ) ) ' test_expect_success '"git submodule sync --recursive" propagates changes in origin' ' ( cd recursive-clone && git remote set-url origin foo/bar && git submodule sync --recursive && ( cd submodule && #actual foo/submodule test "$(git config remote.origin.url)" = "../foo/submodule" ) && ( cd submodule/sub-submodule && test "$(git config remote.origin.url)" = "../../foo/submodule" ) ) ' test_expect_success '"git submodule sync" handles origin URL of the form ./foo' ' ( cd relative-clone && git remote set-url origin ./foo && git submodule sync && ( cd submodule && #actual ./submodule test "$(git config remote.origin.url)" = "../submodule" ) ) ' test_expect_success '"git submodule sync" handles origin URL of the form ./foo/bar' ' ( cd relative-clone && git remote set-url origin ./foo/bar && git submodule sync && ( cd submodule && #actual ./foo/submodule test "$(git config remote.origin.url)" = "../foo/submodule" ) ) ' test_expect_success '"git submodule sync" handles origin URL of the form ../foo' ' ( cd relative-clone && git remote set-url origin ../foo && git submodule sync && ( cd submodule && #actual ../submodule test "$(git config remote.origin.url)" = "../../submodule" ) ) ' test_expect_success '"git submodule sync" handles origin URL of the form ../foo/bar' ' ( cd relative-clone && git remote set-url origin ../foo/bar && git submodule sync && ( cd submodule && #actual ../foo/submodule test "$(git config remote.origin.url)" = "../../foo/submodule" ) ) ' test_expect_success '"git submodule sync" handles origin URL of the form ../foo/bar with deeply nested submodule' ' ( cd relative-clone && git remote set-url origin ../foo/bar && mkdir -p a/b/c && ( cd a/b/c && git init && >.gitignore && git add .gitignore && test_tick && git commit -m "initial commit" ) && git submodule add ../bar/a/b/c ./a/b/c && git submodule sync && ( cd a/b/c && #actual ../foo/bar/a/b/c test "$(git config remote.origin.url)" = "../../../../foo/bar/a/b/c" ) ) ' test_done
/** * percentage between two numbers */ import util from "../util"; function percent(input, divided, round) { let divider = util.isString(input) ? Number(input) : input; divided = divided || 100; round = round || false; if (!util.isNumber(divider) || isNaN(divider)) return input; return round ? Math.round((divider / divided) * 100) : (divider / divided) * 100; } export default percent
<reponame>shin-kinoshita/dbflute-core<gh_stars>0 /* * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.dbflute.cbean.sqlclause; import java.util.List; import org.dbflute.cbean.sqlclause.orderby.OrderByClause; import org.dbflute.cbean.sqlclause.query.QueryClauseArranger; import org.dbflute.dbmeta.info.ColumnInfo; import org.dbflute.dbmeta.name.ColumnRealName; import org.dbflute.dbmeta.name.ColumnSqlName; import org.dbflute.dbway.DBDef; import org.dbflute.dbway.DBWay; import org.dbflute.dbway.WayOfMySQL.FullTextSearchModifier; import org.dbflute.util.Srl; /** * SqlClause for MySQL. * @author jflute */ public class SqlClauseMySql extends AbstractSqlClause { // =================================================================================== // Definition // ========== /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; // =================================================================================== // Attribute // ========= /** String of fetch-scope as sql-suffix. */ protected String _fetchScopeSqlSuffix = ""; /** String of lock as sql-suffix. */ protected String _lockSqlSuffix = ""; /** The binding value for paging as 'limit'. */ protected Integer _pagingBindingLimit; /** The binding value for paging as 'offset'. */ protected Integer _pagingBindingOffset; /** Does it suppress bind variable for paging? */ protected boolean _suppressPagingBinding; // =================================================================================== // Constructor // =========== /** * Constructor. * @param tableDbName The DB name of table. (NotNull) **/ public SqlClauseMySql(String tableDbName) { super(tableDbName); } // =================================================================================== // Main Override // ============= // ----------------------------------------------------- // Complete Clause // --------------- @Override public String getClause() { if (canFoundRows()) { return "select found_rows()"; // and sql_calc_found_rows is implemented at select-hint process } return super.getClause(); } protected boolean canFoundRows() { return canPagingCountLater() && isSelectClauseTypeNonUnionCount(); } // =================================================================================== // OrderBy Override // ================ @Override protected OrderByClause.OrderByNullsSetupper createOrderByNullsSetupper() { return createOrderByNullsSetupperByCaseWhen(); } // =================================================================================== // FetchScope Override // =================== /** * {@inheritDoc} */ protected void doFetchFirst() { doFetchPage(); } /** * {@inheritDoc} */ protected void doFetchPage() { if (_suppressPagingBinding) { _fetchScopeSqlSuffix = " limit " + getPageStartIndex() + ", " + getFetchSize(); } else { // mainly here _pagingBindingLimit = getFetchSize(); _pagingBindingOffset = getPageStartIndex(); _fetchScopeSqlSuffix = " limit /*pmb.sqlClause.pagingBindingOffset*/0, /*pmb.sqlClause.pagingBindingLimit*/0"; } } /** * {@inheritDoc} */ protected void doClearFetchPageClause() { _fetchScopeSqlSuffix = ""; } // =================================================================================== // Lock Override // ============= /** * {@inheritDoc} */ public void lockForUpdate() { _lockSqlSuffix = " for update"; } // =================================================================================== // Hint Override // ============= /** * {@inheritDoc} */ protected String createSelectHint() { final StringBuilder sb = new StringBuilder(); if (canSqlCalcFoundRows()) { sb.append(" sql_calc_found_rows"); // and found_rows() is implemented at getClause override } return sb.toString(); } protected boolean canSqlCalcFoundRows() { return isFetchNarrowingEffective() && canPagingCountLater() && isSelectClauseNonUnionSelect(); } /** * {@inheritDoc} */ protected String createFromBaseTableHint() { return ""; } /** * {@inheritDoc} */ protected String createFromHint() { return ""; } /** * {@inheritDoc} */ protected String createSqlSuffix() { return _fetchScopeSqlSuffix + _lockSqlSuffix; } // [DBFlute-0.7.5] // =================================================================================== // Query Update Override // ===================== @Override protected boolean isUpdateSubQueryUseLocalTableSupported() { return false; } @Override protected boolean isUpdateDirectJoinSupported() { return true; // MySQL can use 'update MEMBER dfloc inner join ...' } @Override protected boolean isUpdateTableAliasNameSupported() { return true; // MySQL needs 'update MEMBER dfloc ...' when it has relation } @Override protected boolean isDeleteTableAliasHintSupported() { return true; // MySQL needs 'delete dfloc from MEMBER dfloc ...' when it has relation } // [DBFlute-0.9.9.1C] // =================================================================================== // Collate Clause // ============== public static class CollateUTF8UnicodeArranger implements QueryClauseArranger { public String arrange(ColumnRealName columnRealName, String operand, String bindExpression, String rearOption) { return columnRealName + " collate utf8_unicode_ci " + operand + " " + bindExpression + rearOption; } } public static class CollateUTF8GeneralArranger implements QueryClauseArranger { public String arrange(ColumnRealName columnRealName, String operand, String bindExpression, String rearOption) { return columnRealName + " collate utf8_general_ci " + operand + " " + bindExpression + rearOption; } } public static class CollateUTF8MB4UnicodeArranger implements QueryClauseArranger { public String arrange(ColumnRealName columnRealName, String operand, String bindExpression, String rearOption) { return columnRealName + " collate utf8mb4_unicode_520_ci " + operand + " " + bindExpression + rearOption; } } // [DBFlute-0.9.5] // =================================================================================== // Full-Text Search // ================ /** * Build a condition string of match statement for full-text search. <br> * Bind variable is unused because the condition value should be literal in MySQL. * @param textColumnList The list of text column. (NotNull, NotEmpty, StringColumn, TargetTableColumn) * @param conditionValue The condition value embedded without binding (by MySQL restriction) but escaped. (NotNull) * @param modifier The modifier of full-text search. (NullAllowed: If the value is null, No modifier specified) * @param tableDbName The DB name of the target table. (NotNull) * @param aliasName The alias name of the target table. (NotNull) * @return The condition string of match statement. (NotNull) */ public String buildMatchCondition(List<ColumnInfo> textColumnList, String conditionValue, FullTextSearchModifier modifier, String tableDbName, String aliasName) { assertTextColumnList(textColumnList); assertVariousTextSearchResource(conditionValue, modifier, tableDbName, aliasName); final StringBuilder sb = new StringBuilder(); int index = 0; for (ColumnInfo columnInfo : textColumnList) { if (columnInfo == null) { continue; } assertTextColumnTable(tableDbName, columnInfo); assertTextColumnType(tableDbName, columnInfo); final ColumnSqlName columnSqlName = columnInfo.getColumnSqlName(); if (index > 0) { sb.append(","); } sb.append(aliasName).append(".").append(columnSqlName); ++index; } sb.insert(0, "match(").append(") against ('"); sb.append(escapeMatchConditionValue(conditionValue)).append("'"); if (modifier != null) { sb.append(" ").append(modifier.code()); } sb.append(")"); return sb.toString(); } protected String escapeMatchConditionValue(String conditionValue) { conditionValue = Srl.replace(conditionValue, "\\", "\\\\"); conditionValue = Srl.replace(conditionValue, "'", "''"); return conditionValue; } protected void assertTextColumnList(List<ColumnInfo> textColumnList) { if (textColumnList == null) { String msg = "The argument 'textColumnList' should not be null."; throw new IllegalArgumentException(msg); } if (textColumnList.isEmpty()) { String msg = "The argument 'textColumnList' should not be empty list."; throw new IllegalArgumentException(msg); } } protected void assertVariousTextSearchResource(String conditionValue, FullTextSearchModifier modifier, String tableDbName, String aliasName) { if (conditionValue == null || conditionValue.length() == 0) { String msg = "The argument 'conditionValue' should not be null or empty: " + conditionValue; throw new IllegalArgumentException(msg); } if (tableDbName == null || tableDbName.trim().length() == 0) { String msg = "The argument 'tableDbName' should not be null or trimmed-empty: " + tableDbName; throw new IllegalArgumentException(msg); } if (aliasName == null || aliasName.trim().length() == 0) { String msg = "The argument 'aliasName' should not be null or trimmed-empty: " + aliasName; throw new IllegalArgumentException(msg); } } protected void assertTextColumnTable(String tableDbName, ColumnInfo columnInfo) { final String tableOfColumn = columnInfo.getDBMeta().getTableDbName(); if (!tableOfColumn.equalsIgnoreCase(tableDbName)) { String msg = "The table of the text column should be '" + tableDbName + "'"; msg = msg + " but the table is '" + tableOfColumn + "': column=" + columnInfo; throw new IllegalArgumentException(msg); } } protected void assertTextColumnType(String tableDbName, ColumnInfo columnInfo) { if (!columnInfo.isObjectNativeTypeString()) { String msg = "The text column should be String type: column=" + columnInfo; throw new IllegalArgumentException(msg); } } // [DBFlute-1.0.3.1] // =================================================================================== // CursorSelect Option // =================== public boolean isCursorSelectByPagingAllowed() { // MySQL's cursor select has problems so allowed // (RepeatableRead is default on MySQL so safety relatively) return true; } // [DBFlute-0.9.8.4] // =================================================================================== // DBWay // ===== public DBWay dbway() { return DBDef.MySQL.dbway(); } // [DBFlute-1.0.4D] // =================================================================================== // Accessor // ======== public Integer getPagingBindingLimit() { // for parameter comment return _pagingBindingLimit; } public Integer getPagingBindingOffset() { // for parameter comment return _pagingBindingOffset; } public SqlClauseMySql suppressPagingBinding() { // for compatible? anyway, just in case _suppressPagingBinding = true; return this; } }
#!/usr/bin/env bats @test "go version" { run bash -c "docker exec di-circleci-infra-image-slim-edge go version" [[ "${output}" =~ "1.16.5" ]] } @test "rust version" { run bash -c "docker exec di-circleci-infra-image-slim-edge rustc --version" [[ "${output}" =~ "1.53.0" ]] } @test "python3 version" { run bash -c "docker exec di-circleci-infra-image-slim-edge python -V" [[ "${output}" =~ "3.9.2" ]] } @test "ruby version" { run bash -c "docker exec di-circleci-infra-image-slim-edge ruby -v" [[ "${output}" =~ "2.7.3" ]] } @test "evaluate installed pip packages and versions" { run bash -c "docker exec di-circleci-infra-image-slim-edge pip list --format json" [[ "${output}" =~ "{\"name\": \"setuptools\", \"version\": \"57.1.0\"}" ]] [[ "${output}" =~ "{\"name\": \"awscli\", \"version\": \"1.19.105\"}" ]] [[ "${output}" =~ "{\"name\": \"invoke\", \"version\": \"1.5.0\"}" ]] [[ "${output}" =~ "{\"name\": \"hvac\", \"version\": \"0.10.14\"}" ]] [[ "${output}" =~ "{\"name\": \"requests\", \"version\": \"2.25.1\"}" ]] [[ "${output}" =~ "{\"name\": \"Jinja2\", \"version\": \"3.0.1\"}" ]] [[ "${output}" =~ "{\"name\": \"pylint\", \"version\": \"2.8.3\"}" ]] [[ "${output}" =~ "{\"name\": \"yamllint\", \"version\": \"1.26.1\"}" ]] } # so far, can't figure out how to test version # # @test "pip version" { # run bash -c "docker exec di-circleci-infra-image-slim-edge pip -V" # [[ "${output}" =~ "20.3.4" ]] # } @test "awscli version" { run bash -c "docker exec di-circleci-infra-image-slim-edge aws --version" [[ "${output}" =~ "1.19.105" ]] } @test "invoke version" { run bash -c "docker exec di-circleci-infra-image-slim-edge invoke -V" [[ "${output}" =~ "1.5.0" ]] } @test "awspec version" { run bash -c "docker exec di-circleci-infra-image-slim-edge awspec -v" [[ "${output}" =~ "1.24.2" ]] } @test "inspec version" { run bash -c "docker exec di-circleci-infra-image-slim-edge inspec -v" [[ "${output}" =~ "4.38.3" ]] } @test "terraform version" { run bash -c "docker exec di-circleci-infra-image-slim-edge terraform version" [[ "${output}" =~ "1.0.2" ]] } @test "tflint version" { run bash -c "docker exec di-circleci-infra-image-slim-edge tflint --version" [[ "${output}" =~ "0.29.1" ]] } @test "kubectl version" { run bash -c "docker exec di-circleci-infra-image-slim-edge kubectl version --client=true" [[ "${output}" =~ "1.21.1" ]] } @test "helm version" { run bash -c "docker exec di-circleci-infra-image-slim-edge helm version" [[ "${output}" =~ "3.6.1" ]] } @test "sonobuoy version" { run bash -c "docker exec di-circleci-infra-image-slim-edge sonobuoy version" [[ "${output}" =~ "0.52.0" ]] } @test "istioctl version" { run bash -c "docker exec di-circleci-infra-image-slim-edge istioctl version --remote=false" [[ "${output}" =~ "1.10.2" ]] } @test "vault version" { run bash -c "docker exec di-circleci-infra-image-slim-edge vault version" [[ "${output}" =~ "1.7.3" ]] } @test "docker-compose version" { run bash -c "docker exec di-circleci-infra-image-slim-edge docker-compose --version" [[ "${output}" =~ "1.29.2" ]] }
#!/usr/bin/env bash NOTIFY_ICON=/usr/share/icons/Papirus/32x32/apps/system-software-update.svg get_total_updates() { UPDATES=$(checkupdates 2>/dev/null | wc -l); } while true; do get_total_updates # notify user of updates if hash notify-send &>/dev/null; then if (( UPDATES > 50 )); then notify-send -u critical -i $NOTIFY_ICON \ "You really need to update!!" "$UPDATES New packages" elif (( UPDATES > 25 )); then notify-send -u normal -i $NOTIFY_ICON \ "You should update soon" "$UPDATES New packages" elif (( UPDATES > 2 )); then notify-send -u low -i $NOTIFY_ICON \ "$UPDATES New packages" fi fi # when there are updates available # every 10 seconds another check for updates is done while (( UPDATES > 0 )); do if (( UPDATES == 1 )); then echo " $UPDATES" elif (( UPDATES > 1 )); then echo " $UPDATES" else echo " U2D" fi sleep 10 get_total_updates done # when no updates are available, use a longer loop, this saves on CPU # and network uptime, only checking once every 30 min for new updates while (( UPDATES == 0 )); do echo " U2D" sleep 1800 get_total_updates done done
#!/bin/bash rm -fR .clone_defs 2> /dev/null mkdir .clone_defs cd .clone_defs git init git remote add origin -f git@github.com:rive-app/rive.git git config core.sparseCheckout true echo '/dev/defs/*' > .git/info/sparse-checkout git pull origin master rm -fR ../defs mv dev/defs ../ cd .. rm -fR .clone_defs
import { Resolver, Query, Mutation, Args, Int } from '@nestjs/graphql'; import { GameService } from './game.service'; import { Game } from './entities/game.entity'; import { CreateGameInput } from './dto/create-game.input'; import { UpdateGameInput } from './dto/update-game.input'; @Resolver(() => Game) export class GameResolver { constructor(private readonly gameService: GameService) {} @Mutation(() => Game) createGame(@Args('createGameInput') createGameInput: CreateGameInput) { return this.gameService.create(createGameInput); } @Query(() => [Game], { name: 'gameList' }) findAll() { return this.gameService.findAll(); } @Query(() => Game, { name: 'game' }) findOne(@Args('id', { type: () => Int }) id: number) { return this.gameService.findOne(id); } @Mutation(() => Game) updateGame(@Args('updateGameInput') updateGameInput: UpdateGameInput) { return this.gameService.update(updateGameInput.id, updateGameInput); } @Mutation(() => Game) removeGame(@Args('id', { type: () => Int }) id: number) { return this.gameService.remove(id); } }
import Joi from 'joi'; export declare const ModelSchema: Joi.ObjectSchema<any>;
#! /bin/bash # # must be run after base-notebook.sh # may be run before or after scipy-notebook.sh # # This is just a shell script version of # https://github.com/jupyter/docker-stacks/blob/master/r-notebook/Dockerfile # # We are blindly assuming the needed Linux distro packages are already installed, such as: # fonts-dejavu # unixodbc # unixodbc-dev # r-cran-rodbc # gfortran # gcc MINICONDA_VERSION=4.6.14 CONDA_VERSION=4.7.10 CONDA_DIR=$HOME/miniconda3 PATH=$CONDA_DIR/bin:$PATH #verify that conda is found in $HOME/miniconda3/bin echo `which conda` conda install --quiet --yes \ 'r-base=3.6.1' \ 'r-rodbc=1.3*' \ 'unixodbc=2.3.*' \ 'r-irkernel=1.0*' \ 'r-plyr=1.8*' \ 'r-devtools=2.0*' \ 'r-tidyverse=1.2*' \ 'r-shiny=1.3*' \ 'r-rmarkdown=1.14*' \ 'r-forecast=8.7*' \ 'r-rsqlite=2.1*' \ 'r-reshape2=1.4*' \ 'r-nycflights13=1.0*' \ 'r-caret=6.0*' \ 'r-rcurl=1.95*' \ 'r-crayon=1.3*' \ 'r-randomforest=4.6*' \ 'r-htmltools=0.3*' \ 'r-sparklyr=1.0*' \ 'r-htmlwidgets=1.3*' \ 'r-hexbin=1.27*' # not really sure why this is done as a separate # run of conda, just mimicking Dockerfile conda install --quiet --yes r-e1071
package knokko.container; import java.util.ArrayList; import knokko.main.HyperCombat; import knokko.recipes.RecipesIngotEnchanter; import knokko.slots.SlotBattery; import knokko.slots.SlotOutputIngotEnchanter; import knokko.tileentity.TileEntityIngotEnchanter; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ContainerIngotEnchanter extends Container { private final IInventory ingotEnchanter; private final int sizeInventory; private int ticksEnchantingItemSoFar; private int ticksPerItem; private int timeCanEnchant; private int energy; private int enoughEnergy; private int[] slots = new int[6]; public boolean config; public ContainerIngotEnchanter(InventoryPlayer parInventoryPlayer, IInventory parIInventory){ inventorySlots = new ArrayList(){ public ContainerIngotEnchanter container = ContainerIngotEnchanter.this; @Override public int size(){ return container.config ? 0 : super.size(); } }; ingotEnchanter = parIInventory; sizeInventory = ingotEnchanter.getSizeInventory(); addSlotToContainer(new Slot(ingotEnchanter, TileEntityIngotEnchanter.slotEnum.INPUT_SLOT.ordinal(), 48, 15)); addSlotToContainer(new Slot(ingotEnchanter, TileEntityIngotEnchanter.slotEnum.SPECIAL_SLOT.ordinal(), 112, 15)); addSlotToContainer(new SlotOutputIngotEnchanter(parInventoryPlayer.player, ingotEnchanter, TileEntityIngotEnchanter.slotEnum.OUTPUT_SLOT.ordinal(), 80, 35)); addSlotToContainer(new SlotBattery(ingotEnchanter, TileEntityIngotEnchanter.slotEnum.BATTERY_SLOT.ordinal(), 44, 54)); int i; for (i = 0; i < 3; ++i){ for (int j = 0; j < 9; ++j){ addSlotToContainer(new Slot(parInventoryPlayer, j+i*9+9, 8+j*18, 84+i*18)); } } for (i = 0; i < 9; ++i){ addSlotToContainer(new Slot(parInventoryPlayer, i, 8 + i * 18, 142)); } } @Override public void addCraftingToCrafters(ICrafting listener){ super.addCraftingToCrafters(listener); listener.func_175173_a(this, ingotEnchanter); } /** * Looks for changes made in the container, sends them to every listener. */ @Override public void detectAndSendChanges(){ super.detectAndSendChanges(); for (int i = 0; i < crafters.size(); ++i){ ICrafting icrafting = (ICrafting)crafters.get(i); if (ticksEnchantingItemSoFar != ingotEnchanter.getField(2)) icrafting.sendProgressBarUpdate(this, 2, ingotEnchanter.getField(2)); if (timeCanEnchant != ingotEnchanter.getField(0)) icrafting.sendProgressBarUpdate(this, 0, ingotEnchanter.getField(0)); if (ticksPerItem != ingotEnchanter.getField(3)) icrafting.sendProgressBarUpdate(this, 3, ingotEnchanter.getField(3)); if(energy != ingotEnchanter.getField(4)) icrafting.sendProgressBarUpdate(this, 4, ingotEnchanter.getField(4)); if(enoughEnergy != ingotEnchanter.getField(5)) icrafting.sendProgressBarUpdate(this, 5, ingotEnchanter.getField(5)); int t = 0; while(t < slots.length){ if(slots[t] != ingotEnchanter.getField(6 + t)) icrafting.sendProgressBarUpdate(this, 6 + t, ingotEnchanter.getField(6 + t)); ++t; } } ticksEnchantingItemSoFar = ingotEnchanter.getField(2); timeCanEnchant = ingotEnchanter.getField(0); ticksPerItem = ingotEnchanter.getField(3); energy = ingotEnchanter.getField(4); enoughEnergy = ingotEnchanter.getField(5); int t = 0; while(t < slots.length){ slots[t] = ingotEnchanter.getField(6 + t); ++t; } } @Override @SideOnly(Side.CLIENT) public void updateProgressBar(int id, int data){ ingotEnchanter.setField(id, data); } @Override public boolean canInteractWith(EntityPlayer playerIn){ return ingotEnchanter.isUseableByPlayer(playerIn); } @Override public ItemStack transferStackInSlot(EntityPlayer playerIn, int slotIndex){ ItemStack itemStack1 = null; Slot slot = (Slot)inventorySlots.get(slotIndex); if (slot != null && slot.getHasStack()){ ItemStack itemStack2 = slot.getStack(); itemStack1 = itemStack2.copy(); if (slotIndex == TileEntityIngotEnchanter.slotEnum.OUTPUT_SLOT.ordinal()){ if (!mergeItemStack(itemStack2, sizeInventory, sizeInventory+36, true)) return null; slot.onSlotChange(itemStack2, itemStack1); } else if (slotIndex != TileEntityIngotEnchanter.slotEnum.INPUT_SLOT.ordinal()){ if (RecipesIngotEnchanter.instance().getEnchantingResult(itemStack2, ingotEnchanter.getStackInSlot(TileEntityIngotEnchanter.slotEnum.SPECIAL_SLOT.ordinal())) != null){ if (!mergeItemStack(itemStack2, 0, 1, false)) return null; } else if (slotIndex >= sizeInventory && slotIndex < sizeInventory+27){ if (!mergeItemStack(itemStack2, sizeInventory+27, sizeInventory+36, false)) return null; } else if (slotIndex >= sizeInventory+27 && slotIndex < sizeInventory+36 && !mergeItemStack(itemStack2, sizeInventory+1, sizeInventory+27, false)) return null; } else if (!mergeItemStack(itemStack2, sizeInventory, sizeInventory+36, false)) return null; if (itemStack2.stackSize == 0) slot.putStack((ItemStack)null); else slot.onSlotChanged(); if (itemStack2.stackSize == itemStack1.stackSize) return null; slot.onPickupFromSlot(playerIn, itemStack2); } return itemStack1; } }
module xor_and_module (input [7:0] a, input [7:0] b, output [7:0] c); reg [7:0] temp0, temp1; always@(*) begin temp0 = a ^ b; temp1 = a & b; c = temp0 & temp1; end endmodule
<filename>src/service/WishListService.java package service; import domain.Product; import domain.WishList; import mapper.WishListMapper; import utility.UnitOfWork; public class WishListService { private WishListMapper wishListMapper = new WishListMapper(); public void createWishList(WishList wishList) { UnitOfWork.newCurrent(); UnitOfWork.getCurrent().registerNew(wishList); UnitOfWork.getCurrent().commit(); } public void updateWishList(WishList wishList) { UnitOfWork.newCurrent(); UnitOfWork.getCurrent().registerNew(wishList); UnitOfWork.getCurrent().commit(); } public void DeleteFromWishList(WishList wishList, Product product) { wishList.setToDelete(product); UnitOfWork.newCurrent(); UnitOfWork.getCurrent().registerDeleted(wishList); UnitOfWork.getCurrent().commit(); } public WishList findByUserId(WishList wishList) { return wishListMapper.findWithId(wishList); } public WishList findByUserAndProductId(WishList wishList, Product product) { return wishListMapper.findByProductAndUserId(wishList, product); } }
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; CREATE TABLE IF NOT EXISTS users( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, updated_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL, name VARCHAR(100) NOT NULL, about VARCHAR NOT NULL );
# lottery_b4705a5d67c5507773016a2bbd2440ca python3 open_lth.py lottery --num_workers 4 --default_hparams=mnist_lenet_300_100 --model_name mnist_lenet_300_300_100 --level=16 --replicate=$replicate # lottery_e6ed6df2d24f7195508e3b6699972146 python3 open_lth.py lottery --num_workers 4 --default_hparams=mnist_lenet_300_100 --model_name mnist_lenet_300_300_300_100 --level=16 --replicate=$replicate # lottery_338d12765906cd84453d3c3ed830dd2b python3 open_lth.py lottery --num_workers 4 --default_hparams=mnist_lenet_300_100 --model_name mnist_lenet_300_300_300_300_100 --level=16 --replicate=$replicate # From mnist_lenet_300_300_300_100 -> mnist_lenet_300_300_300_300_100 export source_model="mnist_lenet_300_300_300_100" export target_model="mnist_lenet_300_300_300_300_100" export mapping="0:0;1:1,2;2:3" python3 open_lth.py lottery_branch change_depth --num_workers 4 --default_hparams=mnist_lenet_300_100 \ --model_name $source_model --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=10 # From mnist_lenet_300_300_300_100 -> mnist_lenet_300_300_100 export source_model="mnist_lenet_300_300_300_100" export target_model="mnist_lenet_300_300_100" export mapping="0:0;1:1" python3 open_lth.py lottery_branch change_depth --num_workers 4 --default_hparams=mnist_lenet_300_100 \ --model_name $source_model --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=10 # From mnist_lenet_300_300_100 -> mnist_lenet_300_300_300_100 export source_model="mnist_lenet_300_300_100" export target_model="mnist_lenet_300_300_300_100" export mapping="0:0;1:1,2" python3 open_lth.py lottery_branch change_depth --num_workers 4 --default_hparams=mnist_lenet_300_100 \ --model_name $source_model --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=10 # From mnist_lenet_300_300_100 -> mnist_lenet_300_300_300_300_100 export source_model="mnist_lenet_300_300_100" export target_model="mnist_lenet_300_300_300_300_100" export mapping="0:0;1:1,2,3" python3 open_lth.py lottery_branch change_depth --num_workers 4 --default_hparams=mnist_lenet_300_100 \ --model_name $source_model --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=10 # From mnist_lenet_300_300_300_300_100 -> mnist_lenet_300_300_100 export source_model="mnist_lenet_300_300_300_300_100" export target_model="mnist_lenet_300_300_100" export mapping="0:0;1:1" python3 open_lth.py lottery_branch change_depth --num_workers 4 --default_hparams=mnist_lenet_300_100 \ --model_name $source_model --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=10 # From mnist_lenet_300_300_300_300_100 -> mnist_lenet_300_300_300_100 export source_model="mnist_lenet_300_300_300_300_100" export target_model="mnist_lenet_300_300_300_100" export mapping="0:0;1:1;2:2" python3 open_lth.py lottery_branch change_depth --num_workers 4 --default_hparams=mnist_lenet_300_100 \ --model_name $source_model --replicate=$replicate \ --target_model_name $target_model --block_mapping "${mapping}" --levels=10
<reponame>zhuofdeng/advent-of-code-2021 export class BingoBoard { private numbers: string[][] = []; private won = false; constructor(input: string) { const rows = input.split('\n'); rows.forEach((row, index) => { this.numbers[index] = row.split(' '); this.numbers[index] = this.numbers[index].filter((num) => num !== ''); }); } public get hasWon() { return this.won; } public checkNumber = (number: string) => { // check all the number to see if it exists on the board this.numbers.forEach((row) => { // mark the number if it exists const index = row.indexOf(number); row[index] = '-1'; }); // check for winning condition. // 1. check for all rows. this.numbers.forEach((row) => { if (row.filter((nums) => nums !== '-1').length === 0) { this.won = true; } }); const columns = this.numbers[0].length; let column = 0; // 2. check for all columns. if (this.won === false) { for(column = 0; column < columns; column++) { const columnNumbers: string[] = []; this.numbers.forEach((row) => { columnNumbers.push(row[column]) }); if (columnNumbers.filter((num) => num !== '-1').length === 0) { this.won = true; } } } // 3. check Diagonal if (this.won === false) { const diagonalNumbers: string[] = []; for(column = 0; column < columns; column++) { this.numbers.forEach((row) => { diagonalNumbers.push(row[column]); }) } if (diagonalNumbers.filter((num) => num !== '-1').length === 0) { this.won = true; } } } public getScores = (): number => { if (this.won === true) { let totalScore = 0; this.numbers.forEach((row) => { row.forEach((element) => { const value = parseInt(element); if (value > -1) { totalScore += value; } }); }); return totalScore; } return -1; } }
<filename>server/node/src/main/java/org/kaaproject/kaa/server/admin/controller/CtlController.java /* * Copyright 2014-2016 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.server.admin.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.kaaproject.kaa.common.dto.ctl.CTLSchemaDto; import org.kaaproject.kaa.common.dto.ctl.CTLSchemaExportMethod; import org.kaaproject.kaa.common.dto.ctl.CTLSchemaMetaInfoDto; import org.kaaproject.kaa.common.dto.file.FileData; import org.kaaproject.kaa.server.admin.services.util.Utils; import org.kaaproject.kaa.server.admin.servlet.ServletUtils; import org.kaaproject.kaa.server.admin.shared.services.KaaAdminServiceException; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; @Api(value = "Common Type Library", description = "Provides function for manage CTL", basePath = "/kaaAdmin/rest") @Controller public class CtlController extends AbstractAdminController { /** * The Constant BUFFER. */ private static final int BUFFER = 1024 * 100; /** * Saves a CTL schema. * * @param body the ctl body * @param applicationToken the application token * @param tenantId id of the tenant * @return CTL schema info * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Create CTL schema", notes = "Creates a CTL schema with application token. Only authorized users are allowed to perform this operation.") @ApiResponses(value = { @ApiResponse(code = 400, message = "The CTL schema body provided is invalid"), @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The tenant ID of the CTL schema does not match the tenant ID of the authenticated user"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/saveSchema", params = {"body"}, method = RequestMethod.POST) @ResponseBody public CTLSchemaDto saveCTLSchemaWithAppToken( @ApiParam(name = "body", value = "The CTL schema structure", required = true) @RequestParam String body, @ApiParam(name = "tenantId", value = "A unique tenant identifier", required = false) @RequestParam(required = false) String tenantId, @ApiParam(name = "applicationToken", value = "A unique auto-generated application identifier", required = false) @RequestParam(required = false) String applicationToken) throws KaaAdminServiceException { return ctlService.saveCTLSchemaWithAppToken(body, tenantId, applicationToken); } /** * Removes a CTL schema by its fully qualified name and version number. * * @param fqn the fqn * @param version the version * @param tenantId id of the tenant * @param applicationToken the application token * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Delete CTL schema", notes = "Deletes a CTL schema. Only authorized users are allowed to perform this operation.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The tenant ID of the CTL schema does not match the tenant ID of the authenticated user"), @ApiResponse(code = 404, message = "A CTL schema with the specified fully qualified name, version number, tenant and application identifiers " + "does not exist"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/deleteSchema", params = {"fqn", "version"}, method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void deleteCTLSchemaByFqnVersionTenantIdAndApplicationToken( @ApiParam(name = "fqn", value = "The fully qualified name of the CTL schema", required = true) @RequestParam String fqn, @ApiParam(name = "version", value = "The version number of the CTL schema", required = true) @RequestParam int version, @ApiParam(name = "tenantId", value = "A unique tenant identifier", required = false) @RequestParam(required = false) String tenantId, @ApiParam(name = "applicationToken", value = "A unique auto-generated application identifier", required = false) @RequestParam(required = false) String applicationToken) throws KaaAdminServiceException { ctlService.deleteCTLSchemaByFqnVersionTenantIdAndApplicationToken(fqn, version, tenantId, applicationToken); } /** * Retrieves a CTL schema by its fully qualified name and version number. * * @param fqn the fqn * @param version the version * @param tenantId id of the tenant * @param applicationToken the application token * @return CTL schema info * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Get CTL schema", notes = "Returns a CTL schema. Only authorized users are allowed to perform this operation.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The tenant ID of the CTL schema does not match the tenant ID of the authenticated user"), @ApiResponse(code = 404, message = "A CTL schema with the specified fully qualified name and version number does not exist."), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/getSchema", params = {"fqn", "version"}, method = RequestMethod.GET) @ResponseBody public CTLSchemaDto getCTLSchemaByFqnVersionTenantIdAndApplicationToken( @ApiParam(name = "fqn", value = "The fully qualified name of the CTL schema", required = true) @RequestParam String fqn, @ApiParam(name = "version", value = "The version number of the CTL schema", required = true) @RequestParam int version, @ApiParam(name = "tenantId", value = "A unique tenant identifier", required = false) @RequestParam(required = false) String tenantId, @ApiParam(name = "applicationToken", value = "A unique auto-generated application identifier", required = false) @RequestParam(required = false) String applicationToken) throws KaaAdminServiceException { return ctlService.getCTLSchemaByFqnVersionTenantIdAndApplicationToken(fqn, version, tenantId, applicationToken); } /** * Retrieves a CTL schema by its id. * * @param id the CTL schema id * @return CTL schema info * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Get CTL schema by it's id", notes = "Returns a CTL schema. Only authorized users are allowed to perform this operation.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The tenant ID of the CTL schema does not match the tenant ID of the authenticated user"), @ApiResponse(code = 404, message = "A CTL schema with the specified id does not exist."), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/getSchemaById", params = {"id"}, method = RequestMethod.GET) @ResponseBody public CTLSchemaDto getCTLSchemaById( @ApiParam(name = "id", value = "A unique CTL schema identifier", required = true) @RequestParam String id) throws KaaAdminServiceException { return ctlService.getCTLSchemaById(id); } /** * Checks if CTL schema with same fqn is already exists in the sibling application. * * @param fqn the fqn * @param tenantId id of the tenant * @param applicationToken the application token * @return true if CTL schema with same fqn is already exists in other scope * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Check CTL schema FQN", notes = "Checks if CTL schema with same fqn is already exists in the sibling application. Only authorized users are allowed to perform this " + "operation.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The Tenant ID of the CTL schema does not match the Tenant ID of the authenticated user"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/checkFqn", params = {"fqn"}, method = RequestMethod.GET) @ResponseBody public boolean checkFqnExistsWithAppToken( @ApiParam(name = "fqn", value = "The fully qualified name of the CTL schema", required = true) @RequestParam String fqn, @ApiParam(name = "tenantId", value = "A unique tenant identifier", required = false) @RequestParam(required = false) String tenantId, @ApiParam(name = "applicationToken", value = "A unique auto-generated application identifier", required = false) @RequestParam(required = false) String applicationToken) throws KaaAdminServiceException { return ctlService.checkFqnExistsWithAppToken(fqn, tenantId, applicationToken); } /** * Promote existing CTL schema meta info from application to tenant scope * * @param applicationId the id of application where schema was created * @param fqn the fqn of promoting CTL schema * @return CTLSchemaMetaInfoDto the promoted CTL schema meta info object. * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Promote CTL schema from application scope to Tenant", notes = "Promote existing CTL schema meta info scope from application to tenant. Only authorized users are allowed to perform this operation.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The Tenant ID of the CTL schema does not match the Tenant ID of the authenticated user"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/promoteScopeToTenant", method = RequestMethod.POST) @ResponseBody public CTLSchemaMetaInfoDto promoteScopeToTenant( @ApiParam(name = "applicationId", value = "A unique application identifier", required = true) @RequestParam String applicationId, @ApiParam(name = "fqn", value = "The fully qualified name of the CTL schema", required = true) @RequestParam String fqn) throws KaaAdminServiceException { return ctlService.promoteScopeToTenant(applicationId, fqn); } /** * Retrieves a list of available system CTL schemas. * * @return CTL schema metadata list * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Get system CTL schemas", notes = "Returns a list of available system CTL schemas metadata. Only authorized users are allowed to perform this operation.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/getSystemSchemas", method = RequestMethod.GET) @ResponseBody public List<CTLSchemaMetaInfoDto> getSystemLevelCTLSchemas() throws KaaAdminServiceException { return ctlService.getSystemLevelCTLSchemas(); } /** * Retrieves a list of available CTL schemas for tenant. * * @return CTL schema metadata list * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Get tenant CTL schemas", notes = "Returns a list of available CTL schemas metadata for current tenant. The current user must have one of the following roles: " + "TENANT_ADMIN, TENANT_DEVELOPER or TENANT_USER.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/getTenantSchemas", method = RequestMethod.GET) @ResponseBody public List<CTLSchemaMetaInfoDto> getTenantLevelCTLSchemas() throws KaaAdminServiceException { return ctlService.getTenantLevelCTLSchemas(); } /** * Retrieves a list of available CTL schemas for application. * * @param applicationToken the application token * @return CTL schema metadata list * @throws KaaAdminServiceException the kaa admin service exception */ @ApiOperation(value = "Get application CTL schemas", notes = "Returns a list of available CTL schemas metadata for an application. The current user must have one of the following roles: " + "TENANT_DEVELOPER or TENANT_USER.") @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The authenticated user does not have the required role (TENANT_DEVELOPER, or TENANT_USER) or Tenant ID of " + "the application does not match the Tenant ID of the user"), @ApiResponse(code = 404, message = "An application with the specified applicationToken does not exist"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/getApplicationSchemas/{applicationToken}", method = RequestMethod.GET) @ResponseBody public List<CTLSchemaMetaInfoDto> getApplicationLevelCTLSchemasByAppToken( @ApiParam(name = "applicationToken", value = "A unique auto-generated application identifier", required = true) @PathVariable String applicationToken) throws KaaAdminServiceException { return ctlService.getApplicationLevelCTLSchemasByAppToken(applicationToken); } /** * Exports a CTL schema and, depending on the export method specified, all * of its dependencies. * * @param fqn - the schema fqn * @param version - the schema version * @param method - the schema export method * @param applicationToken the application token * @param request - the http request * @param response - the http response * @throws KaaAdminServiceException the kaa admin service exception * @see CTLSchemaExportMethod */ @ApiOperation(value = "Export CTL schema", notes = "Exports a CTL schema and, depending on the export method specified, all of its dependencies. Only authorized users are allowed to " + "perform this operation.") @ApiResponses(value = { @ApiResponse(code = 400, message = "Unknown export method specified"), @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The authenticated user does not have the required role (TENANT_DEVELOPER or TENANT_USER) or the Tenant ID " + "of the application does not match the Tenant ID of the authenticated user"), @ApiResponse(code = 404, message = "The CTL schema with the given fqn, version and application Id does not exist"), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/exportSchema", params = {"fqn", "version", "method"}, method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) public void exportCTLSchemaByAppToken( @ApiParam(name = "fqn", value = "The fully qualified name of the CTL schema", required = true) @RequestParam String fqn, @ApiParam(name = "version", value = "The version number of the CTL schema", required = true) @RequestParam int version, @ApiParam(name = "method", value = "The schema export method (either SHALLOW, FLAT, DEEP or LIBRARY)", required = true) @RequestParam String method, @ApiParam(name = "applicationToken", value = "A unique auto-generated application identifier", required = false) @RequestParam(required = false) String applicationToken, HttpServletRequest request, HttpServletResponse response) throws KaaAdminServiceException { try { FileData output = ctlService.exportCTLSchemaByAppToken(fqn, version, applicationToken, CTLSchemaExportMethod.valueOf(method.toUpperCase())); ServletUtils.prepareDisposition(request, response, output.getFileName()); response.setContentType(output.getContentType()); response.setContentLength(output.getFileData().length); response.setBufferSize(BUFFER); response.getOutputStream().write(output.getFileData()); response.flushBuffer(); } catch (Exception cause) { throw Utils.handleException(cause); } } /** * Get existing flat schema. * * @param id * of the CTL schema * @return the flat schema string * @throws KaaAdminServiceException * the kaa admin service exception */ @ApiOperation(value = "Get flat schema by it's id", notes = "Returns a flat schema. Only authorized users are allowed to perform this operation.") @RequestMapping(value = "CTL/getFlatSchemaByCtlSchemaId", params = { "id" }, method = RequestMethod.GET) @ApiResponses(value = { @ApiResponse(code = 401, message = "The user is not authenticated or invalid credentials were provided"), @ApiResponse(code = 403, message = "The tenant ID of the CTL schema does not match the tenant ID of the authenticated user"), @ApiResponse(code = 404, message = "A CTL schema with the specified id does not exist."), @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @ResponseBody public String getFlatSchemaByCtlSchemaId( @ApiParam(name = "id", value = "A unique CTL schema identifier", required = true) @RequestParam String id) throws KaaAdminServiceException { return ctlService.getFlatSchemaByCtlSchemaId(id); } }
# frozen_string_literal: true git File.join(Chef::Config['file_cache_path'], 'unco') do repository node['unco']['repo'] reference node['unco']['ref'] action :sync end execute 'install unco' do cwd File.join(Chef::Config['file_cache_path'], 'unco') command <<-COMMAND cmake -DCMAKE_INSTALL_PREFIX=#{node['unco']['install_target']} make preinstall cmake -DCMAKE_INSTALL_PREFIX=#{node['unco']['install_target']} -P cmake_install.cmake make clean COMMAND not_if "#{node['unco']['install_target']}/bin/unco --version | grep #{node['unco']['version']}" end
<reponame>alterem/smartCityService package com.zhcs.utils.mail; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.zhcs.utils.LogUtil; import com.zhcs.utils.strRandom.RandomStr; //***************************************************************************** /** * <p>Title:SimpleMailSender</p> * <p>Description:邮件发送器</p> * <p>Copyright: Copyright (c) 2017</p> * <p>Company: 深圳市智慧城市管家信息科技有限公司</p> * @author 刘晓东 - Alter * @version v1.0 2017年2月23日 */ //***************************************************************************** public class SimpleMailSender { //************************************************************************* /** * 【发送】文本格式邮件 * @param mailInfo 邮件信息对象 * @return boolean true:成功,false:失败 * @throws Exception 异常对象 */ //************************************************************************* public boolean sendTextMail(MailSenderInfo mailInfo) { try { //判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); if (mailInfo.isValidate()) { //如果需要身份认证,则创建一个密码验证器 authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } //根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro,authenticator); //根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); //创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); //设置邮件消息的发送者 mailMessage.setFrom(from); //创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); mailMessage.setRecipient(Message.RecipientType.TO,to); //设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); //设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); //设置邮件消息的主要内容 String mailContent = mailInfo.getContent(); mailMessage.setText(mailContent); //发送邮件 Transport.send(mailMessage); LogUtil.info("发送成功!"); } catch (AddressException e) { return false; } catch (MessagingException e) { return false; } return true; } //************************************************************************* /** * 【发送】HTML格式邮件 * @param mailInfo 邮件信息对象 * @return boolean true:成功,false:失败 * @throws MessagingException 消息异常 */ //************************************************************************* public boolean sendHtmlMail(MailSenderInfo mailInfo) throws MessagingException{ //判断是否需要身份认证 MyAuthenticator authenticator = null; Properties pro = mailInfo.getProperties(); //如果需要身份认证,则创建一个密码验证器 if (mailInfo.isValidate()) { authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword()); } //根据邮件会话属性和密码验证器构造一个发送邮件的session Session sendMailSession = Session.getDefaultInstance(pro,authenticator); //根据session创建一个邮件消息 Message mailMessage = new MimeMessage(sendMailSession); //创建邮件发送者地址 Address from = new InternetAddress(mailInfo.getFromAddress()); //设置邮件消息的发送者 mailMessage.setFrom(from); //创建邮件的接收者地址,并设置到邮件消息中 Address to = new InternetAddress(mailInfo.getToAddress()); //Message.RecipientType.TO属性表示接收者的类型为TO mailMessage.setRecipient(Message.RecipientType.TO,to); //设置邮件消息的主题 mailMessage.setSubject(mailInfo.getSubject()); //设置邮件消息发送的时间 mailMessage.setSentDate(new Date()); //MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象 Multipart mainPart = new MimeMultipart(); //创建一个包含HTML内容的MimeBodyPart BodyPart html = new MimeBodyPart(); //设置HTML内容 html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); mainPart.addBodyPart(html); //将MiniMultipart对象设置为邮件内容 mailMessage.setContent(mainPart); //发送邮件 Transport.send(mailMessage); LogUtil.info("mail Send success..."); return true; } //************************************************************************* /** * 【发送】邮件 * @param smtp 邮件服务器 * @param port 端口 * @param email 本邮箱账号 * @param password <PASSWORD>密码 * @param tomail 对方箱账号 * @param title 标题 * @param content 内容 * @param type 类型:1:文本格式;2:HTML格式 * @throws Exception 异常对象 */ //************************************************************************* public static void sendEmail(String smtp, String port, String email, String password, String tomail, String title, String content, String type) throws Exception { //这个类主要是设置邮件 MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost(smtp); mailInfo.setMailServerPort(port); mailInfo.setValidate(true); mailInfo.setUserName(email); mailInfo.setPassword(password); mailInfo.setFromAddress(email); mailInfo.setToAddress(tomail); mailInfo.setSubject(title); mailInfo.setContent(content); //这个类主要来发送邮件 SimpleMailSender sms = new SimpleMailSender(); if ("1".equals(type)) { sms.sendTextMail(mailInfo); } else { sms.sendHtmlMail(mailInfo); } } //************************************************************************* /** * 【接口】邮件发送主接口。 * @param Addressee 发送给谁 * @param title 邮件标题 * @param content 内容 * @return * @throws Exception */ //************************************************************************* public static boolean sendEmail(String Addressee, String title, String content, Boolean textMail) throws MessagingException { MailSenderInfo mailInfo = new MailSenderInfo(); mailInfo.setMailServerHost("smtp.163.com"); mailInfo.setMailServerPort("25"); mailInfo.setValidate(true); mailInfo.setUserName("13027991217"); mailInfo.setPassword("<PASSWORD>");//您的邮箱密码 mailInfo.setFromAddress("<EMAIL>"); mailInfo.setToAddress(Addressee); mailInfo.setSubject(title); mailInfo.setContent(content); LogUtil.info("content:{}", content); //这个类主要来发送邮件 SimpleMailSender sms = new SimpleMailSender(); if(textMail){ sms.sendTextMail(mailInfo);//发送文体格式 } else { sms.sendHtmlMail(mailInfo);//发送html格式 } return true; } public static void main(String[] args) throws MessagingException { SimpleMailSender.sendEmail("<EMAIL>", "测试邮件!", "<span style='color:red'>您的验证码是:" + RandomStr.randomStr(6) + "</span>" , false); } }
def get_view_function(url_pattern: str) -> str: urlpatterns = [ ('auth/$', 'gchatautorespond.apps.autorespond.views.auth_view'), ('oauth2callback/$', 'gchatautorespond.apps.autorespond.views.auth_return_view'), ('worker_status/$', 'gchatautorespond.apps.autorespond.views.worker_status_view'), ('test/$', 'gchatautorespond.apps.autorespond.views.test_view'), ('$', 'gchatautorespond.apps.autorespond.views.autorespond_view', 'autorespond'), ] for pattern, view_function in urlpatterns: if url_pattern == pattern: return view_function return '404 Not Found'
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "Kernel#trace_var" do before :each do $Kernel_trace_var_global = nil end after :each do untrace_var :$Kernel_trace_var_global $Kernel_trace_var_global = nil $Kernel_trace_var_extra = nil end it "is a private method" do Kernel.should have_private_instance_method(:trace_var) end it "hooks assignments to a global variable" do captured = nil trace_var :$Kernel_trace_var_global do |value| captured = value end $Kernel_trace_var_global = 'foo' captured.should == 'foo' end it "accepts a proc argument instead of a block" do captured = nil trace_var :$Kernel_trace_var_global, proc {|value| captured = value} $Kernel_trace_var_global = 'foo' captured.should == 'foo' end # String arguments should be evaluated in the context of the caller. it "accepts a String argument instead of a Proc or block" do trace_var :$Kernel_trace_var_global, '$Kernel_trace_var_extra = true' $Kernel_trace_var_global = 'foo' $Kernel_trace_var_extra.should == true end it "raises ArgumentError if no block or proc is provided" do lambda do trace_var :$Kernel_trace_var_global end.should raise_error(ArgumentError) end end
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="8a_scraper", version="0.0.2", author="<NAME>", author_email="<EMAIL>", license="MIT", description="A Python client for scraping data from 8a.nu", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/vishaalagartha/8a_scraper", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires=">=3.6", install_requires=[ 'beautifulsoup4==4.9.1', 'bs4==0.0.1', 'certifi==2020.6.20', 'chardet==3.0.4', 'idna==2.10', 'requests==2.24.0', 'selenium==3.141.0', 'soupsieve==2.0.1', 'urllib3==1.25.9' ], extras_require={ 'test': ['unittest'], }, keywords=[ "climbing", "rockclimbing", "bouldering", "sportclimbing", "8a", "8a.nu", "data mining", ] )
public class CustomDataStructure { private Set<Integer> set; public CustomDataStructure() { set = new HashSet<>(); } public void add(int x) { set.add(x); } public void remove(int x) { set.remove(x); } public boolean contains(int x) { return set.contains(x); } }
<gh_stars>0 package io.sumac.devtools.propertyresolver.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target({ FIELD, METHOD, PARAMETER }) public @interface Property { String name(); boolean optional() default false; }
function generateWeightedList(list) { // Create a result array const result = []; // Store total weights sum let sum = 0; // Iterate over the given list for (let i = 0; i < list.length; i++) { // Generate a random number const randomNum = Math.random(); // Calculate the partial sum sum += randomNum; // Add the element to result array result.push(list[i]); // Calculate the partial sum sum -= randomNum; } // Sort the result array with the partial sum result.sort(function(a, b) { return sum[a] - sum[b]; }); // Return the sorted result array return result; } const list = ['Apple','Orange','Grape']; const weightedList = generateWeightedList(list); // weightedList: [Grape, Apple, Orange]
/** * Copyright 2016 <NAME> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.pathirage.freshet.samza; import org.apache.samza.checkpoint.CheckpointManagerFactory; import org.apache.samza.checkpoint.kafka.KafkaCheckpointManagerFactory; import org.apache.samza.config.MapConfig; import org.apache.samza.job.StreamJobFactory; import org.apache.samza.serializers.Serde; import org.apache.samza.serializers.SerdeFactory; import org.apache.samza.storage.kv.BaseKeyValueStorageEngineFactory; import org.apache.samza.system.SystemFactory; import org.apache.samza.task.StreamTask; import java.util.HashMap; import static java.lang.String.format; import static org.pathirage.freshet.common.Validations.*; public class SamzaJobConfigBuilder extends HashMap<String, String> { private static final String SERIALIZER_PREFIX = "serializers.registry.%s"; private static final String SERIALIZER_SERDE_CLASS = SERIALIZER_PREFIX + ".class"; private static final String SYSTEM_PREFIX = "systems.%s."; private static final String SYSTEM_FACTORY = SYSTEM_PREFIX + "samza.factory"; private static final String SYSTEM_KEY_SERDE = SYSTEM_PREFIX + "samza.key.serde"; private static final String SYSTEM_MSG_SERDE = SYSTEM_PREFIX + "samza.msg.serde"; private static final String SYSTEM_PROPERTY = SYSTEM_PREFIX + "%s"; private static final String SYSTEM_CONSUMER_OFFSET_DEFAULT = SYSTEM_PREFIX + "samza.offset.default"; private static final String STREAM_PREFIX = "systems.%s.streams.%s."; private static final String STREAM_MSG_SERDE = STREAM_PREFIX + "samza.msg.serde"; private static final String STREAM_KEY_SERDE = STREAM_PREFIX + "samza.key.serde"; private static final String STREAM_BOOTSTRAP = STREAM_PREFIX + "samza.bootstrap"; private static final String STREAM_CONSUMER_RESET_OFFSET = STREAM_PREFIX + "samza.reset.offset"; private static final String STREAM_CONSUMER_OFFSET_DEFAULT = STREAM_PREFIX + "samza.offset.default"; private static final String TASK_CLASS = "task.class"; private static final String INPUT_STREAMS = "task.inputs"; private static final String INPUT_STREAMS_VALUE_TEMPLATE = "%s,%s.%s"; private static final String CHECKPOINT_MANAGER_FACTORY = "task.checkpoint.factory"; private static final String CHECKPOINT_SYSTEM = "task.checkpoint.system"; private final static String LOCAL_STORAGE_PREFIX = "stores.%s."; private final static String LOCAL_STORAGE_FACTORY = LOCAL_STORAGE_PREFIX + "factory"; private final static String LOCAL_STORAGE_KEY_SERDE = LOCAL_STORAGE_PREFIX + "key.serde"; private final static String LOCAL_STORAGE_MSG_SERDE = LOCAL_STORAGE_PREFIX + "msg.serde"; private final static String LOCAL_STORAGE_CHANGELOG_STREAM = LOCAL_STORAGE_PREFIX + "changelog"; private static final String YARN_PACKAGE_PATH = "yarn.package.path"; private static final String YARN_CONTAINER_MAX_MEMORY_MB = "yarn.container.memory.mb"; private static final String YARN_CONTAINER_MAX_CPU_CORES = "yarn.container.cpu.cores"; private static final String YARN_CONTAINER_COUNT = "yarn.container.count"; private static final String JOB_COORDINATOR_SYSTEM = "job.coordinator.system"; private static final String JOB_COORDINATOR_STREAM_REPLICATION_FACTOR = "job.coordinator.replication.factor"; private static final String JOB_NAME = "job.name"; private static final String JOB_FACTORY_CLASS = "job.factory.class"; public void reset() { clear(); } public MapConfig build() { return new MapConfig(this); } public SamzaJobConfigBuilder jobName(String jobName) { isNullOrEmpty(jobName, "Job name"); put(JOB_NAME, jobName); return this; } public SamzaJobConfigBuilder jobFactory(Class<? extends StreamJobFactory> factoryClass) { isNull(factoryClass, "Job factory class"); put(JOB_FACTORY_CLASS, factoryClass.getName()); return this; } public SamzaJobConfigBuilder addSerde(String name, Class<? extends SerdeFactory> serdeClass) { isNullOrEmpty(name, "Serde name"); isNull(serdeClass, "Serde class"); put(format(SERIALIZER_SERDE_CLASS, name), serdeClass.getName()); return this; } public SamzaJobConfigBuilder addSystem(String name, Class<? extends SystemFactory> factory, String keySerde, String messageSerde, MapConfig additionalConfigurations) { isNullOrEmpty(name, "System name"); isNull(factory, "System factory class"); put(format(SYSTEM_FACTORY, name), factory.getName()); if (!isNullOrEmpty(keySerde)) { isSerdeExists(keySerde); put(format(SYSTEM_KEY_SERDE, name), keySerde); } if (!isNullOrEmpty(messageSerde)) { isSerdeExists(messageSerde); put(format(SYSTEM_MSG_SERDE, name), messageSerde); } if (additionalConfigurations != null) { for (Entry<String, String> c : additionalConfigurations.entrySet()) { put(format(SYSTEM_PROPERTY, name, c.getKey()), c.getValue()); } } return this; } public SamzaJobConfigBuilder addStream(String system, String name, String keySerde, String messageSerde, Boolean isBootstrap) { isNullOrEmpty(system, "System name"); isNullOrEmpty(name, "Stream name"); // TODO: fix semantics of isNullOrEmpty. Two methods behave differently. if (!isNullOrEmpty(keySerde)) { isSerdeExists(keySerde); put(format(STREAM_KEY_SERDE, system, name), keySerde); } if (!isNullOrEmpty(messageSerde)) { isSerdeExists(messageSerde); put(format(STREAM_MSG_SERDE, system, name), messageSerde); } if (isBootstrap != null && isBootstrap) { put(format(STREAM_BOOTSTRAP, system, name), isBootstrap.toString()); } return this; } public SamzaJobConfigBuilder task(Class<? extends StreamTask> taskClass) { isNull(taskClass, "Task class"); put(TASK_CLASS, taskClass.getName()); return this; } public SamzaJobConfigBuilder addInput(String system, String stream) { isNullOrEmpty(system, "System name"); isNullOrEmpty(stream, "Stream name"); if (!containsKey(format(SYSTEM_FACTORY, system))) { throw new IllegalArgumentException("Cannot find system " + system + "."); } if (containsKey(INPUT_STREAMS)) { put(INPUT_STREAMS, format(INPUT_STREAMS_VALUE_TEMPLATE, get(INPUT_STREAMS), system, stream)); } else { put(INPUT_STREAMS, format("%s.%s", system, stream)); } return this; } public SamzaJobConfigBuilder addBroadcastInput(String broadcastInput) { throw new UnsupportedOperationException("Not implemented yet."); } public SamzaJobConfigBuilder checkpointingConfig(Class<? extends CheckpointManagerFactory> checkpointFactoryClass, String system) { if (checkpointFactoryClass != null) { put(CHECKPOINT_MANAGER_FACTORY, checkpointFactoryClass.getName()); } if (checkpointFactoryClass.getName().equals(KafkaCheckpointManagerFactory.class.getName())) { put(CHECKPOINT_SYSTEM, system); } return this; } public SamzaJobConfigBuilder addLocalStorage(String name, Class<? extends BaseKeyValueStorageEngineFactory> storageEngineFactory, String keySerde, String messageSerde, String changelogSystem, String changelogStream) { isNullOrEmpty(name, "Local storage name"); isNull(storageEngineFactory, "Storage engine factory"); isNullOrEmpty(keySerde, "Key Serde"); isNullOrEmpty(messageSerde, "Message Serde"); isNullOrEmpty(changelogSystem, "Changelog system"); isNullOrEmpty(changelogStream, "Changelog stream"); isSerdeExists(keySerde); isSerdeExists(messageSerde); if (!containsKey(format(SYSTEM_FACTORY, changelogSystem))) { throw new IllegalArgumentException("Cannot find system " + changelogSystem); } put(format(LOCAL_STORAGE_FACTORY, name), storageEngineFactory.getName()); put(format(LOCAL_STORAGE_KEY_SERDE, name), keySerde); put(format(LOCAL_STORAGE_MSG_SERDE, name), messageSerde); put(format(LOCAL_STORAGE_CHANGELOG_STREAM, name), format("%s.%s", changelogSystem, changelogStream)); return this; } public SamzaJobConfigBuilder yarnPackagePath(String packagePath) { isNullOrEmpty(packagePath, "YARN package path"); put(YARN_PACKAGE_PATH, packagePath); return this; } public SamzaJobConfigBuilder yarnContainerCount(int containerCount) { if (containerCount <= 0) { throw new IllegalArgumentException("Container count is less than or equal to 0."); } put(YARN_CONTAINER_COUNT, Integer.toString(containerCount)); return this; } public SamzaJobConfigBuilder jobCoordinatorSystem(String system, Integer replicationFactor) { isSystemExists(system); put(JOB_COORDINATOR_SYSTEM, system); if (replicationFactor != null) { put(JOB_COORDINATOR_STREAM_REPLICATION_FACTOR, Integer.toString(replicationFactor)); } return this; } public SamzaJobConfigBuilder addCustomConfig(String name, String value) { isNullOrEmpty(name, "Custom configuration name"); isNullOrEmpty(value, "Custom configuration value"); put(name, value); return this; } private void isSerdeExists(String serde) { if (!containsKey(format(SERIALIZER_SERDE_CLASS, serde))) { throw new IllegalArgumentException("Cannot find Serde " + serde + "."); } } private void isSystemExists(String system) { if (!containsKey(format(SYSTEM_FACTORY, system))) { throw new IllegalArgumentException(); } } }
import org.springframework.context.annotation.Configuration import org.springframework.boot.web.servlet.ServletRegistrationBean import org.springframework.context.annotation.Bean import org.h2.server.web.WebServlet @Configuration class H2Config { @Bean def h2servletRegistration(): ServletRegistrationBean = { val registrationBean = new ServletRegistrationBean(new WebServlet) registrationBean.addUrlMappings("/console/*") return registrationBean } }
const React = require('react'); const { Button, Modal, Divider, Dialog, Drawer, Space, Dropdown, Menu, Layout, Icon, Link, } = require('antd'); require('antd/dist/antd.css'); const { Header, Footer, Sider, Content } = Layout; class Home extends React.Component { constructor(props) { super(props); } toggleState(e, state) { try { e.preventDefault() } catch (e) {} this.setState({ [state]: ! this.state[state] }); } render() { return ( <Space direction="vertical"> <h2>Home Page</h2> </Space> ) } } module.exports = Home;
<filename>testdata/flow/flow.c #include <stdio.h> int main() { int a = sizeof(1); int *b = &a; switch (a) { case 4: printf("sizeof(int) == 4\n"); break; case 8: printf("sizeof(int) == 8\n"); break; case 0: case 1: default: printf("sizeof(int) == unknown\n"); } while (a) { a--; if (a == 5) { printf("a = 5, continue\n"); continue; } if (a == 3) { break; } } printf("a = %d\n", a); if (b) { printf("&a\n"); } return 0; }
package com.wxh.sdk.http; import com.google.gson.Gson; import com.orhanobut.logger.Logger; import com.wxh.sdk.des3.AESUtils; import com.wxh.sdk.httputils.HttpResponse; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.builder.GetBuilder; import com.zhy.http.okhttp.builder.PostFormBuilder; import com.zhy.http.okhttp.builder.PostStringBuilder; import java.util.Map; import okhttp3.MediaType; /** * 网络请求 2016/8/14. */ public class HttpRequest { /** * Get请求 * @param url * @param params * @param listener * @param <T> */ public static <T> void doGet(String url, Map<String, Object> params, HttpResponse<T> listener) { GetBuilder builder = OkHttpUtils.get(); builder.url(url); if (params!=null){ for (String key : params.keySet()) { builder.addParams(key, String.valueOf(params.get(key))); } } builder.build().execute(listener); } /** * Get请求 * @param url * @param listener * @param <T> */ public static <T> void doGet(String url,HttpResponse<T> listener) { doGet(url,null,listener); } /** * Post请求 * @param url * @param params * @param listener * @param <T> */ public static <T> void doPost(String url, Map<String, Object> params, HttpResponse<T> listener) { PostFormBuilder builder = OkHttpUtils.post(); builder.url(url); if (params!=null){ for (String key : params.keySet()) { builder.addParams(key, String.valueOf(params.get(key))); } } builder.build().execute(listener); } /** * Post请求 * @param url * @param listener * @param <T> */ public static <T> void doPost(String url,HttpResponse<T> listener) { doPost(url,null,listener); } /** * POSTJOSN数据 * @param url * @params * @param listener * @param <T> */ public static <T> void doPostJson(String url,Map<String,Object> params, HttpResponse<T> listener) { PostStringBuilder builder = OkHttpUtils.postString(); builder.url(url); String str=url; builder.addHeader("Content-Type", "application/json"); builder.mediaType(MediaType.parse("application/json; charset=utf-8")); if(params!=null){ String json=new Gson().toJson(params); builder.content(AESUtils.Encrypt(json)); str=str+"?"+json; } Logger.i(str); builder.build().execute(listener); } /** * POSTJOSN数据 * @param url * @param listener * @param <T> */ public static <T> void doPostJson(String url,HttpResponse<T> listener) { doPostJson(url,null,listener); } }
chmod +x mvnw ./mvnw clean package -Pnative -Dquarkus.native.container-build=true -Dquarkus.native.container-runtime=docker docker rmi quay.io/qiotcovid19/edge-sensors-emulator:2.0.0-alpha-x86_64 --force docker build -f src/main/docker/Dockerfile.native -t quay.io/qiotcovid19/edge-sensors-emulator:2.0.0-alpha-x86_64 . docker push quay.io/qiotcovid19/edge-sensors-emulator:2.0.0-alpha-x86_64 #docker run -it --rm -p 8080:8080 --net host quay.io/qiot/qiot-integrator
<reponame>yinfuquan/spring-boot-examples package com.yin.springboot.mybatis.server; import com.yin.springboot.mybatis.domain.UmsMemberReceiveAddress; import java.util.List; public interface UmsMemberReceiveAddressService{ int deleteByPrimaryKey(Long id); int insert(UmsMemberReceiveAddress record); int insertOrUpdate(UmsMemberReceiveAddress record); int insertOrUpdateSelective(UmsMemberReceiveAddress record); int insertSelective(UmsMemberReceiveAddress record); UmsMemberReceiveAddress selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(UmsMemberReceiveAddress record); int updateByPrimaryKey(UmsMemberReceiveAddress record); int updateBatch(List<UmsMemberReceiveAddress> list); int batchInsert(List<UmsMemberReceiveAddress> list); }
#/bin/bash sudo apt update -y sudo apt upgrade -y sudo apt-get clean -y sudo apt-get autoremove -y #SAMBA sudo apt-get install -y samba samba-common-bin # требует одно подтверждение при установке (Yes/No), по-умолчанию выбрано то что нужно (No) sudo cp /etc/samba/smb.conf /etc/samba/smb.confbackup sudo rm /etc/samba/smb.conf sudo cp /home/pi/smsetup/files/smb.conf /etc/samba sudo smbpasswd -a pi sudo systemctl restart smbd #NodeJS curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - sudo apt-get install -y nodejs #Docker sudo curl -sSL https://get.docker.com | sh sudo usermod -aG docker pi #Eclipse-mosquitto server sudo docker pull eclipse-mosquitto sudo docker run -it -p 1883:1883 --restart=always eclipse-mosquitto #MagicMirror sudo rm -rf home/pi/MagicMirror git clone --depth=1 https://github.com/MichMich/MagicMirror.git /home/pi/MagicMirror cp -f /home/pi/smsetup/files/config.js /home/pi/MagicMirror/config/config.js cd /home/pi/MagicMirror/modules git clone --depth=1 https://github.com/Jopyth/MMM-Remote-Control.git git clone --depth=1 https://github.com/ronny3050/email-mirror.git email git clone --depth=1 https://github.com/sergge1/MMM-PIR-Sensor.git git clone --depth=1 https://github.com/javiergayala/MMM-mqtt.git git clone --depth=1 https://github.com/cybex-dev/MMM-MQTT-Publisher.git git clone --depth=1 https://github.com/AgP42/MMM-SmartWebDisplay.git git clone --depth=1 https://github.com/mboskamp/MMM-PIR.git npm -y install --prefix /home/pi/MagicMirror && npm -y install --prefix /home/pi/MagicMirror/modules/MMM-Remote-Control && npm -y install --prefix /home/pi/MagicMirror/modules/email && npm -y install --prefix /home/pi/MagicMirror/modules/MMM-mqtt && npm -y install --prefix /home/pi/MagicMirror/modules/MMM-MQTT-Publisher && cd /home/pi/MagicMirror/modules/MMM-PIR npm -y install --prefix /home/pi/MagicMirror/modules/MMM-PIR && npm -y install --prefix /home/pi/MagicMirror/modules/MMM-PIR electron-rebuild && /home/pi/MagicMirror/modules/MMM-PIR/node_modules/.bin/electron-rebuild
""" xy and xyz classes part of hwpy: an OO hardware interface library home: https://www.github.com/wovo/hwpy """ from hwpy_modules.wait import * import copy # =========================================================================== # # xy class # # =========================================================================== class xy: """Transparent container for an (x,y) value pair. """ def __init__(self, x, y): """Create an xy object from x and y values. """ self.x = copy.copy(x) self.y = copy.copy(y) def __eq__(self, other: 'xy'): """Compare for equality """ return (self.x == other.y) and (self.y == other.y) def __ne__(self, other: 'xy'): """Compare for inequality """ return (self.x != other.y) or (self.y != other.y) def __abs__(self): """Return the absolute. """ return xy(abs(self.x), abs(self.y)) def __add__(self, other: 'xy'): """Add two xy """ return xy(self.x + other.x, self.y + other.y) def __sub__(self, other: 'xy'): """Subtract two xy """ return xy(self.x - other.x, self.y - other.y) def __mul__(self, other): """Multiply an xy by a scalar """ return xy(self.x * other, self.y * other) def __rmul__(self, other): """Multiply an xy by a scalar """ return xy(self.x * other, self.y * other) def __truediv__(self, other): """Divide an xy by a scalar """ return xy(self.x / other, self.y / other) def __str__(self, f = "[%d,%d]"): """Return the string representation """ return f % ( self.x, self.y ) # =========================================================================== # # xyz class # # =========================================================================== class xyz: """Transparent container for an (x,y,z) value set. """ def __init__(self, x, y, z): """Create an xyz object from x, y and z values. """ self.x = copy.copy(x) self.y = copy.copy(y) self.z = copy.copy(z) def __eq__(self, other: 'xyz'): """Compare for equality """ return ( (self.x == other.y) and (self.y == other.y) and (self.z == other.z)) def __ne__(self, other: 'xyz'): """Compare for inequality """ return ( (self.x != other.y) or (self.y != other.y) or (self.z != other.z)) def __abs__(self): """Return the absolute. """ return xyz(abs(self.x), abs(self.y), abs(self.z)) def __add__(self, other: 'xyz'): """Add two xyz """ return xyz(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other: 'xyz'): """Subtract two xyz """ return xyz(self.x - other.x, self.y - other.y, self.z - other.z) def __mul__(self, other): """Multiply an xyz by a scalar """ return xyz(self.x * other, self.y * other, self.z * other) def __rmul__(self, other): """Multiply an xyz by a scalar """ return xyz(self.x * other, self.y * other, self.z * other) def __truediv__(self, other): """Divide an xyz by a scalar """ return xyz(self.x / other, self.y / other, self.z * other) def __str__(self, f = "[%d,%d,%d]"): """Return the string representation """ return f % ( self.x, self.y, self.z )
package org.example; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; public class Application extends AbstractHandler { private static final int PAGE_SIZE = 3000; private static final String INDEX_HTML = loadIndex(); private static String loadIndex() { try (BufferedReader reader = new BufferedReader(new InputStreamReader(Application.class.getResourceAsStream("/index.html")))) { final StringBuilder page = new StringBuilder(PAGE_SIZE); String line = null; while ((line = reader.readLine()) != null) { page.append(line); } return page.toString(); } catch (final Exception exception) { return getStackTrace(exception); } } private static String getStackTrace(final Throwable throwable) { final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter, true); throwable.printStackTrace(printWriter); return stringWriter.getBuffer().toString(); } private static int getPort() { return Integer.parseInt(System.getenv().get("PORT")); } private void handleHttpRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { // Handle HTTP requests here. response.getWriter().println(INDEX_HTML); } private void handleCronTask(HttpServletRequest request, HttpServletResponse response) throws IOException { // Handle WorkerTier tasks here. response.getWriter().println("Process Task Here."); } public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); String pathInfo = request.getPathInfo(); if (pathInfo.equalsIgnoreCase("/crontask")) { handleCronTask(request, response); } else { handleHttpRequest(request, response); } } public static void main(String[] args) throws Exception { Server server = new Server(getPort()); server.setHandler(new Application()); server.start(); server.join(); } }
require 'timeout' class MockSocket TIMEOUT = 1 def self.pipe socket1, socket2 = new, new socket1.in, socket2.out = IO.pipe socket2.in, socket1.out = IO.pipe [socket1, socket2] end attr_accessor :in, :out def puts(m) @out.puts(m) end def print(m) @out.print(m) end def gets timeout {@in.gets} end def read(length=nil) timeout {@in.read(length)} end def eof? timeout {@in.eof?} end def empty? begin @in.read_nonblock(1) false rescue Errno::EAGAIN true end end private def timeout(&block) Timeout.timeout(TIMEOUT) {block.call} end end
#!/bin/bash set -eo pipefail SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd) PROJECT_DIR=$1 shift "$@" ./src/play/play \ OREMOA_ \ "${SCRIPT_DIR}/tiles.txt" \ "${PROJECT_DIR}/boards/wwf_challenge.txt"
package edu.uwp.appfactory.racinezoo.EventScreen; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.CalendarContract; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TreeMap; import edu.uwp.appfactory.racinezoo.Model.Event; import edu.uwp.appfactory.racinezoo.Model.EventItem; import edu.uwp.appfactory.racinezoo.Model.HeaderItem; import edu.uwp.appfactory.racinezoo.Model.ListItem; import edu.uwp.appfactory.racinezoo.Model.RealmString; import edu.uwp.appfactory.racinezoo.R; import edu.uwp.appfactory.racinezoo.Util.DateUtils; import edu.uwp.appfactory.racinezoo.Util.GsonUtil; import io.realm.Case; import io.realm.Realm; import io.realm.RealmList; import io.realm.RealmResults; import static android.content.Context.ALARM_SERVICE; public class EventFragment extends Fragment { private static final int REQUEST_CODE = 5; private Realm mRealm; private static final String TAG = "EventsFragment"; private RecyclerView recyclerView; @NonNull private List<ListItem> items = new ArrayList<>(); @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); mRealm = Realm.getDefaultInstance(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View eventView = inflater.inflate(R.layout.fragment_event, container, false); Date endOfYear = new Date(); Calendar c = new GregorianCalendar(); c.setTime(endOfYear); c.set(DateUtils.getCurrentYear(), 11, 31); //Previously only events that had not happened yet would show, but this is just to show all events so you can see the design of the layout Date showAllEvents = new Date(); showAllEvents.setTime(1420099178); RealmResults<Event> result = mRealm.where(Event.class).between("startDate", showAllEvents, c.getTime()).findAll(); buildEventSet(toMapWeek(result)); recyclerView = (RecyclerView) eventView.findViewById(R.id.event_lst_items); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(new EventsAdapter(items, getActivity())); return eventView; } @NonNull private List<Event> loadEvents() { List<Event> events = new ArrayList<>(); for (int i = 1; i < 50; i++) { events.add(new Event("event " + i, buildRandomDateInCurrentMonth())); } return events; } private Date buildRandomDateInCurrentMonth() { Random random = new Random(); return DateUtils.buildDate(random.nextInt(31) + 1); } private Map<Integer, List<Event>> toMapWeek(@NonNull List<Event> events) { Map<Integer, List<Event>> mapMonth = new TreeMap<>(); Calendar c = Calendar.getInstance(); String[] months = new DateFormatSymbols().getMonths(); for (int i = 0; i < months.length; i++) { mapMonth.put(i, new ArrayList<Event>()); } for (Event event : events) { int currentMonth = DateUtils.getMonthNumberFromDate(event.getStartDate()); mapMonth.get(currentMonth).add(event); } for (int i = 0; i < 12; i++) { if (mapMonth.get(i).size() == 0) { mapMonth.remove(i); } else { Collections.sort(mapMonth.get(i), new Comparator<Event>() { @Override public int compare(Event o1, Event o2) { return o1.getStartDate().compareTo(o2.getStartDate()); } }); } } return mapMonth; } private void buildEventSet(Map<Integer, List<Event>> events) { String[] months = new DateFormatSymbols().getMonths(); for (Integer num : events.keySet()) { items.add(new HeaderItem(months[num], "")); List<Event> eventsSubList = events.get(num); items.addAll(groupEvents(eventsSubList)); } } public List<EventItem> groupEvents(List<Event> events) { List<EventItem> tempItems = new ArrayList<>(); List<Event> tempEventList = new ArrayList<>(); int previousDay = -1; int currentDay; for (int i = 0; i < events.size(); i++) { currentDay = DateUtils.getDayOfMonthFromDate(events.get(i).getStartDate()); if (previousDay == -1 || previousDay == currentDay) { tempEventList.add(events.get(i)); previousDay = currentDay; } else { tempItems.add(new EventItem(tempEventList)); tempEventList = new ArrayList<>(); i -= 1; previousDay = -1; } } tempItems.add(new EventItem(tempEventList)); return tempItems; } public void populateRealmDB(List<Event> events) { for (Event event : events) { mRealm.beginTransaction(); mRealm.copyToRealm(event); mRealm.commitTransaction(); } } @Override public void onDestroy() { super.onDestroy(); if (mRealm != null) { mRealm.close(); } } /*@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); *//*inflater.inflate(R.menu.search_menu, menu); SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setQueryHint("Search events..."); searchView.setIconifiedByDefault(true); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { if (!s.equals("") || !s.matches("\\s+")) { Date endOfYear = new Date(); Calendar c = new GregorianCalendar(); c.setTime(endOfYear); c.set(DateUtils.getCurrentYear(), 11, 31); RealmResults<Event> result = mRealm.where(Event.class).between("startDate", new Date(), c.getTime()).contains("name", s, Case.INSENSITIVE).findAll(); items = new ArrayList<ListItem>(); buildEventSet(toMapWeek(result)); recyclerView.setAdapter(new EventsAdapter(items, getContext())); recyclerView.getAdapter().notifyDataSetChanged(); } return false; } });*//* }*/ public static void setEventNotification(Event e, Context context) { Intent intent = new Intent(context, EventAlarmReceiver.class); String notificationInfo = DateUtils.getDateForNotification(e.getStartDate(), e.getEndDate()); intent.putExtra("NOTIF_INFO", notificationInfo); intent.putExtra("EVENT_NAME", e.getName()); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, e.getStartDate().getTime() , pendingIntent); System.out.println("Time Total ----- "+(System.currentTimeMillis()+e.getStartDate().getTime())); SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss"); Log.d("EVENTNOTIF", "notif set for: " + df.format(e.getStartDate())); } }
<filename>source/NuGet/_shared/content/Scripts/_config.js _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g };
<filename>src/main/java/com/github/thomasj/springcache/ext/juc/LinkedHashMapEx.java package com.github.thomasj.springcache.ext.juc; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.DelayQueue; import java.util.concurrent.TimeUnit; import com.google.common.collect.Maps; import lombok.Setter; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import lombok.extern.slf4j.Slf4j; /** * @author <EMAIL> */ @Slf4j public class LinkedHashMapEx extends LinkedHashMap<String, Object> implements InitializingBean, DisposableBean { @Setter private Integer maxCapacity = 10000; private DelayQueue<LRUKey> delayQueue = new DelayQueue<>(); private Map<String, LRUKey> lruItems = Maps.newHashMapWithExpectedSize(1000); private ExpiryTask expiryTask; @Override public void afterPropertiesSet () throws Exception { this.expiryTask = new ExpiryTask(this, delayQueue); this.expiryTask.setName("cache-clean"); this.expiryTask.start(); } @Override protected boolean removeEldestEntry (Map.Entry eldest) { if (super.size() > maxCapacity) { // FIXME 溢出后,延时队列无法清理,必须等待延时达到后启动清理 log.warn("缓存溢出,移除掉 KEY: {}, 容量: {}", eldest.getKey(), maxCapacity); return true; } return false; } @Override public synchronized Object put (String key, Object value) { if (log.isDebugEnabled()) { log.debug("添加缓存, 键: {}, 值: {}", key, value); } return this.put(key, value, 7, TimeUnit.DAYS); } @Override public synchronized Object putIfAbsent (String key, Object value) { return super.putIfAbsent(key, value); } @Override public synchronized Object remove (Object key) { if (log.isDebugEnabled()) { log.debug("删除缓存, 键: {}", key); } LRUKey eLRUKey = lruItems.remove(key); if (eLRUKey != null) { eLRUKey.expiry(); } return super.remove(key); } public synchronized Object put (String key, Object value, long expiry, TimeUnit unit) { if (log.isDebugEnabled()) { log.debug("添加缓存, 键: {}, 值: {}, 过期时间: {} ms.", new Object[] {key, value, TimeUnit.MILLISECONDS.convert(expiry, unit)}); } Object result = super.put(key, value); LRUKey lruKey = new LRUKey(key, expiry, unit); delayQueue.offer(lruKey); LRUKey eLRUKey = lruItems.remove(key); if (eLRUKey != null) { eLRUKey.expiry(); } lruItems.put(key, lruKey); return result; } @Override public void destroy () throws Exception { this.expiryTask.interrupt(); delayQueue.clear(); lruItems.clear(); super.clear(); } }