text stringlengths 1 1.05M |
|---|
def detectCycle(head):
slow_p = head
fast_p = head
while (slow_p and fast_p and fast_p.next):
slow_p = slow_p.next
fast_p = fast_p.next.next
if slow_p == fast_p:
return True
return False |
package com.globalcollect.gateway.sdk.java.gc.product;
import com.globalcollect.gateway.sdk.java.gc.product.definitions.PaymentProduct;
import java.util.List;
/**
* class PaymentProducts
*/
public class PaymentProducts {
private List<PaymentProduct> paymentProducts = null;
public List<PaymentProduct> getPaymentProducts() {
return paymentProducts;
}
public void setPaymentProducts(List<PaymentProduct> value) {
this.paymentProducts = value;
}
}
|
<reponame>pmartynov/greymass.com
import React from 'react';
import { injectIntl } from 'gatsby-plugin-intl';
import { Table, Header, Label, Icon, Responsive } from "semantic-ui-react"
import { JsonRpc } from 'eosjs';
import SharedElementsChainLogo from '../../../shared/elements/chainLogo';
import apisTableStyles from './table.module.css';
const nodes = [
{
logo: 'eos',
url: 'https://eos.greymass.com',
name: 'EOS',
v1: true,
},
{
logo: 'fio',
url: 'https://fio.greymass.com',
name: 'FIO',
v1: true,
},
{
logo: 'instar',
url: 'https://instar.greymass.com',
name: 'Instar',
v1: true,
},
{
logo: 'lynx',
url: 'https://lynx.greymass.com',
name: 'Lynx',
v1: true,
},
{
logo: 'telos',
url: 'https://telos.greymass.com',
name: 'Telos',
v1: true,
},
{
logo: 'wax',
url: 'https://wax.greymass.com',
name: 'WAX',
v1: true,
},
{
logo: 'fio',
url: 'https://fiotestnet.greymass.com',
name: 'FIO (Testnet)',
v1: true,
},
{
logo: 'jungle',
url: 'https://jungle.greymass.com',
name: 'Jungle (Testnet)',
v1: true,
},
{
logo: 'wax',
url: 'https://waxtestnet.greymass.com',
name: 'WAX (Testnet)',
v1: true,
},
]
class Apis extends React.Component {
state = {
responses: [],
};
componentDidMount() {
if (typeof window === 'undefined') {
return;
}
this.tick();
setInterval(() => this.tick(), 3000);
}
tick = async () => this.setState({
responses: await Promise.all(nodes.map(async (node) => {
try {
const start = Date.now();
const eos = new JsonRpc(node.url);
const info = await eos.get_info()
return {
...node,
height: info.head_block_num,
ms: Date.now() - start,
time: info.head_block_time,
}
} catch (err) {
return {
...node,
err,
}
}
}))
})
render() {
const { intl } = this.props;
const { responses } = this.state;
// wait for first responses
if (!responses.length) return false
return (
<div className={apisTableStyles.container}>
<Table definition unstackable>
<Table.Header>
<Table.Row>
<Table.HeaderCell />
<Table.HeaderCell>
{intl.formatMessage({ id: 'shared_apis_table_header_name' })}
</Table.HeaderCell>
<Table.HeaderCell textAlign="center">
{intl.formatMessage({ id: 'shared_apis_table_header_features' })}
</Table.HeaderCell>
<Responsive as={Table.HeaderCell} minWidth={768} textAlign="center">
{intl.formatMessage({ id: 'shared_apis_table_header_height' })}
</Responsive>
<Responsive as={Table.HeaderCell} minWidth={768} textAlign="center">
{intl.formatMessage({ id: 'shared_apis_table_header_status' })}
</Responsive>
<Table.HeaderCell textAlign="center">
{intl.formatMessage({ id: 'shared_apis_table_header_response_time' })}
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{responses.map(response => (
<Table.Row key={response.name}>
<Table.Cell collapsing>
<SharedElementsChainLogo
chain={response.logo}
size="mini"
/>
</Table.Cell>
<Table.Cell>
<Header as='h4' image>
<Header.Content>
{response.name}
<Header.Subheader>{response.url}</Header.Subheader>
</Header.Content>
</Header>
</Table.Cell>
<Responsive as={Table.Cell} minWidth={768} textAlign="center">
<Label color="blue" content="History (V1)"/>
</Responsive>
<Responsive as={Table.Cell} minWidth={768} textAlign="center">
{response.height}
</Responsive>
<Table.Cell textAlign="center">
{!!response.ms ? (
<Icon name="check" size="large" color="green" />
) : (
<Icon name="close" size="large" color="red" />
)}
</Table.Cell>
<Table.Cell textAlign="center">
{response.ms ?
`${response.ms} ms` :
'----'
}
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
</div>
)
}
}
export default injectIntl(Apis);
|
<gh_stars>1-10
module SagePay
module Server
class TransactionCode
def self.random
new.random
end
def random
uuid.generate
end
protected
def uuid
@uuid ||= UUID.new
end
end
end
end |
#!/bin/bash
# download with curl like
# curl -s -o /var/tmp/cloud-boot.sh https://raw.githubusercontent.com/bluestar/cloud-init/master/cloud-boot.sh
# then execute
# /var/tmp/cloud-boot.sh
# alternative for the brave
# curl -s -L https://raw.githubusercontent.com/bluestar/cloud-init/master/cloud-boot.sh | bash
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit -1
fi
CLOUDROOT=/opt/cloud-init
mkdir -pv $CLOUDROOT
cd $CLOUDROOT
if [[ $? -ne 0 ]]; then
echo "Cannot access $CLOUDROOT"
exit -1
fi
github=https://raw.githubusercontent.com/bluestar/cloud-init/master
curl -s -o cloud-init.sh "$github/cloud-init.sh"
bash ./cloud-init.sh |
<gh_stars>0
// Generated from KQuery.g4 by ANTLR 4.9.2
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.*;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class KQueryLexer extends Lexer {
static { RuntimeMetaData.checkVersion("4.9.2", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
Boolean=1, SignedConstant=2, Constant=3, BinConstant=4, OctConstant=5,
HexConstant=6, FloatingPointType=7, IntegerType=8, WidthType=9, BinId=10,
OctId=11, WIDTH=12, HexId=13, TrueMatch=14, FalseMatch=15, Query=16, Array=17,
Symbolic=18, Colon=19, Arrow=20, Equal=21, COMMA=22, NOT=23, SHL=24, LSHR=25,
ASHR=26, CONCAT=27, EXTRACT=28, ZEXT=29, SEXT=30, READ=31, SELECT=32,
NEGETION=33, READLSB=34, READMSB=35, PLUS=36, MINUS=37, ATR=38, BITWISEAND=39,
BITWISEOR=40, BITWISEXOR=41, EQ=42, NEQ=43, ULT=44, ULE=45, UGT=46, UGE=47,
SLT=48, SLE=49, SGT=50, SGE=51, ADD=52, SUB=53, MUL=54, UDIV=55, UREM=56,
SDIV=57, SREM=58, Identifier=59, INT=60, FP=61, Whitespace=62, Newline=63,
BlockComment=64, LineComment=65, LeftParen=66, RightParen=67, LeftBracket=68,
RightBracket=69, LeftBrace=70, RightBrace=71;
public static String[] channelNames = {
"DEFAULT_TOKEN_CHANNEL", "HIDDEN"
};
public static String[] modeNames = {
"DEFAULT_MODE"
};
private static String[] makeRuleNames() {
return new String[] {
"Boolean", "SignedConstant", "Constant", "BinConstant", "OctConstant",
"HexConstant", "FloatingPointType", "IntegerType", "WidthType", "BinId",
"OctId", "WIDTH", "HexId", "TrueMatch", "FalseMatch", "Query", "Array",
"Symbolic", "Colon", "Arrow", "Equal", "COMMA", "NOT", "SHL", "LSHR",
"ASHR", "CONCAT", "EXTRACT", "ZEXT", "SEXT", "READ", "SELECT", "NEGETION",
"READLSB", "READMSB", "PLUS", "MINUS", "ATR", "BITWISEAND", "BITWISEOR",
"BITWISEXOR", "EQ", "NEQ", "ULT", "ULE", "UGT", "UGE", "SLT", "SLE",
"SGT", "SGE", "ADD", "SUB", "MUL", "UDIV", "UREM", "SDIV", "SREM", "DIGIT",
"BIN_DIGIT", "OCTAL_DIGIT", "HEX_DIGIT", "Identifier", "INT", "FP", "Whitespace",
"Newline", "BlockComment", "LineComment", "LeftParen", "RightParen",
"LeftBracket", "RightBracket", "LeftBrace", "RightBrace"
};
}
public static final String[] ruleNames = makeRuleNames();
private static String[] makeLiteralNames() {
return new String[] {
null, null, null, null, null, null, null, null, null, null, "'0b'", "'0o'",
"'w'", "'0x'", "'true'", "'false'", "'query'", "'array'", "'symbolic'",
"':'", "'->'", "'='", "','", "'Not'", "'Shl'", "'LShr'", "'AShr'", "'Concat'",
"'Extract'", "'ZExt'", "'SExt'", "'Read'", "'Select'", "'Neg'", "'ReadLSB'",
"'ReadMSB'", "'+'", "'-'", "'@'", "'And'", "'Or'", "'Xor'", "'Eq'", "'Ne'",
"'Ult'", "'Ule'", "'Ugt'", "'Uge'", "'Slt'", "'Sle'", "'Sgt'", "'Sge'",
"'Add'", "'Sub'", "'Mul'", "'UDiv'", "'URem'", "'SDiv'", "'SRem'", null,
"'i'", "'fp'", null, null, null, null, "'('", "')'", "'['", "']'", "'{'",
"'}'"
};
}
private static final String[] _LITERAL_NAMES = makeLiteralNames();
private static String[] makeSymbolicNames() {
return new String[] {
null, "Boolean", "SignedConstant", "Constant", "BinConstant", "OctConstant",
"HexConstant", "FloatingPointType", "IntegerType", "WidthType", "BinId",
"OctId", "WIDTH", "HexId", "TrueMatch", "FalseMatch", "Query", "Array",
"Symbolic", "Colon", "Arrow", "Equal", "COMMA", "NOT", "SHL", "LSHR",
"ASHR", "CONCAT", "EXTRACT", "ZEXT", "SEXT", "READ", "SELECT", "NEGETION",
"READLSB", "READMSB", "PLUS", "MINUS", "ATR", "BITWISEAND", "BITWISEOR",
"BITWISEXOR", "EQ", "NEQ", "ULT", "ULE", "UGT", "UGE", "SLT", "SLE",
"SGT", "SGE", "ADD", "SUB", "MUL", "UDIV", "UREM", "SDIV", "SREM", "Identifier",
"INT", "FP", "Whitespace", "Newline", "BlockComment", "LineComment",
"LeftParen", "RightParen", "LeftBracket", "RightBracket", "LeftBrace",
"RightBrace"
};
}
private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames();
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
public KQueryLexer(CharStream input) {
super(input);
_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
@Override
public String getGrammarFileName() { return "KQuery.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public String[] getChannelNames() { return channelNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
public static final String _serializedATN =
"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2I\u01f4\b\1\4\2\t"+
"\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+
"\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+
"\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31\t\31"+
"\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t \4!"+
"\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4"+
",\t,\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64\t"+
"\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:\4;\t;\4<\t<\4=\t="+
"\4>\t>\4?\t?\4@\t@\4A\tA\4B\tB\4C\tC\4D\tD\4E\tE\4F\tF\4G\tG\4H\tH\4I"+
"\tI\4J\tJ\4K\tK\4L\tL\3\2\3\2\5\2\u009c\n\2\3\3\3\3\5\3\u00a0\n\3\3\3"+
"\3\3\3\4\6\4\u00a5\n\4\r\4\16\4\u00a6\3\4\3\4\3\4\5\4\u00ac\n\4\3\5\3"+
"\5\6\5\u00b0\n\5\r\5\16\5\u00b1\3\6\3\6\6\6\u00b6\n\6\r\6\16\6\u00b7\3"+
"\7\3\7\6\7\u00bc\n\7\r\7\16\7\u00bd\3\b\3\b\6\b\u00c2\n\b\r\b\16\b\u00c3"+
"\3\b\3\b\7\b\u00c8\n\b\f\b\16\b\u00cb\13\b\5\b\u00cd\n\b\3\t\3\t\6\t\u00d1"+
"\n\t\r\t\16\t\u00d2\3\n\3\n\6\n\u00d7\n\n\r\n\16\n\u00d8\3\13\3\13\3\13"+
"\3\f\3\f\3\f\3\r\3\r\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\20\3\20"+
"\3\20\3\20\3\20\3\20\3\21\3\21\3\21\3\21\3\21\3\21\3\22\3\22\3\22\3\22"+
"\3\22\3\22\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\24\3\24\3\25"+
"\3\25\3\25\3\26\3\26\3\27\3\27\3\30\3\30\3\30\3\30\3\31\3\31\3\31\3\31"+
"\3\32\3\32\3\32\3\32\3\32\3\33\3\33\3\33\3\33\3\33\3\34\3\34\3\34\3\34"+
"\3\34\3\34\3\34\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\36\3\36\3\36"+
"\3\36\3\36\3\37\3\37\3\37\3\37\3\37\3 \3 \3 \3 \3 \3!\3!\3!\3!\3!\3!\3"+
"!\3\"\3\"\3\"\3\"\3#\3#\3#\3#\3#\3#\3#\3#\3$\3$\3$\3$\3$\3$\3$\3$\3%\3"+
"%\3&\3&\3\'\3\'\3(\3(\3(\3(\3)\3)\3)\3*\3*\3*\3*\3+\3+\3+\3,\3,\3,\3-"+
"\3-\3-\3-\3.\3.\3.\3.\3/\3/\3/\3/\3\60\3\60\3\60\3\60\3\61\3\61\3\61\3"+
"\61\3\62\3\62\3\62\3\62\3\63\3\63\3\63\3\63\3\64\3\64\3\64\3\64\3\65\3"+
"\65\3\65\3\65\3\66\3\66\3\66\3\66\3\67\3\67\3\67\3\67\38\38\38\38\38\3"+
"9\39\39\39\39\3:\3:\3:\3:\3:\3;\3;\3;\3;\3;\3<\3<\3=\3=\3>\3>\3?\3?\3"+
"@\3@\7@\u01bb\n@\f@\16@\u01be\13@\3A\3A\3B\3B\3B\3C\6C\u01c6\nC\rC\16"+
"C\u01c7\3C\3C\3D\3D\5D\u01ce\nD\3D\5D\u01d1\nD\3D\3D\3E\3E\7E\u01d7\n"+
"E\fE\16E\u01da\13E\3E\3E\3E\3E\3F\3F\7F\u01e2\nF\fF\16F\u01e5\13F\3F\3"+
"F\3G\3G\3H\3H\3I\3I\3J\3J\3K\3K\3L\3L\4\u00c9\u01d8\2M\3\3\5\4\7\5\t\6"+
"\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\35\20\37\21!\22#\23%\24"+
"\'\25)\26+\27-\30/\31\61\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K"+
"\'M(O)Q*S+U,W-Y.[/]\60_\61a\62c\63e\64g\65i\66k\67m8o9q:s;u<w\2y\2{\2"+
"}\2\177=\u0081>\u0083?\u0085@\u0087A\u0089B\u008bC\u008dD\u008fE\u0091"+
"F\u0093G\u0095H\u0097I\3\2\n\3\2\60\60\4\2\62\63aa\4\2\629aa\6\2\62;C"+
"Haach\5\2C\\aac|\7\2\60\60\62;C\\aac|\4\2\13\13\"\"\4\2\f\f\17\17\2\u0203"+
"\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2"+
"\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2"+
"\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2"+
"\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2"+
"\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3"+
"\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2"+
"\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2\2\2"+
"U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3"+
"\2\2\2\2c\3\2\2\2\2e\3\2\2\2\2g\3\2\2\2\2i\3\2\2\2\2k\3\2\2\2\2m\3\2\2"+
"\2\2o\3\2\2\2\2q\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\2\177\3\2\2\2\2\u0081\3"+
"\2\2\2\2\u0083\3\2\2\2\2\u0085\3\2\2\2\2\u0087\3\2\2\2\2\u0089\3\2\2\2"+
"\2\u008b\3\2\2\2\2\u008d\3\2\2\2\2\u008f\3\2\2\2\2\u0091\3\2\2\2\2\u0093"+
"\3\2\2\2\2\u0095\3\2\2\2\2\u0097\3\2\2\2\3\u009b\3\2\2\2\5\u009f\3\2\2"+
"\2\7\u00ab\3\2\2\2\t\u00ad\3\2\2\2\13\u00b3\3\2\2\2\r\u00b9\3\2\2\2\17"+
"\u00bf\3\2\2\2\21\u00ce\3\2\2\2\23\u00d4\3\2\2\2\25\u00da\3\2\2\2\27\u00dd"+
"\3\2\2\2\31\u00e0\3\2\2\2\33\u00e2\3\2\2\2\35\u00e5\3\2\2\2\37\u00ea\3"+
"\2\2\2!\u00f0\3\2\2\2#\u00f6\3\2\2\2%\u00fc\3\2\2\2\'\u0105\3\2\2\2)\u0107"+
"\3\2\2\2+\u010a\3\2\2\2-\u010c\3\2\2\2/\u010e\3\2\2\2\61\u0112\3\2\2\2"+
"\63\u0116\3\2\2\2\65\u011b\3\2\2\2\67\u0120\3\2\2\29\u0127\3\2\2\2;\u012f"+
"\3\2\2\2=\u0134\3\2\2\2?\u0139\3\2\2\2A\u013e\3\2\2\2C\u0145\3\2\2\2E"+
"\u0149\3\2\2\2G\u0151\3\2\2\2I\u0159\3\2\2\2K\u015b\3\2\2\2M\u015d\3\2"+
"\2\2O\u015f\3\2\2\2Q\u0163\3\2\2\2S\u0166\3\2\2\2U\u016a\3\2\2\2W\u016d"+
"\3\2\2\2Y\u0170\3\2\2\2[\u0174\3\2\2\2]\u0178\3\2\2\2_\u017c\3\2\2\2a"+
"\u0180\3\2\2\2c\u0184\3\2\2\2e\u0188\3\2\2\2g\u018c\3\2\2\2i\u0190\3\2"+
"\2\2k\u0194\3\2\2\2m\u0198\3\2\2\2o\u019c\3\2\2\2q\u01a1\3\2\2\2s\u01a6"+
"\3\2\2\2u\u01ab\3\2\2\2w\u01b0\3\2\2\2y\u01b2\3\2\2\2{\u01b4\3\2\2\2}"+
"\u01b6\3\2\2\2\177\u01b8\3\2\2\2\u0081\u01bf\3\2\2\2\u0083\u01c1\3\2\2"+
"\2\u0085\u01c5\3\2\2\2\u0087\u01d0\3\2\2\2\u0089\u01d4\3\2\2\2\u008b\u01df"+
"\3\2\2\2\u008d\u01e8\3\2\2\2\u008f\u01ea\3\2\2\2\u0091\u01ec\3\2\2\2\u0093"+
"\u01ee\3\2\2\2\u0095\u01f0\3\2\2\2\u0097\u01f2\3\2\2\2\u0099\u009c\5\35"+
"\17\2\u009a\u009c\5\37\20\2\u009b\u0099\3\2\2\2\u009b\u009a\3\2\2\2\u009c"+
"\4\3\2\2\2\u009d\u00a0\5I%\2\u009e\u00a0\5K&\2\u009f\u009d\3\2\2\2\u009f"+
"\u009e\3\2\2\2\u00a0\u00a1\3\2\2\2\u00a1\u00a2\5\7\4\2\u00a2\6\3\2\2\2"+
"\u00a3\u00a5\5w<\2\u00a4\u00a3\3\2\2\2\u00a5\u00a6\3\2\2\2\u00a6\u00a4"+
"\3\2\2\2\u00a6\u00a7\3\2\2\2\u00a7\u00ac\3\2\2\2\u00a8\u00ac\5\t\5\2\u00a9"+
"\u00ac\5\13\6\2\u00aa\u00ac\5\r\7\2\u00ab\u00a4\3\2\2\2\u00ab\u00a8\3"+
"\2\2\2\u00ab\u00a9\3\2\2\2\u00ab\u00aa\3\2\2\2\u00ac\b\3\2\2\2\u00ad\u00af"+
"\5\25\13\2\u00ae\u00b0\5y=\2\u00af\u00ae\3\2\2\2\u00b0\u00b1\3\2\2\2\u00b1"+
"\u00af\3\2\2\2\u00b1\u00b2\3\2\2\2\u00b2\n\3\2\2\2\u00b3\u00b5\5\27\f"+
"\2\u00b4\u00b6\5{>\2\u00b5\u00b4\3\2\2\2\u00b6\u00b7\3\2\2\2\u00b7\u00b5"+
"\3\2\2\2\u00b7\u00b8\3\2\2\2\u00b8\f\3\2\2\2\u00b9\u00bb\5\33\16\2\u00ba"+
"\u00bc\5}?\2\u00bb\u00ba\3\2\2\2\u00bc\u00bd\3\2\2\2\u00bd\u00bb\3\2\2"+
"\2\u00bd\u00be\3\2\2\2\u00be\16\3\2\2\2\u00bf\u00c1\5\u0083B\2\u00c0\u00c2"+
"\5w<\2\u00c1\u00c0\3\2\2\2\u00c2\u00c3\3\2\2\2\u00c3\u00c1\3\2\2\2\u00c3"+
"\u00c4\3\2\2\2\u00c4\u00cc\3\2\2\2\u00c5\u00c9\t\2\2\2\u00c6\u00c8\13"+
"\2\2\2\u00c7\u00c6\3\2\2\2\u00c8\u00cb\3\2\2\2\u00c9\u00ca\3\2\2\2\u00c9"+
"\u00c7\3\2\2\2\u00ca\u00cd\3\2\2\2\u00cb\u00c9\3\2\2\2\u00cc\u00c5\3\2"+
"\2\2\u00cc\u00cd\3\2\2\2\u00cd\20\3\2\2\2\u00ce\u00d0\5\u0081A\2\u00cf"+
"\u00d1\5w<\2\u00d0\u00cf\3\2\2\2\u00d1\u00d2\3\2\2\2\u00d2\u00d0\3\2\2"+
"\2\u00d2\u00d3\3\2\2\2\u00d3\22\3\2\2\2\u00d4\u00d6\5\31\r\2\u00d5\u00d7"+
"\5w<\2\u00d6\u00d5\3\2\2\2\u00d7\u00d8\3\2\2\2\u00d8\u00d6\3\2\2\2\u00d8"+
"\u00d9\3\2\2\2\u00d9\24\3\2\2\2\u00da\u00db\7\62\2\2\u00db\u00dc\7d\2"+
"\2\u00dc\26\3\2\2\2\u00dd\u00de\7\62\2\2\u00de\u00df\7q\2\2\u00df\30\3"+
"\2\2\2\u00e0\u00e1\7y\2\2\u00e1\32\3\2\2\2\u00e2\u00e3\7\62\2\2\u00e3"+
"\u00e4\7z\2\2\u00e4\34\3\2\2\2\u00e5\u00e6\7v\2\2\u00e6\u00e7\7t\2\2\u00e7"+
"\u00e8\7w\2\2\u00e8\u00e9\7g\2\2\u00e9\36\3\2\2\2\u00ea\u00eb\7h\2\2\u00eb"+
"\u00ec\7c\2\2\u00ec\u00ed\7n\2\2\u00ed\u00ee\7u\2\2\u00ee\u00ef\7g\2\2"+
"\u00ef \3\2\2\2\u00f0\u00f1\7s\2\2\u00f1\u00f2\7w\2\2\u00f2\u00f3\7g\2"+
"\2\u00f3\u00f4\7t\2\2\u00f4\u00f5\7{\2\2\u00f5\"\3\2\2\2\u00f6\u00f7\7"+
"c\2\2\u00f7\u00f8\7t\2\2\u00f8\u00f9\7t\2\2\u00f9\u00fa\7c\2\2\u00fa\u00fb"+
"\7{\2\2\u00fb$\3\2\2\2\u00fc\u00fd\7u\2\2\u00fd\u00fe\7{\2\2\u00fe\u00ff"+
"\7o\2\2\u00ff\u0100\7d\2\2\u0100\u0101\7q\2\2\u0101\u0102\7n\2\2\u0102"+
"\u0103\7k\2\2\u0103\u0104\7e\2\2\u0104&\3\2\2\2\u0105\u0106\7<\2\2\u0106"+
"(\3\2\2\2\u0107\u0108\7/\2\2\u0108\u0109\7@\2\2\u0109*\3\2\2\2\u010a\u010b"+
"\7?\2\2\u010b,\3\2\2\2\u010c\u010d\7.\2\2\u010d.\3\2\2\2\u010e\u010f\7"+
"P\2\2\u010f\u0110\7q\2\2\u0110\u0111\7v\2\2\u0111\60\3\2\2\2\u0112\u0113"+
"\7U\2\2\u0113\u0114\7j\2\2\u0114\u0115\7n\2\2\u0115\62\3\2\2\2\u0116\u0117"+
"\7N\2\2\u0117\u0118\7U\2\2\u0118\u0119\7j\2\2\u0119\u011a\7t\2\2\u011a"+
"\64\3\2\2\2\u011b\u011c\7C\2\2\u011c\u011d\7U\2\2\u011d\u011e\7j\2\2\u011e"+
"\u011f\7t\2\2\u011f\66\3\2\2\2\u0120\u0121\7E\2\2\u0121\u0122\7q\2\2\u0122"+
"\u0123\7p\2\2\u0123\u0124\7e\2\2\u0124\u0125\7c\2\2\u0125\u0126\7v\2\2"+
"\u01268\3\2\2\2\u0127\u0128\7G\2\2\u0128\u0129\7z\2\2\u0129\u012a\7v\2"+
"\2\u012a\u012b\7t\2\2\u012b\u012c\7c\2\2\u012c\u012d\7e\2\2\u012d\u012e"+
"\7v\2\2\u012e:\3\2\2\2\u012f\u0130\7\\\2\2\u0130\u0131\7G\2\2\u0131\u0132"+
"\7z\2\2\u0132\u0133\7v\2\2\u0133<\3\2\2\2\u0134\u0135\7U\2\2\u0135\u0136"+
"\7G\2\2\u0136\u0137\7z\2\2\u0137\u0138\7v\2\2\u0138>\3\2\2\2\u0139\u013a"+
"\7T\2\2\u013a\u013b\7g\2\2\u013b\u013c\7c\2\2\u013c\u013d\7f\2\2\u013d"+
"@\3\2\2\2\u013e\u013f\7U\2\2\u013f\u0140\7g\2\2\u0140\u0141\7n\2\2\u0141"+
"\u0142\7g\2\2\u0142\u0143\7e\2\2\u0143\u0144\7v\2\2\u0144B\3\2\2\2\u0145"+
"\u0146\7P\2\2\u0146\u0147\7g\2\2\u0147\u0148\7i\2\2\u0148D\3\2\2\2\u0149"+
"\u014a\7T\2\2\u014a\u014b\7g\2\2\u014b\u014c\7c\2\2\u014c\u014d\7f\2\2"+
"\u014d\u014e\7N\2\2\u014e\u014f\7U\2\2\u014f\u0150\7D\2\2\u0150F\3\2\2"+
"\2\u0151\u0152\7T\2\2\u0152\u0153\7g\2\2\u0153\u0154\7c\2\2\u0154\u0155"+
"\7f\2\2\u0155\u0156\7O\2\2\u0156\u0157\7U\2\2\u0157\u0158\7D\2\2\u0158"+
"H\3\2\2\2\u0159\u015a\7-\2\2\u015aJ\3\2\2\2\u015b\u015c\7/\2\2\u015cL"+
"\3\2\2\2\u015d\u015e\7B\2\2\u015eN\3\2\2\2\u015f\u0160\7C\2\2\u0160\u0161"+
"\7p\2\2\u0161\u0162\7f\2\2\u0162P\3\2\2\2\u0163\u0164\7Q\2\2\u0164\u0165"+
"\7t\2\2\u0165R\3\2\2\2\u0166\u0167\7Z\2\2\u0167\u0168\7q\2\2\u0168\u0169"+
"\7t\2\2\u0169T\3\2\2\2\u016a\u016b\7G\2\2\u016b\u016c\7s\2\2\u016cV\3"+
"\2\2\2\u016d\u016e\7P\2\2\u016e\u016f\7g\2\2\u016fX\3\2\2\2\u0170\u0171"+
"\7W\2\2\u0171\u0172\7n\2\2\u0172\u0173\7v\2\2\u0173Z\3\2\2\2\u0174\u0175"+
"\7W\2\2\u0175\u0176\7n\2\2\u0176\u0177\7g\2\2\u0177\\\3\2\2\2\u0178\u0179"+
"\7W\2\2\u0179\u017a\7i\2\2\u017a\u017b\7v\2\2\u017b^\3\2\2\2\u017c\u017d"+
"\7W\2\2\u017d\u017e\7i\2\2\u017e\u017f\7g\2\2\u017f`\3\2\2\2\u0180\u0181"+
"\7U\2\2\u0181\u0182\7n\2\2\u0182\u0183\7v\2\2\u0183b\3\2\2\2\u0184\u0185"+
"\7U\2\2\u0185\u0186\7n\2\2\u0186\u0187\7g\2\2\u0187d\3\2\2\2\u0188\u0189"+
"\7U\2\2\u0189\u018a\7i\2\2\u018a\u018b\7v\2\2\u018bf\3\2\2\2\u018c\u018d"+
"\7U\2\2\u018d\u018e\7i\2\2\u018e\u018f\7g\2\2\u018fh\3\2\2\2\u0190\u0191"+
"\7C\2\2\u0191\u0192\7f\2\2\u0192\u0193\7f\2\2\u0193j\3\2\2\2\u0194\u0195"+
"\7U\2\2\u0195\u0196\7w\2\2\u0196\u0197\7d\2\2\u0197l\3\2\2\2\u0198\u0199"+
"\7O\2\2\u0199\u019a\7w\2\2\u019a\u019b\7n\2\2\u019bn\3\2\2\2\u019c\u019d"+
"\7W\2\2\u019d\u019e\7F\2\2\u019e\u019f\7k\2\2\u019f\u01a0\7x\2\2\u01a0"+
"p\3\2\2\2\u01a1\u01a2\7W\2\2\u01a2\u01a3\7T\2\2\u01a3\u01a4\7g\2\2\u01a4"+
"\u01a5\7o\2\2\u01a5r\3\2\2\2\u01a6\u01a7\7U\2\2\u01a7\u01a8\7F\2\2\u01a8"+
"\u01a9\7k\2\2\u01a9\u01aa\7x\2\2\u01aat\3\2\2\2\u01ab\u01ac\7U\2\2\u01ac"+
"\u01ad\7T\2\2\u01ad\u01ae\7g\2\2\u01ae\u01af\7o\2\2\u01afv\3\2\2\2\u01b0"+
"\u01b1\4\62;\2\u01b1x\3\2\2\2\u01b2\u01b3\t\3\2\2\u01b3z\3\2\2\2\u01b4"+
"\u01b5\t\4\2\2\u01b5|\3\2\2\2\u01b6\u01b7\t\5\2\2\u01b7~\3\2\2\2\u01b8"+
"\u01bc\t\6\2\2\u01b9\u01bb\t\7\2\2\u01ba\u01b9\3\2\2\2\u01bb\u01be\3\2"+
"\2\2\u01bc\u01ba\3\2\2\2\u01bc\u01bd\3\2\2\2\u01bd\u0080\3\2\2\2\u01be"+
"\u01bc\3\2\2\2\u01bf\u01c0\7k\2\2\u01c0\u0082\3\2\2\2\u01c1\u01c2\7h\2"+
"\2\u01c2\u01c3\7r\2\2\u01c3\u0084\3\2\2\2\u01c4\u01c6\t\b\2\2\u01c5\u01c4"+
"\3\2\2\2\u01c6\u01c7\3\2\2\2\u01c7\u01c5\3\2\2\2\u01c7\u01c8\3\2\2\2\u01c8"+
"\u01c9\3\2\2\2\u01c9\u01ca\bC\2\2\u01ca\u0086\3\2\2\2\u01cb\u01cd\7\17"+
"\2\2\u01cc\u01ce\7\f\2\2\u01cd\u01cc\3\2\2\2\u01cd\u01ce\3\2\2\2\u01ce"+
"\u01d1\3\2\2\2\u01cf\u01d1\7\f\2\2\u01d0\u01cb\3\2\2\2\u01d0\u01cf\3\2"+
"\2\2\u01d1\u01d2\3\2\2\2\u01d2\u01d3\bD\2\2\u01d3\u0088\3\2\2\2\u01d4"+
"\u01d8\7%\2\2\u01d5\u01d7\13\2\2\2\u01d6\u01d5\3\2\2\2\u01d7\u01da\3\2"+
"\2\2\u01d8\u01d9\3\2\2\2\u01d8\u01d6\3\2\2\2\u01d9\u01db\3\2\2\2\u01da"+
"\u01d8\3\2\2\2\u01db\u01dc\7%\2\2\u01dc\u01dd\3\2\2\2\u01dd\u01de\bE\2"+
"\2\u01de\u008a\3\2\2\2\u01df\u01e3\7%\2\2\u01e0\u01e2\n\t\2\2\u01e1\u01e0"+
"\3\2\2\2\u01e2\u01e5\3\2\2\2\u01e3\u01e1\3\2\2\2\u01e3\u01e4\3\2\2\2\u01e4"+
"\u01e6\3\2\2\2\u01e5\u01e3\3\2\2\2\u01e6\u01e7\bF\2\2\u01e7\u008c\3\2"+
"\2\2\u01e8\u01e9\7*\2\2\u01e9\u008e\3\2\2\2\u01ea\u01eb\7+\2\2\u01eb\u0090"+
"\3\2\2\2\u01ec\u01ed\7]\2\2\u01ed\u0092\3\2\2\2\u01ee\u01ef\7_\2\2\u01ef"+
"\u0094\3\2\2\2\u01f0\u01f1\7}\2\2\u01f1\u0096\3\2\2\2\u01f2\u01f3\7\177"+
"\2\2\u01f3\u0098\3\2\2\2\25\2\u009b\u009f\u00a6\u00ab\u00b1\u00b7\u00bd"+
"\u00c3\u00c9\u00cc\u00d2\u00d8\u01bc\u01c7\u01cd\u01d0\u01d8\u01e3\3\b"+
"\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
} |
#!/usr/bin/env bash
exec php-fpm7.4 -c /etc/php/7.4/cli/php.ini |
<filename>lib/ping.js
/*
* express-mfs
*
* Copyright(c) 2020 <NAME>
* MIT Licensed
*/
"use strict";
var debug = require("debug")("express-mfs:ping");
module.exports = ping;
// =============================================================================
// ping middleware
// =============================================================================
function ping(req, res, next)
{
var err;
// only support registering on GET method
if (req.method !== "GET")
{
err = new Error("express-mfs: not found");
res.statusCode = 404;
return(next(err));
}
// only support JSON
if (!req.accepts("JSON"))
{
err = new Error("express-mfs: invalid Accept type");
res.statusCode = 406;
return(next(err));
}
res.json({message: "pong"});
return;
} |
#!/usr/bin/env bash
# Copyright 2018 Ryan Wick (rrwick@gmail.com)
# https://github.com/rrwick/Bacsort
# This script runs FastANI in parallel to build a distance matrix between all assembly clusters. It
# takes one argument: the number of threads.
# This file is part of Bacsort. Bacsort is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version. Bacsort is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details. You should have received a copy of the GNU General Public License along with
# Bacsort. If not, see <http://www.gnu.org/licenses/>.
mkdir -p tree
printf "\n"
echo "Find pairwise distances with FastANI"
echo "------------------------------------------------"
cd clusters
ls *.fna.gz > cluster_list
total_count=$( wc -l < cluster_list )
count_per_file=$( perl -w -e "use POSIX; print ceil($total_count/$1), qq{\n}" )
cat cluster_list | shuf > split.tmp
split -a 4 -dl $count_per_file split.tmp cluster_list_
rm split.tmp
for q in cluster_list_*; do
q_num=$(echo $q | sed 's/cluster_list_//')
for r in cluster_list_*; do
r_num=$(echo $r | sed 's/cluster_list_//')
echo "Running FastANI on clusters "$q_num" and "$r_num
fastANI --rl $r --ql $q -o ../tree/fastani_output_"$q_num"_"$r_num" &> ../tree/fastani_stdout_"$q_num"_"$r_num" &
done
printf "Waiting for results... "
wait
echo "done"
done
cd ..
cat tree/fastani_output_* > tree/fastani_output
rm tree/fastani_output_* tree/fastani_stdout_*
|
<filename>python/src/v3/pin.py
import json
from api_media_object import ApiMediaObject
class Pin(ApiMediaObject):
def __init__(self, pin_id, api_config, access_token):
super().__init__(api_config, access_token)
self.pin_id = pin_id
# https://developers.pinterest.com/docs/redoc/#operation/v3_get_pin_GET
def get(self):
if not self.pin_id:
raise ValueError("pin_id must be set to get a pin")
return self.request_data("/v3/pins/{}/".format(self.pin_id))
@classmethod
def print_summary(cls, pin_data):
print("--- Pin Summary ---")
print(f"Pin ID: {pin_data['id']}")
print(f"Type: {pin_data['type']}")
if pin_data["type"] == "pin":
print(f"Description: {pin_data.get('description')}")
print(f"Domain: {pin_data.get('domain')}")
print(f"Native format type: {pin_data.get('native_format_type')}")
elif pin_data["type"] == "story":
print(f"Story type: {pin_data.get('story_type')}")
print("--------------------")
# https://developers.pinterest.com/docs/redoc/#operation/v3_create_pin_handler_PUT
def create(self, pin_data, board_id, section=None, media=None):
OPTIONAL_ATTRIBUTES = [
"alt_text",
"description",
"title",
]
create_data = {"board_id": board_id, "image_url": pin_data["image_large_url"]}
# https://developers.pinterest.com/docs/redoc/#section/Using-video-APIs
media_id = self.media_to_media_id(media)
if media_id:
self.check_upload_id(media_id)
create_data["media_upload_id"] = media_id
if section:
create_data["section"] = section
link = pin_data.get("link")
if link:
create_data["source_url"] = link
carousel_data = pin_data.get("carousel_data")
if carousel_data:
create_data["carousel_data_json"] = json.dumps(
carousel_data, separators=(",", ":")
)
for key in OPTIONAL_ATTRIBUTES:
value = pin_data.get(key)
if value:
create_data[key] = value
pin_data = self.put_data("/v3/pins/", create_data)
self.pin_id = pin_data["id"]
return pin_data
# https://developers.pinterest.com/docs/redoc/#operation/register_media_upload_POST
def upload_media(self, media_path):
"""
Upload a video from the specified path and return a media_id.
Called by ApiMediaObject:media_to_media_id().
"""
media_upload = self.post_data("/v3/media/uploads/register/", {"type": "video"})
self.upload_file_multipart(
media_upload["upload_url"], media_path, media_upload["upload_parameters"]
)
return media_upload["upload_id"]
# https://developers.pinterest.com/docs/redoc/#operation/get_media_uploads_GET
def check_upload_id(self, upload_id):
"""
Poll for the status of the upload until it is complete.
"""
self.reset_backoff()
while True:
media_response = self.request_data(
f"/v3/media/uploads/?upload_ids={upload_id}"
)
upload_record = media_response.get(upload_id)
if not upload_record:
raise RuntimeError(f"upload {upload_id} not found")
status = upload_record.get("status")
if not status:
raise RuntimeError(f"upload {upload_id} has no status")
if status == "succeeded":
return
if status == "failed":
failure_code = upload_record.get("failure_code", "unknown")
raise RuntimeError(
f"upload {upload_id} failed with code: {failure_code}"
)
self.wait_backoff(f"Upload {upload_id} status: {status}.")
|
SELECT Position, MAX(Salary)
FROM Employees
GROUP BY Position; |
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Navbar, Nav, Form, FormControl, Button } from 'react-bootstrap';
import About from './components/about.component';
import Home from './components/home.component';
import logo from "./skull.png";
class App extends Component {
constructor(props) {
super(props);
this.state = {
location: null,
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit() {
this.setState({ location: 'location=' + document.getElementById('input').value });
}
componentWillMount() {
navigator.geolocation.getCurrentPosition(position => {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
if (latitude && longitude) {
this.setState({
location: `latitude=${latitude}&longitude=${longitude}`
});
}
});
}
render() {
return (
<Router>
<div className="container">
<Navbar bg="light" expand="lg">
<Navbar.Brand>
<a className="navbar-brand" href="/">
<img src={logo} width="30" height="30" alt="logo" />
</a>
<Link to="/" className="navbar-brand">AppsByNick™</Link>
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav>
<Link to="/" className="nav-link float-right">Home</Link>
</Nav>
<Nav>
<Link to="/about" className="nav-link float-right">About</Link>
</Nav>
</Nav>
<Form inline>
<FormControl id="input" type="text" placeholder="City, Hood, Zip" className="mr-sm-2" />
<Button variant="outline-success" onClick={this.handleSubmit}>Submit</Button>
</Form>
</Navbar.Collapse>
</Navbar>
<h2 className="text-center bg-light text-dark">Resturant Decision Maker</h2>
<Route path="/" exact component={(location) => <Home location={this.state.location} />} />
<Route path="/about" component={(location) => <About location={this.state.location} />} />
</div>
</Router>
);
}
}
export default App; |
<reponame>jetmuffin/dlkit-frontend
export default {
'GET /oauth/access_token':(req,res)=>{while(true);},
} |
def max_difference(arr):
if len(arr) < 2:
return 0
curr_max = arr[1]-arr[0]
min_elem = min(arr[0], arr[1])
for i in range(2, len(arr)):
curr_max = max(curr_max, arr[i] - min_elem)
min_elem = min(min_elem, arr[i])
return curr_max
print(max_difference([2, 3, 10, 6, 4, 8, 1])) |
import re
from typing import List, Optional
def extract_substrings(input_string: str, pattern_list: List[str]) -> List[Optional[str]]:
matched_substrings = []
for pattern in pattern_list:
match = re.match(pattern, input_string)
if match:
matched_substrings.append(match.group(1))
else:
matched_substrings.append(None)
return matched_substrings |
#!/bin/bash -u
set -e
#
# Copyright (c) 2012 Tresys Technology LLC, Columbia, Maryland, USA
#
# This software was developed by Tresys Technology LLC
# with U.S. Government sponsorship.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# 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.
. $(dirname $0)/audit_rules_common
add_rule '-w /etc/selinux -p wa -l MAC-policy'
|
<reponame>OSWeDev/oswedev
import IAPIParamTranslator from "../../interfaces/IAPIParamTranslator";
import IAPIParamTranslatorStatic from "../../interfaces/IAPIParamTranslatorStatic";
export default class StringParamVO implements IAPIParamTranslator<StringParamVO> {
public static URL: string = ':text';
public static fromREQ(req): StringParamVO {
if (!(req && req.params)) {
return null;
}
return new StringParamVO(req.params.text);
}
public static fromParams(text: string): StringParamVO {
return new StringParamVO(text);
}
public static getAPIParams(param: StringParamVO): any[] {
return [param.text];
}
public constructor(
public text: string) {
}
public translateToURL(): string {
return this.text;
}
}
export const StringParamVOStatic: IAPIParamTranslatorStatic<StringParamVO> = StringParamVO; |
RangeError();
|
<reponame>ClaudioMayoral/ProyectoFinalWeb
//Creacion de la mini aplicaciones const app = express()
const router = require("express").Router()
const usuarioController = require('../../controllers/usuario/blueprint')
//generar las rutas
router.get("/:id",usuarioController.getUsuario)
router.post('/crear',usuarioController.createUsuario)
router.post('/actualizar/:id',usuarioController.updateUsuario)
router.post('/eliminar/:id',usuarioController.deleteUsuario)
module.exports = router
|
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# Load and prepare the dataset
dataset = pd.read_csv('dataset.csv')
X = dataset.iloc[:,:-1]
y = dataset.iloc[:,-1]
# Instantiate the classifier
clf = RandomForestClassifier()
# Train the classifier
clf.fit(X, y)
# Predict the labels of the test data
predictions = clf.predict(X)
# Accuracy score of the predictions
accuracy = accuracy_score(y, predictions) |
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class NumberOperations {
public List<Integer> modifyList(List<Integer> numbers) {
List<Integer> modifiedList = new ArrayList<>();
// Replace negative numbers with their absolute values
for (int num : numbers) {
modifiedList.add(Math.abs(num));
}
// Remove duplicates and sort the list
Set<Integer> uniqueNumbers = new HashSet<>(modifiedList);
modifiedList.clear();
modifiedList.addAll(uniqueNumbers);
modifiedList.sort(null);
return modifiedList;
}
} |
import lib2to3
from lib2to3 import fixer_base
from lib2to3.pytree import Node
from lib2to3.fixer_util import LParen, RParen, Name
class FixNewstyle(fixer_base.BaseFix):
PATTERN = "classdef< 'class' name=NAME ['(' ')'] colon=':' any >"
def transform(self, node, results):
name = results["name"]
if not results.get("paren"):
# If the class definition does not have parentheses, insert them
self.insert_object(node, 2)
return node
def insert_object(self, node, idx):
node.insert_child(idx, RParen())
node.insert_child(idx, Name(u"object"))
node.insert_child(idx, LParen())
# Example usage
code = "class MyClass:\n pass"
fixer = FixNewstyle(None, None)
tree = lib2to3.pgen2.parse_string(code)
fixer.refactor_tree(tree)
print(tree) |
import uk.gov.bis.lite.user.api.view.enums.AccountStatus;
import java.util.HashMap;
import java.util.Map;
public class AccountStatusProcessor {
public static Map<AccountStatus, Integer> countAccountStatus(AccountStatus[] accountStatuses) {
Map<AccountStatus, Integer> statusCountMap = new HashMap<>();
for (AccountStatus status : accountStatuses) {
statusCountMap.put(status, statusCountMap.getOrDefault(status, 0) + 1);
}
return statusCountMap;
}
public static void main(String[] args) {
AccountStatus[] statuses = {AccountStatus.ACTIVE, AccountStatus.PENDING_APPROVAL, AccountStatus.ACTIVE,
AccountStatus.INACTIVE, AccountStatus.SUSPENDED, AccountStatus.ACTIVE, AccountStatus.CLOSED,
AccountStatus.INACTIVE, AccountStatus.ACTIVE, AccountStatus.SUSPENDED, AccountStatus.SUSPENDED};
Map<AccountStatus, Integer> statusCount = countAccountStatus(statuses);
System.out.println(statusCount);
}
} |
#!/bin/sh
#
# DNS support routines for assigning DNS entries for several devices. This
# module adds DNS support for scripts.
#
RESOLV_FILE="/tmp/resolv.conf"
DNS_TMP="/tmp/dns"
dns_reset()
{
local iface="$1"; shift
local resolv="${DNS_TMP}/${iface}.resolv"
mkdir -p "${DNS_TMP}"
# Touch temporary resolv file
echo -n > "${resolv}.$$"
}
dns_add()
{
local iface="$1" ; shift
local resolv="${DNS_TMP}/${iface}.resolv"
echo "$@" >> "${resolv}.$$"
}
dns_apply()
{
local iface="$1" ; shift
local resolv="${DNS_TMP}/${iface}.resolv"
[ -e "${resolv}.$$" ] && {
mv -f "${resolv}.$$" "${resolv}"
}
find "${DNS_TMP}" -name '*.resolv' -exec cat {} \; > "${RESOLV_FILE}.$$"
mv "${RESOLV_FILE}.$$" "${RESOLV_FILE}"
}
|
package br.com.controle.financeiro.service.impl;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import javax.transaction.Transactional;
import br.com.controle.financeiro.configuration.security.SecurityConfig.Roles;
import br.com.controle.financeiro.configuration.security.auth.firebase.FirebaseAuthenticationToken;
import br.com.controle.financeiro.model.entity.Role;
import br.com.controle.financeiro.model.entity.UserEntity;
import br.com.controle.financeiro.model.repository.RoleRepository;
import br.com.controle.financeiro.model.repository.UserRepository;
import br.com.controle.financeiro.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service(value = UserServiceImpl.NAME)
public class UserServiceImpl implements UserService {
public static final String NAME = "UserService";
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
public UserDetails loadUserByUsername(String username) {
Optional<UserEntity> user = userRepository.findById(username);
if (user.isEmpty()) {
throw new UsernameNotFoundException("Bad credentials");
}
UserEntity userDetails = user.get();
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (GrantedAuthority role : userDetails.getAuthorities()) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getAuthority()));
}
return new User(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
}
@Override
@Transactional
@Secured(value = Roles.ROLE_ANONYMOUS)
public UserEntity registerUser(RegisterUserInit init) {
Optional<UserEntity> userLoaded = userRepository.findById(init.getUserName());
if (userLoaded.isEmpty()) {
UserEntity userEntity = new UserEntity();
userEntity.setName(init.getName());
userEntity.setEmail(init.getEmail());
userEntity.setId(init.getUserName());
userEntity.setAuthorities(getUserRoles());
// TODO firebase users should not be able to login via username and
// password so for now generation of password is OK
userEntity.setPassword(<PASSWORD>());
userRepository.save(userEntity);
logger.info("registerUser -> user created");
return userEntity;
} else {
logger.info("registerUser -> user exists");
return userLoaded.get();
}
}
@Override
public UserEntity getAuthenticatedUser() {
String user;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof FirebaseAuthenticationToken) {
user = String.valueOf(((UserDetails) auth.getPrincipal()).getUsername());
return userRepository.findById(user).orElseThrow();
}
throw new UsernameNotFoundException("Bad credentials");
}
private List<Role> getUserRoles() {
return Collections.singletonList(getRole(Roles.ROLE_USER));
}
private Role getRole(String authority) {
Role adminRole = roleRepository.findByAuthority(authority);
return Objects.requireNonNullElseGet(adminRole, () -> new Role(authority));
}
}
|
#!/bin/bash
TASK=18
MODEL=ctrl_visualbert
MODEL_CONFIG=ctrl_visualbert_base
TASKS_CONFIG=xm-influence_test_tasks
PRETRAINED=/science/image/nlp-datasets/emanuele/checkpoints/mpre-unmasked/conceptual_captions_s1234/volta/ctrl_visualbert/ctrl_visualbert_base/pytorch_model_9.bin
OUTPUT_DIR=/science/image/nlp-datasets/emanuele/results/xm-influence/flickr30kentities_vis4lang/${MODEL}_s1234
source activate /science/image/nlp-datasets/emanuele/envs/xm-influence
cd ../../../../volta
python ablate_vis4lang.py \
--bert_model bert-base-uncased --config_file config/${MODEL_CONFIG}.json --from_pretrained ${PRETRAINED} \
--tasks_config_file config_tasks/${TASKS_CONFIG}.yml --task $TASK --split val \
--output_dir ${OUTPUT_DIR} --dump_results --masking all
conda deactivate
|
<filename>src/1darray/pack_float.h
#ifndef _1DARRAY_PACK_FLOAT_H
#define _1DARRAY_PACK_FLOAT_H
void pack_1darray_f32_data(unsigned char buf[], unsigned size,
float const arr[]);
void pack_1darray_f32_data_in(unsigned char buf[], unsigned size);
void pack_1darray_f64_data(unsigned char buf[], unsigned size,
double const arr[]);
void pack_1darray_f64_data_in(unsigned char buf[], unsigned size);
#endif
|
<gh_stars>100-1000
///////////////////////////////////////////////////////////////
// Copyright 2021 <NAME>. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
//
#ifdef _MSC_VER
#define _SCL_SECURE_NO_WARNINGS
#endif
#include <thread>
#include <boost/detail/lightweight_test.hpp>
#include <boost/array.hpp>
#include <boost/math/special_functions/relative_difference.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/quadrature/tanh_sinh.hpp>
#include "test.hpp"
#if !defined(TEST_MPF_50) && !defined(TEST_MPFR_50)
#define TEST_MPF_50
#define TEST_MPFR_50
#ifdef _MSC_VER
#pragma message("CAUTION!!: No backend type specified so testing everything.... this will take some time!!")
#endif
#ifdef __GNUC__
#pragma warning "CAUTION!!: No backend type specified so testing everything.... this will take some time!!"
#endif
#endif
#include <boost/multiprecision/mpfr.hpp>
#if defined(TEST_MPF_50)
#include <boost/multiprecision/gmp.hpp>
#endif
template <class T>
void thread_test_proc(unsigned digits)
{
typedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<1000> > mpfr_float_1000;
if (!mpfr_buildopt_tls_p())
return;
T::thread_default_precision(digits);
T result, value;
value = boost::math::constants::pi<T>();
result.assign(boost::math::constants::pi<mpfr_float_1000>().str());
BOOST_CHECK_LE(boost::math::epsilon_difference(value, result), 20);
BOOST_CHECK_EQUAL(value.precision(), digits);
for (unsigned i = 20; i < 500; ++i)
{
T arg(i);
arg /= 3;
value = boost::math::tgamma(arg);
BOOST_CHECK_EQUAL(value.precision(), digits);
result.assign(boost::math::tgamma(mpfr_float_1000(arg)).str());
BOOST_CHECK_LE(boost::math::epsilon_difference(value, result), 800);
}
//
// Try tanh_sinh integration:
//
using namespace boost::math::constants;
boost::math::quadrature::tanh_sinh<T> integrator;
T tol = 500;
// Example 1:
auto f1 = [](const T& t) { return static_cast<T>(t * boost::math::log1p(t)); };
T Q = integrator.integrate(f1, (T)0, (T)1);
T Q_expected = half<T>() * half<T>();
BOOST_CHECK_EQUAL(Q.precision(), digits);
BOOST_CHECK_EQUAL(Q_expected.precision(), digits);
BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);
// Example 2:
auto f2 = [](const T& t) { return static_cast<T>(t * t * atan(t)); };
Q = integrator.integrate(f2, (T)0, (T)1);
Q_expected = (pi<T>() - 2 + 2 * ln_two<T>()) / 12;
BOOST_CHECK_EQUAL(Q.precision(), digits);
BOOST_CHECK_EQUAL(Q_expected.precision(), digits);
BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);
// Example 3:
auto f3 = [](const T& t) { return static_cast<T>(exp(t) * cos(t)); };
Q = integrator.integrate(f3, (T)0, half_pi<T>());
Q_expected = boost::math::expm1(half_pi<T>()) * half<T>();
BOOST_CHECK_EQUAL(Q.precision(), digits);
BOOST_CHECK_EQUAL(Q_expected.precision(), digits);
BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);
// Example 4:
auto f4 = [](T x) -> T { T t0 = sqrt(x*x + 2); return atan(t0)/(t0*(x*x+1)); };
Q = integrator.integrate(f4, (T)0, (T)1);
Q_expected = 5 * pi<T>() * pi<T>() / 96;
BOOST_CHECK_EQUAL(Q.precision(), digits);
BOOST_CHECK_EQUAL(Q_expected.precision(), digits);
BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);
// Example 5:
auto f5 = [](const T& t)->T { return sqrt(t) * log(t); };
Q = integrator.integrate(f5, (T)0, (T)1);
Q_expected = -4 / (T)9;
BOOST_CHECK_EQUAL(Q.precision(), digits);
BOOST_CHECK_EQUAL(Q_expected.precision(), digits);
BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);
// Example 6:
auto f6 = [](const T& t)->T { return sqrt(1 - t * t); };
Q = integrator.integrate(f6, (T)0, (T)1);
Q_expected = pi<T>() / 4;
BOOST_CHECK_EQUAL(Q.precision(), digits);
BOOST_CHECK_EQUAL(Q_expected.precision(), digits);
BOOST_CHECK_LE(boost::math::epsilon_difference(Q, Q_expected), tol);
}
int main()
{
#ifdef TEST_MPF_50
{
std::thread t1(thread_test_proc<boost::multiprecision::mpf_float>, 35);
std::thread t2(thread_test_proc<boost::multiprecision::mpf_float>, 55);
std::thread t3(thread_test_proc<boost::multiprecision::mpf_float>, 75);
std::thread t4(thread_test_proc<boost::multiprecision::mpf_float>, 105);
std::thread t5(thread_test_proc<boost::multiprecision::mpf_float>, 305);
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
}
#endif
#ifdef TEST_MPFR_50
{
std::thread t1(thread_test_proc<boost::multiprecision::mpfr_float>, 35);
std::thread t2(thread_test_proc<boost::multiprecision::mpfr_float>, 55);
std::thread t3(thread_test_proc<boost::multiprecision::mpfr_float>, 75);
std::thread t4(thread_test_proc<boost::multiprecision::mpfr_float>, 105);
std::thread t5(thread_test_proc<boost::multiprecision::mpfr_float>, 305);
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
}
#endif
return boost::report_errors();
}
|
<gh_stars>0
import React, { useRef } from 'react';
import Column from '../Column';
import Row from '../Row';
function Filters(props) {
const employeeName = useRef(null);
const employeeOccupation = useRef(null);
const employeeDepartment = useRef(null);
const salaryGreater = useRef(null);
const employeeSalary = useRef(null);
const submitFilters = event => {
event.preventDefault();
const nameVal = employeeName.current.value.toLowerCase();
const occupationVal = employeeOccupation.current.value.toLowerCase();
const departmentVal = employeeDepartment.current.value.toLowerCase();
const isSalaryGreater = salaryGreater.current.checked;
const salaryVal = parseInt(employeeSalary.current.value);
const filters = {
name: nameVal.length > 0 ? nameVal : null,
occupation: occupationVal.length > 0 ? occupationVal : null,
department: departmentVal.length > 0 ? departmentVal : null,
isGreater: isSalaryGreater,
salary: !isNaN(salaryVal) && salaryVal > 0 ? salaryVal : null
};
props.setFilters(filters);
};
return (
<form>
<Row>
<Column>
<label htmlFor='filterEmployeeName'>Name:</label>
<input type='text' ref={employeeName} id='filterEmployeeName' placeholder='<NAME>' />
</Column>
<Column>
<label htmlFor='filterEmployeeOccupation'>Occupation:</label>
<input
type='text'
ref={employeeOccupation}
id='filterEmployeeOccupation'
placeholder='Sales Manager'
/>
</Column>
<Column>
<label htmlFor='filterEmployeeDepartment'>Department:</label>
<input
type='text'
ref={employeeDepartment}
id='filterEmployeeDepartment'
placeholder='Sales'
/>
</Column>
<Column>
<label htmlFor='filterEmployeeSalary'>Salary: </label>
<label htmlFor='greaterThan'>>=</label>
<input
type='radio'
ref={salaryGreater}
id='greaterThan'
name='filterSalaryOption'
defaultChecked={true}
/>
<label htmlFor='lessThan'><=</label>
<input type='radio' id='lessThan' name='filterSalaryOption' />
<input
type='number'
ref={employeeSalary}
id='filterEmployeeSalary'
placeholder='120000'
/>
</Column>
<Column>
<button type='submit' onClick={submitFilters} className='btn-sm btn-primary'>
Filter Employees
</button>
</Column>
</Row>
</form>
);
}
export default Filters;
|
package edu.fiuba.algo3.modelo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
public class DibujoTest {
@Test
public void testDibujoCrearTramo_deberiaDevolverErrorSiLaPosicionDeInicioYFinSonIguales() {
Posicion inicio = new Posicion(0, 0);
Posicion fin = new Posicion(0, 0);
Dibujo dibujo = new Dibujo();
try {
dibujo.crearTramo(inicio, fin);
fail("Debería lanzar TramoInvalidoPosicionDeInicioYFinIgualesException");
} catch (Exception e) {
assertEquals(TramoInvalidoPosicionDeInicioYFinIgualesException.class, e.getClass());
}
}
@Test
public void testDibujoObtenerTramos_deberiaDevolverUnaListaVaciaSiNoSeCrearonTramos() {
Dibujo dibujo = new Dibujo();
List<Tramo> tramos = dibujo.obtenerTramos();
assertTrue(tramos.isEmpty());
}
@Test
public void testDibujoObtenerTramos_deberiaDevolverUnaListaConLosTramosCreados() throws Exception {
Dibujo dibujo = new Dibujo();
List<Tramo> tramos = new ArrayList<>(List.of(
new Tramo(new Posicion(0,0), new Posicion(1,0)),
new Tramo(new Posicion(0,0), new Posicion(0,1)),
new Tramo(new Posicion(0,0), new Posicion(-1,0)),
new Tramo(new Posicion(0,0), new Posicion(0,-1))
));
assertTrue(dibujo.obtenerTramos().isEmpty());
dibujo.crearTramo(new Posicion(0,0), new Posicion(1,0));
dibujo.crearTramo(new Posicion(0,0), new Posicion(0,1));
dibujo.crearTramo(new Posicion(0,0), new Posicion(-1,0));
dibujo.crearTramo(new Posicion(0,0), new Posicion(0,-1));
assertFalse(dibujo.obtenerTramos().isEmpty());
List<Tramo> tramosCreados = dibujo.obtenerTramos();
tramosCreados.forEach(tramo -> assertTrue(
tramos.stream().anyMatch(unTramo -> unTramo.equals(tramo))));
assertEquals(tramosCreados.size(), tramos.size());
}
@Test
public void testDibujoContieneTramo_deberiaDevolverTrueSiLoContiene() throws Exception {
Posicion inicio = new Posicion(0,0);
Posicion fin = new Posicion(1,0);
Tramo tramo = new Tramo(inicio, fin);
Dibujo dibujo = new Dibujo();
dibujo.crearTramo(inicio, fin);
assertTrue(dibujo.contieneTramo(tramo));
}
@Test
public void testDibujoContieneTramo_deberiaDevolverFalseSiNoLoContiene() throws Exception {
Posicion inicio = new Posicion(0,0);
Posicion fin = new Posicion(1,0);
Posicion otroFin = new Posicion(0,1);
Tramo tramo = new Tramo(inicio, otroFin);
Dibujo dibujo = new Dibujo();
dibujo.crearTramo(inicio, fin);
assertFalse(dibujo.contieneTramo(tramo));
}
}
|
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for DLA-619-1
#
# Security announcement date: 2016-09-11 00:00:00 UTC
# Script generation date: 2017-01-01 21:09:18 UTC
#
# Operating System: Debian 7 (Wheezy)
# Architecture: i386
#
# Vulnerable packages fix on version:
# - qemu-kvm:1.1.2+dfsg-6+deb7u15
#
# Last versions recommanded by security team:
# - qemu-kvm:1.1.2+dfsg-6+deb7u19
#
# CVE List:
# - CVE-2016-7116
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo apt-get install --only-upgrade qemu-kvm=1.1.2+dfsg-6+deb7u19 -y
|
import React from 'react';
import FancyLink from './FancyLink';
import SignIn from './SignIn';
const mainLogo = require('./../assets/white_logo_transparent.png');
const Welcome = (props) => {
return (
<div>
<img src={mainLogo} alt='Sweat Deck Logo' style={{display: 'block', margin: 'auto', marginTop: '20px', marginBottom: '15px', height: '330px', width: '330px'}}/>
<SignIn {...props} onSignIn={props.onSignIn}/>
<div style={{marginTop: '85px'}}>
<FancyLink linkTo='/register' linkName='REGISTER'/>
</div>
</div>
)
}
export default Welcome;
|
#! /bin/bash
#SBATCH -o /home/martin/workspace/sweet/benchmarks/rexi_tests_lrz_freq_waves/2015_12_27_scalability_rexi_fd/run_rexi_par_m000512_t008_n0128_r0008_a1.txt
###SBATCH -e /home/martin/workspace/sweet/benchmarks/rexi_tests_lrz_freq_waves/2015_12_27_scalability_rexi_fd/run_rexi_par_m000512_t008_n0128_r0008_a1.err
#SBATCH -J rexi_par_m000512_t008_n0128_r0008_a1
#SBATCH --get-user-env
#SBATCH --clusters=mpp2
#SBATCH --ntasks=8
#SBATCH --cpus-per-task=8
#SBATCH --exclusive
#SBATCH --export=NONE
#SBATCH --time=08:00:00
#declare -x NUMA_BLOCK_ALLOC_VERBOSITY=1
declare -x KMP_AFFINITY="granularity=thread,compact,1,0"
declare -x OMP_NUM_THREADS=8
echo "OMP_NUM_THREADS=$OMP_NUM_THREADS"
echo
. /etc/profile.d/modules.sh
module unload gcc
module unload fftw
module unload python
module load python/2.7_anaconda_nompi
module unload intel
module load intel/16.0
module unload mpi.intel
module load mpi.intel/5.1
module load gcc/5
cd /home/martin/workspace/sweet/benchmarks/rexi_tests_lrz_freq_waves/2015_12_27_scalability_rexi_fd
cd ../../../
. local_software/env_vars.sh
# force to use FFTW WISDOM data
declare -x SWEET_FFTW_LOAD_WISDOM_FROM_FILE="FFTW_WISDOM_nofreq_T0"
time -p mpiexec.hydra -genv OMP_NUM_THREADS 8 -envall -ppn 3 -n 8 ./build/rexi_par_m_tno_a1 --initial-freq-x-mul=2.0 --initial-freq-y-mul=1.0 -f 1 -g 1 -H 1 -X 1 -Y 1 --compute-error 1 -t 50 -R 4 -C 0.3 -N 128 -U 0 -S 0 --use-specdiff-for-complex-array 1 --rexi-h 0.2 --timestepping-mode 1 --staggering 0 --rexi-m=512 -C -5.0
|
<reponame>mnenad/pizza-poc-frontend
import {Component, ElementRef, Inject} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {OrderDetail} from "../model/orderDetail";
import {LoginService} from "../service/login.service";
import {Router} from "@angular/router";
import {OrderService} from "../service/order.service";
import {Toppings} from "./toppings";
import {ConfigService} from "../service/config.service";
@Component({
selector: 'order',
templateUrl: 'order.component.html',
styleUrls: ['order.scss']
})
export class OrderComponent {
private http: Http;
public toppings: Toppings;
private loginService: LoginService;
private router: Router;
private orderService: OrderService;
private configService: ConfigService;
model:OrderDetail;
//init the model
constructor(http: Http, orderService: OrderService, loginService: LoginService, router: Router, configService: ConfigService) {
this.toppings = new Toppings();
this.http = http;
this.loginService = loginService;
this.router = router;
this.orderService = orderService;
this.configService = configService;
this.model = new OrderDetail(
"0",
0,
'',
'',
'',
'',
'',
'',
[],
[]
);
}
updateCheckedOtherTopping(option, event) {
var index = this.model.otherToppings.indexOf(option);
if (event.target.checked) {
if (index === -1) {
this.model.otherToppings.push(option);
}
} else {
// console.log('remove');
if (index !== -1) {
this.model.otherToppings.splice(index, 1);
}
}
}
updateCheckedMeats(option, event) {
var index = this.model.meats.indexOf(option);
if (event.target.checked) {
if (index === -1) {
this.model.meats.push(option);
}
} else {
console.log('remove');
if (index !== -1) {
this.model.meats.splice(index, 1);
}
}
}
ngAfterViewInit() {
console.log('OrderComponent loginService.getUser()', this.loginService.getUser())
if (this.loginService.getUser() == null) {
this.router.navigate(['/landing']);
}
this.getToppings();
}
getToppings() {
this.http.get(this.configService.getBaseUrl() + '/toppings')
.map((res: Response) => res.json())
.subscribe(
data => {
this.toppings = data;
this.model.premadeName = this.orderService.getOrderDetail().premadeName;
this.model.size = this.orderService.getOrderDetail().size;
this.model.crustStyle = this.orderService.getOrderDetail().crustStyle;
this.model.baseSauce = this.orderService.getOrderDetail().baseSauce;
this.model.cheese = this.orderService.getOrderDetail().cheese;
this.model.otherToppings = this.orderService.getOrderDetail().otherToppings;
this.model.meats = this.orderService.getOrderDetail().meats;
},
err => console.error(err),
() => {
console.log('done1', this.toppings)
}
);
}
public navigateToCheckout() {
this.orderService.setOrderDetail(this.model);
this.router.navigate(['/checkout']);
}
// ngOnDestroy(){
// this.orderService.setOrderDetailToEmpty();
// }
}
|
# bash script to be sourced from fedora_setup.sh
# Copy .zshrc and offer to change default shell
Separate 4
printf "Successfully installed \e[36mzsh\e[00m, configuring...\n"
# Create .zshrc files
[ ! -f ~/.zshrc ] && cat "$script_location/samples/zshrc" | tee ~/.zshrc ~/.zshrc-og >/dev/null
sudo [ ! -f /root/.zshrc ] && cat "$script_location/samples/zshrc" | sudo tee /root/.zshrc /root/.zshrc-og >/dev/null
# Offer to install powerline-shell
read -rp "$(printf "Do you want to install \e[01mPowerline Shell\e[00m? (y/N) ")"
if [ ${REPLY,,} = "y" ]; then
printf "Installing \e[01mPowerline Shell\e[00m...\n"
sudo pip3 install powerline-shell &>/dev/null; O=$?
else
O=1
fi
if [ $O -eq 0 ]; then
mkdir -p ~/.config/powerline-shell
sudo mkdir -p /root/.config/powerline-shell
#region file
FILE='{
"segments": [
"virtual_env",
"username",
"hostname",
"ssh",
"cwd",
"git",
"hg",
"jobs",
"root"
],
"cwd": {
"max_depth": 3
}
}'
#endregion
printf "%s\n" "$FILE" | sudo tee /root/.config/powerline-shell/config.json | tee ~/.config/powerline-shell/config.json >/dev/null
unset FILE
fi
printf "Choose the prompt style you prefer: \n"
select s in $(cat "$HOME/.zshrc" | grep "# Choose a prompt style between" | sed -e 's/\s*#.*: //'); do
if [ $O -ne 0 ] && [ $s = "powerline" ]; then
printf "Sorry, powerline was not installed, choose another style\n"
continue
fi
sed -i "s/^ prompt_style=.*$/ prompt_style=$s/" ~/.zshrc
break
done
read -rp "Do you want to make `tput setaf 6`Z-Shell`tput sgr0` your default shell? (Y/n) "
if [[ ${REPLY,,} == "y" ]] || [ -z $REPLY ]; then
chsh -s $(which zsh)
sudo chsh -s $(which zsh)
fi
|
<reponame>ralberts/jsondata-backend
'use strict';
var _ = require('lodash');
/**
* Book.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = _.merge(_.cloneDeep(require('../base/Model')), {
attributes: {
title: {
type: 'string',
required: true
},
description: {
type: 'json',
defaultsTo: ''
},
releaseDate: {
type: 'date',
required: true
},
// Relationship
dataObject: {
model: 'dataObject'
}
}
});
|
#!/bin/bash
python3 scripts/init.py |
#!/bin/sh
node server.js |
<reponame>prinsmike/go-start<filename>view/textarea.go
package view
const (
TextAreaDefaultCols = 80
TextAreaDefaultRows = 3
)
///////////////////////////////////////////////////////////////////////////////
// TextArea
type TextArea struct {
ViewBaseWithId
Text string
Name string
Cols int
Rows int
Readonly bool
Disabled bool
TabIndex int
Class string
Placeholder string
Required bool // HTML5
Autofocus bool // HTML5
}
func (self *TextArea) Render(ctx *Context) (err error) {
ctx.Response.XML.OpenTag("textarea")
ctx.Response.XML.AttribIfNotDefault("id", self.id)
ctx.Response.XML.AttribIfNotDefault("class", self.Class)
cols := self.Cols
if cols == 0 {
cols = TextAreaDefaultCols
}
rows := self.Rows
if rows == 0 {
rows = TextAreaDefaultRows
}
ctx.Response.XML.Attrib("name", self.Name)
ctx.Response.XML.Attrib("rows", rows)
ctx.Response.XML.Attrib("cols", cols)
ctx.Response.XML.AttribIfNotDefault("tabindex", self.TabIndex)
ctx.Response.XML.AttribFlag("readonly", self.Readonly)
ctx.Response.XML.AttribFlag("disabled", self.Disabled)
ctx.Response.XML.AttribFlag("required", self.Required)
ctx.Response.XML.AttribFlag("autofocus", self.Autofocus)
ctx.Response.XML.AttribIfNotDefault("placeholder", self.Placeholder)
ctx.Response.XML.EscapeContent(self.Text)
ctx.Response.XML.CloseTagAlways()
return nil
}
//func (self *TextArea) SetText(text string) {
// self.Text = text
// ViewChanged(self)
//}
//
//func (self *TextArea) SetName(name string) {
// self.Name = name
// ViewChanged(self)
//}
//
//func (self *TextArea) SetCols(cols int) {
// self.Cols = cols
// ViewChanged(self)
//}
//
//func (self *TextArea) SetRows(rows int) {
// self.Rows = rows
// ViewChanged(self)
//}
//
//func (self *TextArea) SetReadonly(readonly bool) {
// self.Readonly = readonly
// ViewChanged(self)
//}
//
//func (self *TextArea) SetTabIndex(tabindex int) {
// self.TabIndex = tabindex
// ViewChanged(self)
//}
//
//func (self *TextArea) SetClass(class string) {
// self.Class = class
// ViewChanged(self)
//}
|
#!/bin/bash
######################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# SPDX-License-Identifier: MIT-0 #
######################################################################
source .env
export MODE=-it
echo ""
echo "Testing container ${CONTAINER} on ${TO} ..."
case ${TO} in
"lambda")
echo "Testing lambda function ${LAMBDA_FUNCTION_NAME} ..."
for t in $(ls ${LAMBDA_TEST_PATH}/test*.sh); do echo Running test $t; $t; done
;;
"compose")
if [ "${COMPOSE_CONTEXT_TYPE}" == "moby" ]; then
CONTAINER_INDEX=$1
if [ "$CONTAINER_INDEX" == "" ]; then
CONTAINER_INDEX=1
fi
docker exec ${MODE} ${COMPOSE_PROJECT_NAME}_${CONTAINER}_${CONTAINER_INDEX} sh -c "for t in \$(ls /test*.sh); do echo Running test \$t; \$t; done;"
elif [ "${COMPOSE_CONTEXT_TYPE}" == "ecs" ]; then
endpoint_host=$(./status.sh | grep ${CONTAINER} | grep Running | awk '{print $4}' | cut -d ':' -f 1)
endpoint="http://${endpoint_host}:${PORT_EXTERNAL}"
for t in $(ls ${COMPOSE_TEST_PATH}/test*.sh); do echo Running test $t; $t $endpoint; done
else
echo ""
echo "Unrecognized COMPOSE_CONTEXT_TYPE ${COMPOSE_CONTEXT_TYPE}"
echo "Supported context types: moby | ecs"
fi
;;
"ecs")
endpoint_host=$(./status.sh | grep ${CONTAINER} | grep RUNNING | awk '{print $3}' | cut -d ':' -f 1)
endpoint="http://${endpoint_host}:${PORT_EXTERNAL}"
for t in $(ls ${COMPOSE_TEST_PATH}/test*.sh); do echo Running test $t; $t $endpoint; done
;;
"kubernetes")
CONTAINER_INDEX=$1
if [ "$CONTAINER_INDEX" == "" ]; then
CONTAINER_INDEX=1
fi
unset DEBUG; ${KUBECTL} -n ${NAMESPACE} exec -it $( ${KUBECTL} -n ${NAMESPACE} get pod | grep ${APP_NAME} | head -n ${CONTAINER_INDEX} | tail -n 1 | cut -d ' ' -f 1 ) -- bash -c "for t in \$(ls /test*.sh); do echo Running test \$t; \$t; done"
;;
"batchlocal")
BATCH_COMMAND="cd /job; for t in \$(ls test*.sh); do echo Running test \$t; ./\$t; done"
echo "${BATCH_COMMAND}"
docker container run ${RUN_OPTS} ${CONTAINER_NAME} -d ${NETWORK} ${VOL_MAP} ${REGISTRY}${IMAGE}${TAG} bash -c "${BATCH_COMMAND}"
./logs.sh
./stop.sh
;;
"batch")
BATCH_COMMAND="cd /job; ./test1.sh; ./test2.sh"
./run.sh "[\"/bin/bash\",\"-c\",\"${BATCH_COMMAND}\"]"
;;
*)
docker exec ${MODE} ${CONTAINER} sh -c "for t in \$(ls /test*.sh); do echo Running test \$t; \$t; done;"
;;
esac
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('forum_conversation', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='post',
name='anonymous_key',
field=models.CharField(max_length=100, null=True, verbose_name='Anonymous user forum key', blank=True),
),
]
|
<filename>node_modules/vue-smooth-reflow/types/vue-smooth-reflow.d.ts<gh_stars>100-1000
import Vue from "vue"
import { ComponentOptions } from "vue/types/options"
export interface TransitionEvent {
selector?: string;
propertyName?: string;
}
export interface Options {
el?: Element | string;
property?: string | Array<string>;
transition?: string;
transitionEvent?: TransitionEvent;
hideOverflow?: boolean;
}
declare const mixin: ComponentOptions<Vue>;
export default mixin;
|
sudo apt update
sudo apt upgrade
sudo apt install -y \
git-core \
htop \
fortune-mod \
cowsay \
ddate \
python3-pip \
python-pip \
tmux \
libpq-dev \
python-dev \
bash-completion \
gnupg2 \
scdaemon \
direnv \
lolcat
sudo apt clean
pip install --user virtualenvwrapper
pip3 install --user ipython
sudo snap install mdless
|
<filename>src/main/java/com/github/bingoohuang/blackcat/agent/collectors/BlackcatNetstatCollector.java
package com.github.bingoohuang.blackcat.agent.collectors;
import com.github.bingoohuang.blackcat.sdk.protobuf.BlackcatMsg.BlackcatNetStat;
import com.github.bingoohuang.blackcat.sdk.protobuf.BlackcatMsg.BlackcatReq;
import com.github.bingoohuang.blackcat.sdk.protobuf.BlackcatMsg.BlackcatReqHead.ReqType;
import com.github.bingoohuang.blackcat.sdk.utils.Blackcats;
import com.google.common.base.Optional;
import lombok.SneakyThrows;
import lombok.val;
public class BlackcatNetstatCollector implements BlackcatCollector {
@Override @SneakyThrows
public Optional<BlackcatReq> collect() {
val sigar = SigarSingleton.SIGAR;
val netStat = sigar.getNetStat();
val builder = BlackcatNetStat.newBuilder();
builder.setAllInboundTotal(netStat.getAllInboundTotal())
.setAllOutboundTotal(netStat.getAllOutboundTotal())
.setTcpBound(netStat.getTcpBound())
.setTcpClose(netStat.getTcpClose())
.setTcpCloseWait(netStat.getTcpCloseWait())
.setTcpClosing(netStat.getTcpClosing())
.setTcpEstablished(netStat.getTcpEstablished())
.setTcpFinWait1(netStat.getTcpFinWait1())
.setTcpFinWait2(netStat.getTcpFinWait2())
.setTcpIdle(netStat.getTcpIdle())
.setTcpInboundTotal(netStat.getTcpInboundTotal())
.setTcpLastAck(netStat.getTcpLastAck())
.setTcpListen(netStat.getTcpListen())
.setTcpOutboundTotal(netStat.getTcpOutboundTotal())
.setTcpSynRecv(netStat.getTcpSynRecv())
.setTcpSynSent(netStat.getTcpSynSent())
.setTcpTimeWait(netStat.getTcpTimeWait());
val blackcatReq = BlackcatReq.newBuilder()
.setBlackcatReqHead(Blackcats.buildHead(ReqType.BlackcatNetStat))
.setBlackcatNetStat(builder).build();
return Optional.of(blackcatReq);
}
}
|
<reponame>ImportanceOfBeingErnest/networkx
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2019 by
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# All rights reserved.
# BSD license.
#
"""Group centrality measures."""
from itertools import combinations
import networkx as nx
__all__ = ['group_betweenness_centrality']
def group_betweenness_centrality(G, C, normalized=True, weight=None):
r"""Compute the group betweenness centrality for a group of nodes.
Group betweenness centrality of a group of nodes $C$ is the sum of the
fraction of all-pairs shortest paths that pass through any vertex in $C$
.. math::
c_B(C) =\sum_{s,t \in V-C; s<t} \frac{\sigma(s, t|C)}{\sigma(s, t)}
where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
shortest $(s, t)$-paths, and $\sigma(s, t|C)$ is the number of
those paths passing through some node in group $C$. Note that
$(s, t)$ are not members of the group ($V-C$ is the set of nodes
in $V$ that are not in $C$).
Parameters
----------
G : graph
A NetworkX graph.
C : list or set
C is a group of nodes which belong to G, for which group betweenness
centrality is to be calculated.
normalized : bool, optional
If True, group betweenness is normalized by `2/((|V|-|C|)(|V|-|C|-1))`
for graphs and `1/((|V|-|C|)(|V|-|C|-1))` for directed graphs where `|V|`
is the number of nodes in G and `|C|` is the number of nodes in C.
weight : None or string, optional (default=None)
If None, all edge weights are considered equal.
Otherwise holds the name of the edge attribute used as weight.
Returns
-------
betweenness : float
Group betweenness centrality of the group C.
See Also
--------
betweenness_centrality
Notes
-----
The measure is described in [1]_.
The algorithm is an extension of the one proposed by <NAME> for
betweenness centrality of nodes. Group betweenness is also mentioned in
his paper [2]_ along with the algorithm. The importance of the measure is
discussed in [3]_.
The number of nodes in the group must be a maximum of n - 2 where `n`
is the total number of nodes in the graph.
For weighted graphs the edge weights must be greater than zero.
Zero edge weights can produce an infinite number of equal length
paths between pairs of nodes.
References
----------
.. [1] <NAME> and <NAME>:
The Centrality of Groups and Classes.
Journal of Mathematical Sociology. 23(3): 181-201. 1999.
http://www.analytictech.com/borgatti/group_centrality.htm
.. [2] <NAME>:
On Variants of Shortest-Path Betweenness
Centrality and their Generic Computation.
Social Networks 30(2):136-145, 2008.
http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf
.. [3] <NAME>. al.:
Group Centrality Maximization via Network Design.
SIAM International Conference on Data Mining, SDM 2018, 126–134.
https://sites.cs.ucsb.edu/~arlei/pubs/sdm18.pdf
"""
betweenness = 0 # initialize betweenness to 0
V = set(G.nodes()) # set of nodes in G
C = set(C) # set of nodes in C (group)
V_C = set(V - C) # set of nodes in V but not in C
# accumulation
for pair in combinations(V_C, 2): # (s, t) pairs of V_C
try:
paths = 0
paths_through_C = 0
for path in nx.all_shortest_paths(G, source=pair[0],
target=pair[1], weight=weight):
if set(path) & C:
paths_through_C += 1
paths += 1
betweenness += paths_through_C / paths
except nx.exception.NetworkXNoPath:
betweenness += 0
# rescaling
v, c = len(G), len(C)
if normalized:
scale = 1 / ((v - c) * (v - c - 1))
if not G.is_directed():
scale *= 2
else:
scale = None
if scale is not None:
betweenness *= scale
return betweenness
|
#!/bin/bash
curl -sc /tmp/cookie "https://drive.google.com/uc?export=download&id=1Scu-3Kdz36iIlaBvqJ3sOTLCvzxM71RI" > /dev/null
CODE="$(awk '/_warning_/ {print $NF}' /tmp/cookie)"
curl -Lb /tmp/cookie "https://drive.google.com/uc?export=download&confirm=${CODE}&id=1Scu-3Kdz36iIlaBvqJ3sOTLCvzxM71RI" -o mobilenet_v3_large_224_dm07_full_integer_quant.tflite
echo Download finished.
|
<reponame>navikt/sykepengesoknad<filename>js/utils/sykmeldingUtils.js
export const getTidligsteStartdatoSykeforloep = (sykepengesoknad) => {
return sykepengesoknad.oppfoelgingsdato && sykepengesoknad.oppfoelgingsdato < sykepengesoknad.identdato
? sykepengesoknad.oppfoelgingsdato
: sykepengesoknad.identdato;
};
|
<filename>zgo/zgo.go
// Package zgo provides functions to work with Go source files.
package zgo
import (
"fmt"
"go/ast"
"os"
"path/filepath"
"reflect"
"strings"
)
// ModuleRoot gets the full path to the module root directory.
//
// Returns empty string if it can't find a module.
func ModuleRoot() string {
dir, err := os.Getwd()
if err != nil {
return ""
}
dir, err = filepath.Abs(dir)
if err != nil {
return ""
}
pdir := dir
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir
}
pdir = dir
dir = filepath.Dir(dir)
if dir == pdir {
break
}
}
return ""
}
// Tag gets the tag name for a struct field and all attributes.
//
// It will return the struct field name if there is no tag. This function does
// not do any validation on the tag format. Use go vet!
func Tag(f *ast.Field, n string) (string, []string) {
// For e.g.:
// A, B string `json:"x"`
//
// Most (all?) marshallers and such will simply skip this anyway as
// duplicate keys usually doesn't make too much sense.
if len(f.Names) > 1 {
panic(fmt.Sprintf("cannot use TagName on struct with more than one name: %v",
f.Names))
}
if f.Tag == nil {
if len(f.Names) == 0 {
return getEmbedName(f.Type), nil
}
return f.Names[0].Name, nil
}
tag := reflect.StructTag(strings.Trim(f.Tag.Value, "`")).Get(n)
if tag == "" {
if len(f.Names) == 0 {
return getEmbedName(f.Type), nil
}
return f.Names[0].Name, nil
}
if p := strings.Index(tag, ","); p != -1 {
return tag[:p], strings.Split(tag[p+1:], ",")
}
return tag, nil
}
// TagName gets the tag name for a struct field without any attributes.
//
// It will return the struct field name if there is no tag. This function does
// not do any validation on the tag format. Use go vet!
func TagName(f *ast.Field, n string) string {
name, _ := Tag(f, n)
return name
}
// StarExpr resolves *ast.StarExpr
func StarExpr(e ast.Expr) (ast.Expr, bool) {
s, ok := e.(*ast.StarExpr)
if ok {
return s.X, true
}
return e, false
}
// Embedded struct:
// Foo `json:"foo"`
func getEmbedName(f ast.Expr) string {
start:
switch t := f.(type) {
case *ast.StarExpr:
f = t.X
goto start
case *ast.Ident:
return t.Name
case *ast.SelectorExpr:
return t.Sel.Name
default:
panic(fmt.Sprintf("can't get name for %#v", f))
}
}
// PredeclaredType reports if a type is a predeclared built-in type.
//
// Note that this excludes composite types, such as maps, slices, channels, etc.
//
// https://golang.org/ref/spec#Predeclared_identifiers
func PredeclaredType(n string) bool {
switch n {
case "bool", "byte", "complex64", "complex128", "error", "float32",
"float64", "int", "int8", "int16", "int32", "int64", "rune", "string",
"uint", "uint8", "uint16", "uint32", "uint64", "uintptr":
return true
default:
return false
}
}
|
import { DBOpts } from "./interface";
declare class Collection {
name: any;
storage: any;
cache: any[];
path: string;
cacheable: boolean;
primaryKey: any;
constructor(db: any, name: string, opts: DBOpts);
_initCache(): void;
_filter(filter: any | null, opts: {
type: any;
multi: any;
}): any;
inset(data: any, opts?: any): any;
/**
*
* find('')
* find(['', ''])
*
*/
find(query?: any, opts?: {
skip?: any;
limit?: any;
sort?: any;
_filterType?: string;
}): any;
findOne(query: any, opts?: {
skip?: any;
limit?: any;
sort?: any;
_filterType?: any;
} | undefined): any;
remove(query: {}, opts?: {
multi?: any;
mulit?: any;
} | undefined): number;
update(query: any, values: {
[x: string]: any;
}, opts?: {
multi?: any;
mulit?: any;
_filterType?: string;
}): any;
drop(): boolean;
count(): any;
}
declare class StorageDB {
storage: Storage | null;
database: string;
primaryKey?: string;
sep?: string;
constructor(opts: DBOpts);
get(name: string, opts?: DBOpts): Collection;
collection(name: string, opts?: DBOpts): Collection;
size(): number;
}
export default StorageDB;
|
cd accessibility-checker-engine
npm install
npm run build
cd ..
cd accessibility-checker
npm install
npx mocha -R dot test/mocha/aChecker.Fast/**/*.test.js
|
const mineflayer = require('mineflayer');
const Vec3 = require('vec3');
const { GoalNear } = require('../plugins/pathfinder/index').goals;
const { logError } = require('../utils');
class AutoSleep {
/**
*
* @param {mineflayer.Bot} bot
*/
constructor(bot) {
this.bot = bot;
this.myBed = null;
this.enable = true;
this.prefix = 'sleep';
}
init() {
this.bot.on('time', () => {
if (this.bot.pathfinder && this.bot.pathfinder.isMoving()) return;
if (this.myBed === null) return;
if (this.bot.isSleeping) return;
if (this.bot.time.isDay) return;
if (!this.enable) return;
this.doSleep();
});
}
readMemory(data) {
this.enable = data.enable;
this.myBed = data.myBed;
}
writeMemory() {
return { myBed: this.myBed, enable: this.enable };
}
async chat(args, target) {
if (args.length === 0) {
if (this.bot.time.isDay) {
this.bot.chat('not time to sleep');
} else {
await this.doSleep();
}
}
if (args[0] === 'bed' && args.length === 4) {
this.myBed = Vec3(args[1], args[2], args[3]);
}
if (args[0] === 'on') {
this.enable = true;
}
if (args[0] === 'off') {
this.enable = false;
}
}
async doSleep() {
if (this.myBed === null) {
this.bot.chat('no bed for me');
this.enable = false;
return false;
}
if (this.bot.isSleeping) {
this.bot.chat('sleeping now');
return false;
}
await this.bot.pathfinder.goto(
new GoalNear(this.myBed.x, this.myBed.y, this.myBed.z, 2),
);
const bedBlock = this.bot.blockAt(this.myBed);
if (!bedBlock.name.endsWith('_bed')) {
this.bot.chat('my bed lost');
this.myBed = null;
return false;
}
try {
this.bot.sleep(bedBlock);
} catch (error) {
logError(error);
return false;
}
return true;
}
}
module.exports = AutoSleep;
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { Panel } from 'react-bootstrap';
import { connect } from 'react-redux';
import { set404 } from 'redux/modules/controls';
import SetStatus from 'components/SetStatus';
class HttpStatus extends PureComponent {
static propTypes = {
children: PropTypes.node,
dispatch: PropTypes.func,
status: PropTypes.number
};
static defaultProps = {
status: 404,
};
componentWillMount() {
this.props.dispatch(set404(true));
}
componentWillUnmount() {
this.props.dispatch(set404(false));
}
render() {
const { children, status } = this.props;
return (
<SetStatus code={status}>
<Helmet>
<title>There's been an error</title>
</Helmet>
<Panel bsStyle="danger" className="wr-error-notice">
<Panel.Heading>There's been an error</Panel.Heading>
<Panel.Body>
{ children || 'No such page or content is not accessible.'}
</Panel.Body>
</Panel>
</SetStatus>
);
}
}
export default connect()(HttpStatus);
|
#!/usr/bin/env bash
#grep "done.*EOM.*./0/" fnode0_processlist.txt | ./minutelength.sh
################################
# AWK scripts #
################################
read -d '' scriptVariable << 'EOF'
func time2sec(t) {
x = split(t,ary,":");
if(x!=3) {printf("time2sec(%s) bad split got %d fields. <%d>", t , x ,NR); print $0; exit;}
sec = (ary[1]*60+ary[2])*60+ary[3];
#printf("time2sec(%s) %02d:%02d:%02g= %d\\n",t, ary[1]+0, ary[2]+0,ary[3]+0,sec);
return sec;
}
{ sub(/\\(standard input\\):/,"");
#sub(/:/," ");
fname = $1;
if(NR%1000==0) {printf("\\r%7d",NR)>"/dev/stderr";}
}
NR == 1 {prev = time2sec($2);}
{ now = time2sec($2);
delay = now-prev;
gap[delay]++;
gapsrc[delay] = $0;
printf("%7.2f %s\\n", delay, $0);
prev = now;
}
END {
PROCINFO["sorted_in"] ="@ind_num_desc";
print "Gaps in log"
for(i in gap) {
printf("%7.2f %4d %s\\n", i, gap[i], gapsrc[i]);
if(j++>10) {break;}
}
}
EOF
################################
# End of AWK Scripts #
################################
awk "$scriptVariable"
|
#!/bin/bash
# get schema registry API key and secret
jq '.contexts[].schema_registry_clusters[].schema_registry_credentials' ~/.ccloud/config.json
|
<filename>src/components/breakpoint.js
import { useState, useEffect } from 'react';
import throttle from 'lodash.throttle';
const getDeviceConfig = (width) => {
if (width < 600 ){
return 'mobile';
}
else {
return 'large';
};
};
const useBreakpoint = () => {
const [brkPnt, setBrkpnt] = useState(() => getDeviceConfig(window.innerWidth));
useEffect(() => {
const calcInnerWidth = throttle(function() {
setBrkpnt(getDeviceConfig(window.innerWidth))
}, 200);
window.addEventListener('resize', calcInnerWidth);
return() => window.removeEventListener('resize', calcInnerWidth);
}, []);
return brkPnt;
}
export default useBreakpoint |
def manage_meta_tags_cache(enabled: bool, reset: bool) -> str:
if enabled:
if reset:
return 'Meta tags cache has been successfully reset.'
else:
return 'Meta tags caching is enabled.'
else:
return 'Meta tags caching is not enabled.' |
package io.opensphere.arcgis2.model;
import java.util.List;
import org.codehaus.jackson.annotate.JsonProperty;
/** Tile info. */
public class TileInfo
{
/** The cols. */
@JsonProperty("cols")
private int myCols;
/** The lods. */
@JsonProperty("lods")
private List<LevelOfDetail> myLods;
/** The origin. */
@JsonProperty("origin")
private XYVector myOrigin;
/** The rows. */
@JsonProperty("rows")
private int myRows;
/**
* Get the cols.
*
* @return The cols.
*/
public int getCols()
{
return myCols;
}
/**
* Gets the lods.
*
* @return The lods.
*/
public List<LevelOfDetail> getLods()
{
return myLods;
}
/**
* Get the origin.
*
* @return The origin.
*/
public XYVector getOrigin()
{
return myOrigin;
}
/**
* Get the rows.
*
* @return The rows.
*/
public int getRows()
{
return myRows;
}
/**
* Set the cols.
*
* @param cols The cols.
*/
public void setCols(int cols)
{
myCols = cols;
}
/**
* Sets the lods.
*
* @param lods The lods.
*/
public void setLods(List<LevelOfDetail> lods)
{
myLods = lods;
}
/**
* Set the origin.
*
* @param origin The origin.
*/
public void setOrigin(XYVector origin)
{
myOrigin = origin;
}
/**
* Set the rows.
*
* @param rows The rows.
*/
public void setRows(int rows)
{
myRows = rows;
}
}
|
#!/bin/bash
MYSELF=/usr/bin/mk_newpart.sh
DEV=mmcblk0
TOTAL_SIZE=$(lsblk -l -b -I 179 -o NAME,MAJ:MIN,SIZE | grep "179:0" | awk '{print $3}')
TARGET_ROOTFS2_FSTYPE=btrfs
TARGET_SHARED_FSTYPE=btrfs
SKIP_MB=$(awk '{print $1}' /etc/part_size)
BOOT_MB=$(awk '{print $2}' /etc/part_size)
ROOTFS_MB=$(awk '{print $3}' /etc/part_size)
START_P3=$(( (SKIP_MB + BOOT_MB + ROOTFS_MB) * 2048 ))
END_P3=$((ROOTFS_MB * 2048 + START_P3 -1))
START_P4=$((END_P3 + 1))
END_P4=$((TOTAL_SIZE / 512 - 1))
cat > /tmp/fdisk.script <<EOF
n
p
3
$START_P3
$END_P3
n
p
$START_P4
$END_P4
t
3
83
t
4
83
w
EOF
fdisk /dev/$DEV < /tmp/fdisk.script
if [ $? -ne 0 ];then
echo "fdisk failed, restore the backup bootloader, and abort"
sync
exit 1
fi
echo "fdisk done"
echo
# mkfs
echo "create rootfs2 filesystem ... "
case $TARGET_ROOTFS2_FSTYPE in
xfs) mkfs.xfs -f -L EMMC_ROOTFS2 /dev/${DEV}p3;;
btrfs) mkfs.btrfs -f -L EMMC_ROOTFS2 /dev/${DEV}p3;;
*) mkfs.ext4 -F -L EMMC_ROOTFS2 /dev/${DEV}p3;;
esac
echo "done"
echo "create shared filesystem ... "
mkdir -p /mnt/${DEV}p4
case $TARGET_SHARED_FSTYPE in
xfs) mkfs.xfs -f -L EMMC_SHARED /dev/${DEV}p4
mount -t xfs /dev/${DEV}p4 /mnt/${DEV}p4
;;
btrfs) mkfs.btrfs -f -L EMMC_SHARED /dev/${DEV}p4
mount -t btrfs /dev/${DEV}p4 /mnt/${DEV}p4
;;
*) mkfs.ext4 -F -L EMMC_SHARED /dev/${DEV}p4
mount -t ext4 /dev/${DEV}p4 /mnt/${DEV}p4
;;
esac
mkdir -p /mnt/${DEV}p4/docker
rm -rf /opt/docker
ln -sf /mnt/mmcblk0p4/docker/ /opt/docker
/etc/init.d/dockerd restart
if [ -f /etc/config/AdGuardHome ];then
mkdir -p /mnt/${DEV}p4/AdGuardHome/data
rm -rf /usr/bin/AdGuardHome
ln -sf /mnt/${DEV}p4/AdGuardHome /usr/bin/AdGuardHome
fi
sync
echo "done"
rm -f $MYSELF /etc/part_size /tmp/fdisk.script
mv -f /etc/rc.local.orig /etc/rc.local
|
import { createSlice } from "@reduxjs/toolkit";
import { Itinerary } from 'types/models';
interface State {
value: Itinerary | null;
}
interface Action {
payload: any;
}
interface SliceReducers {
[x: string]: (state: State, action: Action) => void;
}
export const itinerary = createSlice<State, SliceReducers, "itinerary">({
name: "itinerary",
initialState: {
value: null,
},
reducers: {
setItinerary: (state: State, action: Action) => {
if (action?.payload) {
state.value = action.payload;
}
}
},
});
export const { setItinerary } = itinerary.actions;
export default itinerary.reducer;
|
package hello.world;
import org.camunda.bpm.engine.RuntimeService;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* The core Spring Application configuration.
*/
@SpringBootApplication
public class AppConfig {
/**
* Bean creation method for the helloWorld service task.
*
* @param runtimeService the Camunda runtime service handle
* @return the helloWorld service task bean
*/
@Bean
HelloWorldTask helloWorldTask(final RuntimeService runtimeService) {
return new HelloWorldTask(runtimeService);
}
}
|
import { Response } from 'express';
/**
* @description 返回格式的统一处理
* @type {T} 返回数据的 type 类型
*/
export function genHttpData(resultCode, resultMessage, data) {
return {
resultCode,
resultMessage,
data,
};
}
/**
* @description 返回格式的统一处理
* @type {T} 返回数据的 type 类型
*/
export function httpResponse<T>(
res: Response,
data: T = null,
taskCode = 0,
message = '请求成功',
statusCode = 200,
) {
return res.status(statusCode).json(genHttpData(taskCode, message, data));
}
|
TERMUX_PKG_HOMEPAGE=https://www.rust-lang.org
TERMUX_PKG_DESCRIPTION="Rust compiler and utilities (nightly version)"
TERMUX_PKG_DEPENDS="libc++, clang, openssl, lld, zlib, libllvm"
TERMUX_PKG_LICENSE="MIT"
TERMUX_PKG_MAINTAINER="@its-pointless"
TERMUX_PKG_VERSION=1.41.0
TERMUX_PKG_REVISION=1
TERMUX_PKG_SRCURL=https://static.rust-lang.org/dist/2019-12-17/rustc-nightly-src.tar.xz
TERMUX_PKG_SHA256=1a22149617e3be27570f25354c41d79683e9450db6d529855bd41d0be3e766cb
#TERMUX_PKG_CONFLICTS="rust-rls-nightly, rust-docs-nightly, rustfmt-nightly"
#TERMUX_PKG_REPLACES="rust-rls-nightly, rust-docs-nightly, rustfmt-nightly"
TERMUX_PKG_CONFLICTS=rustc-dev-nightly
TERMUX_PKG_REPLACES=rustc-dev-nightly
TERMUX_PKG_KEEP_SHARE_DOC=true
termux_step_configure () {
termux_setup_cmake
termux_setup_rust
# nightlys don't build with stable
rustup install beta-2019-12-15-x86_64-unknown-linux-gnu
rustup default beta-2019-12-15-x86_64-unknown-linux-gnu
rustup component add rustc-dev
rustup target add $CARGO_TARGET_NAME
export PATH=$HOME/.rustup/toolchains/beta-2019-12-15-x86_64-unknown-linux-gnu/bin:$PATH
export RUST_BACKTRACE=1
mkdir -p $TERMUX_PREFIX/opt/rust-nightly
RUST_PREFIX=$TERMUX_PREFIX/opt/rust-nightly
export PATH=$TERMUX_PKG_TMPDIR/bin:$PATH
sed $TERMUX_PKG_BUILDER_DIR/config.toml \
-e "s|@RUST_PREFIX@|$RUST_PREFIX|g" \
-e "s|@TERMUX_PREFIX@|$TERMUX_PREFIX|g" \
-e "s|@TERMUX_HOST_PLATFORM@|$TERMUX_HOST_PLATFORM|g" \
-e "s|@RUST_TARGET_TRIPLE@|$CARGO_TARGET_NAME|g" \
-e "s|@CARGO@|$(which cargo)|g" \
-e "s|@RUSTC@|$(which rustc)|g" > $TERMUX_PKG_BUILDDIR/config.toml
export X86_64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu
export X86_64_UNKNOWN_LINUX_GNU_OPENSSL_INCLUDE_DIR=/usr/include
export PKG_CONFIG_ALLOW_CROSS=1
# for backtrace-sys
export CC_x86_64_unknown_linux_gnu=gcc
export CFLAGS_x86_64_unknown_linux_gnu="-O2"
# havent checked if this is needed...
sed -i 's/$LDFLAGS/@LDFLAGS@/g' $PREFIX/bin/llvm-config
sed -ie "s|@LDFLAGS@|$LDFLAGS|g" $PREFIX/bin/llvm-config
# it won't link with it in TERMUX_PREFIX/lib without breaking other things.
cp $PREFIX/lib/libLLVM-9.0.0.so $TERMUX_STANDALONE_TOOLCHAIN/sysroot/usr/lib/$TERMUX_HOST_PLATFORM/$TERMUX_PKG_API_LEVEL/
unset CC CXX CPP LD CFLAGS CXXFLAGS CPPFLAGS LDFLAGS PKG_CONFIG AR RANLIB
if [ $TERMUX_ARCH = "x86_64" ]; then
cp $TERMUX_STANDALONE_TOOLCHAIN/sysroot/usr/lib/x86_64-linux-android/$TERMUX_PKG_API_LEVEL/libc.so $TERMUX_PREFIX/lib/
cp $TERMUX_STANDALONE_TOOLCHAIN/sysroot/usr/lib/x86_64-linux-android/$TERMUX_PKG_API_LEVEL/libdl.so $TERMUX_PREFIX/lib/
mv $TERMUX_PREFIX/lib/libtinfo.so.6 $TERMUX_PREFIX/lib/libtinfo.so.6.tmp
fi
}
termux_step_make_install () {
../src/x.py dist --host $CARGO_TARGET_NAME --target $CARGO_TARGET_NAME --target wasm32-unknown-unknown || zsh
mkdir $TERMUX_PKG_BUILDDIR/install
# g
for tar in rustc-nightly rustc-dev-nightly rust-docs-nightly rust-std-nightly rust-analysis-nightly cargo-nightly rls-nightly miri-nightly rustc-dev-nightly rustfmt-nightly clippy-nightly; do
tar -xf $TERMUX_PKG_BUILDDIR/build/dist/$tar-$CARGO_TARGET_NAME.tar.gz -C $TERMUX_PKG_BUILDDIR/install
# uninstall previous version
$TERMUX_PKG_BUILDDIR/install/$tar-$CARGO_TARGET_NAME/install.sh --uninstall --prefix=$RUST_PREFIX || true
$TERMUX_PKG_BUILDDIR/install/$tar-$CARGO_TARGET_NAME/install.sh --prefix=$RUST_PREFIX
done
tar -xf $TERMUX_PKG_BUILDDIR/build/dist/rust-src-nightly.tar.gz -C $TERMUX_PKG_BUILDDIR/install
$TERMUX_PKG_BUILDDIR/install/rust-src-nightly/install.sh --uninstall --prefix=$RUST_PREFIX || true
$TERMUX_PKG_BUILDDIR/install/rust-src-nightly/install.sh --prefix=$RUST_PREFIX
WASM=wasm32-unknown-unknown
for tar in rust-std-nightly rust-analysis-nightly; do
tar -xf $TERMUX_PKG_BUILDDIR/build/dist/$tar-$WASM.tar.gz -C $TERMUX_PKG_BUILDDIR/install
# uninstall previous version
$TERMUX_PKG_BUILDDIR/install/$tar-$WASM/install.sh --uninstall --prefix=$RUST_PREFIX || true
$TERMUX_PKG_BUILDDIR/install/$tar-$WASM/install.sh --prefix=$RUST_PREFIX
done
if [ $TERMUX_ARCH = "x86_64" ]; then
rm -f $TERMUX_PREFIX/lib/libc.so $TERMUX_PREFIX/lib/libdl.so
mv $TERMUX_PREFIX/lib/libtinfo.so.6.tmp $TERMUX_PREFIX/lib/libtinfo.so.6
fi
rm $TERMUX_STANDALONE_TOOLCHAIN/sysroot/usr/lib/$TERMUX_HOST_PLATFORM/$TERMUX_PKG_API_LEVEL/libLLVM-9.0.0.so
rm $PREFIX/bin/llvm-config
}
termux_step_post_massage () {
rm $TERMUX_PKG_MASSAGEDIR/$RUST_PREFIX/lib/rustlib/{components,rust-installer-version,install.log,uninstall.sh}
mkdir -p $TERMUX_PKG_MASSAGEDIR/$TERMUX_PREFIX/etc/profile.d
mkdir -p $TERMUX_PKG_MASSAGEDIR/$TERMUX_PREFIX/lib
echo "#!$TERMUX_PREFIX/bin/sh" > $TERMUX_PKG_MASSAGEDIR/$TERMUX_PREFIX/etc/profile.d/rust-nightly.sh
echo "export PATH=$RUST_PREFIX/bin:\$PATH" >> $TERMUX_PKG_MASSAGEDIR/$TERMUX_PREFIX/etc/profile.d/rust-nightly.sh
cd $TERMUX_PKG_MASSAGEDIR/$RUST_PREFIX/lib
ln -sf rustlib/$CARGO_TARGET_NAME/lib/lib*.so .
cd $TERMUX_PKG_MASSAGEDIR/$TERMUX_PREFIX/lib
ln -sf ../opt/rust-nightly/lib/lib*.so .
ln -sf $TERMUX_PREFIX/bin/lld $TERMUX_PKG_MASSAGEDIR$RUST_PREFIX/bin/rust-lld
}
termux_step_create_debscripts () {
#echo "Provides: rustc" >> control
echo "#!$TERMUX_PREFIX/bin/sh" > postinst
echo "echo 'source \$PREFIX/etc/profile.d/rust-nightly.sh to use nightly'" >> postinst
echo "echo 'or export RUSTC=\$PREFIX/opt/rust-nightly/bin/rustc'" >> postinst
}
|
#!/bin/bash
source $HOME/zcmd/devutils/default-docker-env.txt
S3_URL="${SHARED_S3_ASSETS_BUCKET}"
if [ ! $# -eq 2 ]; then
echo "$0 SOURCE_OBJECT_KEY DESTINATION_FILEPATH"
echo "NOTE: BUCKET=$S3_URL"
exit 1
fi
KEY=$1
LOCALNAME=$2
CMD="aws s3 cp ${S3_URL}/${KEY} ${LOCALNAME}"
echo "COPY COMMAND: $CMD"
eval "$CMD"
|
#!/bin/sh
#Modify path to TETware folder on target
export TET_INSTALL_PATH=/path/to/TETware
if [ ! -d "$TET_INSTALL_PATH" ]; then
echo "TET_INSTALL_PATH = $TET_INSTALL_PATH doesn't exist"
echo "Modify this script execute.sh with tetware directory"
exit
fi
export TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-target
export PATH=$TET_TARGET_PATH/bin:$PATH
export LD_LIBRARY_PATH=$TET_TARGET_PATH/lib/tet3:$LD_LIBRARY_PATH
export TET_ROOT=$TET_TARGET_PATH
export TET_SUITE_ROOT=`pwd`
#FILE_NAME_EXTENSION=`date +%s`
RESULT_DIR=results
#HTML_RESULT=$RESULT_DIR/exec-tar-result-$FILE_NAME_EXTENSION.html
#JOURNAL_RESULT=$RESULT_DIR/exec-tar-result-$FILE_NAME_EXTENSION.journal
DATE=$(date +'%Y.%m.%d_%H.%M')
HTML_RESULT=$RESULT_DIR/drm_tc_execute_result_$DATE.html
JOURNAL_RESULT=$RESULT_DIR/drm_tc_execute_result_$DATE.journal
mkdir -p $RESULT_DIR
tcc -e -j $JOURNAL_RESULT -p ./
# Log Levels
# LOG_LEVEL=3 prints only tet_infoline
# LOG_LEVEL=7 prints only tet_infoline & tet_printf
LOG_LEVEL=7
grw -c $LOG_LEVEL -f chtml -o $HTML_RESULT $JOURNAL_RESULT
# Copy the results outside drm-client
echo "Copy the results outside drm-client & in folder drm_tc_results_client"
mkdir -p ../../drm_tc_results_client
cp $RESULT_DIR/drm_tc_execute_result_$DATE.html ../../drm_tc_results_client/
|
<gh_stars>1-10
package com.redislabs.lettusearch;
import static io.lettuce.core.LettuceStrings.isEmpty;
import static io.lettuce.core.LettuceStrings.isNotEmpty;
import java.net.SocketAddress;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import com.redislabs.lettusearch.impl.StatefulRediSearchConnectionImpl;
import com.redislabs.lettusearch.impl.StatefulRediSearchSentinelConnectionImpl;
import com.redislabs.lettusearch.sentinel.api.StatefulRediSearchSentinelConnection;
import io.lettuce.core.AbstractRedisClient;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.ConnectionBuilder;
import io.lettuce.core.ConnectionFuture;
import io.lettuce.core.LettuceStrings;
import io.lettuce.core.RedisChannelWriter;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisConnectionException;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SslConnectionBuilder;
import io.lettuce.core.codec.RedisCodec;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.internal.Futures;
import io.lettuce.core.internal.LettuceAssert;
import io.lettuce.core.output.StatusOutput;
import io.lettuce.core.protocol.CommandArgs;
import io.lettuce.core.protocol.CommandExpiryWriter;
import io.lettuce.core.protocol.CommandHandler;
import io.lettuce.core.protocol.CommandType;
import io.lettuce.core.protocol.DefaultEndpoint;
import io.lettuce.core.protocol.Endpoint;
import io.lettuce.core.resource.ClientResources;
import reactor.core.publisher.Mono;
public class RediSearchClient extends AbstractRedisClient {
private static final RedisURI EMPTY_URI = new RedisURI();
private final RedisURI redisURI;
protected RediSearchClient(ClientResources clientResources, RedisURI redisURI) {
super(clientResources);
assertNotNull(redisURI);
this.redisURI = redisURI;
setDefaultTimeout(redisURI.getTimeout());
}
protected RediSearchClient() {
this(null, EMPTY_URI);
}
public static RediSearchClient create() {
return new RediSearchClient(null, EMPTY_URI);
}
public static RediSearchClient create(RedisURI redisURI) {
assertNotNull(redisURI);
return new RediSearchClient(null, redisURI);
}
public static RediSearchClient create(String uri) {
LettuceAssert.notEmpty(uri, "URI must not be empty");
return new RediSearchClient(null, RedisURI.create(uri));
}
public static RediSearchClient create(ClientResources clientResources) {
assertNotNull(clientResources);
return new RediSearchClient(clientResources, EMPTY_URI);
}
public static RediSearchClient create(ClientResources clientResources, String uri) {
assertNotNull(clientResources);
LettuceAssert.notEmpty(uri, "URI must not be empty");
return create(clientResources, RedisURI.create(uri));
}
public static RediSearchClient create(ClientResources clientResources, RedisURI redisURI) {
assertNotNull(clientResources);
assertNotNull(redisURI);
return new RediSearchClient(clientResources, redisURI);
}
public StatefulRediSearchConnection<String, String> connect() {
return connect(newStringStringCodec());
}
public <K, V> StatefulRediSearchConnection<K, V> connect(RedisCodec<K, V> codec) {
checkForRedisURI();
return getConnection(connectStandaloneAsync(codec, this.redisURI, timeout));
}
public StatefulRediSearchConnection<String, String> connect(RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectStandaloneAsync(newStringStringCodec(), redisURI, redisURI.getTimeout()));
}
public <K, V> StatefulRediSearchConnection<K, V> connect(RedisCodec<K, V> codec, RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectStandaloneAsync(codec, redisURI, redisURI.getTimeout()));
}
public <K, V> ConnectionFuture<StatefulRediSearchConnection<K, V>> connectAsync(RedisCodec<K, V> codec,
RedisURI redisURI) {
assertNotNull(redisURI);
return transformAsyncConnectionException(connectStandaloneAsync(codec, redisURI, redisURI.getTimeout()));
}
private <K, V> ConnectionFuture<StatefulRediSearchConnection<K, V>> connectStandaloneAsync(RedisCodec<K, V> codec,
RedisURI redisURI, Duration timeout) {
assertNotNull(codec);
checkValidRedisURI(redisURI);
logger.debug("Trying to get a Redis connection for: " + redisURI);
DefaultEndpoint endpoint = new DefaultEndpoint(clientOptions, clientResources);
RedisChannelWriter writer = endpoint;
if (CommandExpiryWriter.isSupported(clientOptions)) {
writer = new CommandExpiryWriter(writer, clientOptions, clientResources);
}
StatefulRediSearchConnectionImpl<K, V> connection = newStatefulRedisConnection(writer, codec, timeout);
ConnectionFuture<StatefulRediSearchConnection<K, V>> future = connectStatefulAsync(connection, codec, endpoint,
redisURI, () -> new CommandHandler(clientOptions, clientResources, endpoint));
future.whenComplete((channelHandler, throwable) -> {
if (throwable != null) {
connection.close();
}
});
return future;
}
@SuppressWarnings("unchecked")
private <K, V, S> ConnectionFuture<S> connectStatefulAsync(StatefulRediSearchConnectionImpl<K, V> connection,
RedisCodec<K, V> codec, Endpoint endpoint, RedisURI redisURI,
Supplier<CommandHandler> commandHandlerSupplier) {
ConnectionBuilder connectionBuilder;
if (redisURI.isSsl()) {
SslConnectionBuilder sslConnectionBuilder = SslConnectionBuilder.sslConnectionBuilder();
sslConnectionBuilder.ssl(redisURI);
connectionBuilder = sslConnectionBuilder;
} else {
connectionBuilder = ConnectionBuilder.connectionBuilder();
}
connectionBuilder.connection(connection);
connectionBuilder.clientOptions(clientOptions);
connectionBuilder.clientResources(clientResources);
connectionBuilder.commandHandler(commandHandlerSupplier).endpoint(endpoint);
connectionBuilder(getSocketAddressSupplier(redisURI), connectionBuilder, redisURI);
channelType(connectionBuilder, redisURI);
if (clientOptions.isPingBeforeActivateConnection()) {
if (hasPassword(redisURI)) {
connectionBuilder.enableAuthPingBeforeConnect();
} else {
connectionBuilder.enablePingBeforeConnect();
}
}
ConnectionFuture<?> sync = initializeChannelAsync(connectionBuilder);
if (!clientOptions.isPingBeforeActivateConnection() && hasPassword(redisURI)) {
sync = sync.thenCompose(channelHandler -> {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(redisURI.getPassword());
return connection.async().dispatch(CommandType.AUTH, new StatusOutput<>(codec), args);
});
}
if (LettuceStrings.isNotEmpty(redisURI.getClientName())) {
sync = sync.thenApply(channelHandler -> {
connection.setClientName(redisURI.getClientName());
return channelHandler;
});
}
if (redisURI.getDatabase() != 0) {
sync = sync.thenCompose(channelHandler -> {
CommandArgs<K, V> args = new CommandArgs<>(codec).add(redisURI.getDatabase());
return connection.async().dispatch(CommandType.SELECT, new StatusOutput<>(codec), args);
});
}
return sync.thenApply(channelHandler -> (S) connection);
}
private static boolean hasPassword(RedisURI redisURI) {
return redisURI.getPassword() != null && redisURI.getPassword().length != 0;
}
@Override
public void setOptions(ClientOptions clientOptions) {
super.setOptions(clientOptions);
}
public ClientResources getResources() {
return clientResources;
}
protected <K, V> StatefulRediSearchConnectionImpl<K, V> newStatefulRedisConnection(RedisChannelWriter channelWriter,
RedisCodec<K, V> codec, Duration timeout) {
return new StatefulRediSearchConnectionImpl<>(channelWriter, codec, timeout);
}
protected Mono<SocketAddress> getSocketAddress(RedisURI redisURI) {
return Mono.defer(() -> {
if (redisURI.getSentinelMasterId() != null && !redisURI.getSentinels().isEmpty()) {
logger.debug("Connecting to Redis using Sentinels {}, MasterId {}", redisURI.getSentinels(),
redisURI.getSentinelMasterId());
return lookupRedis(redisURI).switchIfEmpty(Mono.error(new RedisConnectionException(
"Cannot provide redisAddress using sentinel for masterId " + redisURI.getSentinelMasterId())));
} else {
return Mono.fromCallable(() -> clientResources.socketAddressResolver().resolve((redisURI)));
}
});
}
private Mono<SocketAddress> lookupRedis(RedisURI sentinelUri) {
Mono<StatefulRediSearchSentinelConnection<String, String>> connection = Mono
.fromCompletionStage(connectSentinelAsync(newStringStringCodec(), sentinelUri, timeout));
return connection.flatMap(c -> c.reactive() //
.getMasterAddrByName(sentinelUri.getSentinelMasterId()) //
.timeout(this.timeout) //
.flatMap(it -> Mono.fromCompletionStage(c.closeAsync()) //
.then(Mono.just(it))));
}
protected RedisCodec<String, String> newStringStringCodec() {
return StringCodec.UTF8;
}
private Mono<SocketAddress> getSocketAddressSupplier(RedisURI redisURI) {
return getSocketAddress(redisURI)
.doOnNext(addr -> logger.debug("Resolved SocketAddress {} using {}", addr, redisURI));
}
private static <T> ConnectionFuture<T> transformAsyncConnectionException(ConnectionFuture<T> future) {
return future.thenCompose((v, e) -> {
if (e != null) {
return Futures.failed(RedisConnectionException.create(future.getRemoteAddress(), e));
}
return CompletableFuture.completedFuture(v);
});
}
private static <T> CompletableFuture<T> transformAsyncConnectionException(CompletionStage<T> future,
RedisURI target) {
return ConnectionFuture.from(null, future.toCompletableFuture()).thenCompose((v, e) -> {
if (e != null) {
return Futures.failed(RedisConnectionException.create(target.toString(), e));
}
return CompletableFuture.completedFuture(v);
}).toCompletableFuture();
}
private static void checkValidRedisURI(RedisURI redisURI) {
LettuceAssert.notNull(redisURI, "A valid RedisURI is required");
if (redisURI.getSentinels().isEmpty()) {
if (isEmpty(redisURI.getHost()) && isEmpty(redisURI.getSocket())) {
throw new IllegalArgumentException("RedisURI for Redis Standalone does not contain a host or a socket");
}
} else {
if (isEmpty(redisURI.getSentinelMasterId())) {
throw new IllegalArgumentException("TRedisURI for Redis Sentinel requires a masterId");
}
for (RedisURI sentinel : redisURI.getSentinels()) {
if (isEmpty(sentinel.getHost()) && isEmpty(sentinel.getSocket())) {
throw new IllegalArgumentException(
"RedisURI for Redis Sentinel does not contain a host or a socket");
}
}
}
}
private static <K, V> void assertNotNull(RedisCodec<K, V> codec) {
LettuceAssert.notNull(codec, "RedisCodec must not be null");
}
private static void assertNotNull(RedisURI redisURI) {
LettuceAssert.notNull(redisURI, "RedisURI must not be null");
}
private static void assertNotNull(ClientResources clientResources) {
LettuceAssert.notNull(clientResources, "ClientResources must not be null");
}
private void checkForRedisURI() {
LettuceAssert.assertState(this.redisURI != EMPTY_URI,
"RedisURI is not available. Use RedisClient(Host), RedisClient(Host, Port) or RedisClient(RedisURI) to construct your client.");
checkValidRedisURI(this.redisURI);
}
/**
* Open a connection to a Redis Sentinel that treats keys and values as UTF-8
* strings.
*
* @return A new stateful Redis Sentinel connection
*/
public StatefulRediSearchSentinelConnection<String, String> connectSentinel() {
return connectSentinel(newStringStringCodec());
}
/**
* Open a connection to a Redis Sentinel that treats keys and use the supplied
* {@link RedisCodec codec} to encode/decode keys and values. The client
* {@link RedisURI} must contain one or more sentinels.
*
* @param codec Use this codec to encode/decode keys and values, must not be
* {@literal null}
* @param <K> Key type
* @param <V> Value type
* @return A new stateful Redis Sentinel connection
*/
public <K, V> StatefulRediSearchSentinelConnection<K, V> connectSentinel(RedisCodec<K, V> codec) {
checkForRedisURI();
return getConnection(connectSentinelAsync(codec, redisURI, timeout));
}
/**
* Open a connection to a Redis Sentinel using the supplied {@link RedisURI}
* that treats keys and values as UTF-8 strings. The client {@link RedisURI}
* must contain one or more sentinels.
*
* @param redisURI the Redis server to connect to, must not be {@literal null}
* @return A new connection
*/
public StatefulRediSearchSentinelConnection<String, String> connectSentinel(RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectSentinelAsync(newStringStringCodec(), redisURI, redisURI.getTimeout()));
}
/**
* Open a connection to a Redis Sentinel using the supplied {@link RedisURI} and
* use the supplied {@link RedisCodec codec} to encode/decode keys and values.
* The client {@link RedisURI} must contain one or more sentinels.
*
* @param codec the Redis server to connect to, must not be {@literal null}
* @param redisURI the Redis server to connect to, must not be {@literal null}
* @param <K> Key type
* @param <V> Value type
* @return A new connection
*/
public <K, V> StatefulRediSearchSentinelConnection<K, V> connectSentinel(RedisCodec<K, V> codec,
RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectSentinelAsync(codec, redisURI, redisURI.getTimeout()));
}
/**
* Open asynchronously a connection to a Redis Sentinel using the supplied
* {@link RedisURI} and use the supplied {@link RedisCodec codec} to
* encode/decode keys and values. The client {@link RedisURI} must contain one
* or more sentinels.
*
* @param codec the Redis server to connect to, must not be {@literal null}
* @param redisURI the Redis server to connect to, must not be {@literal null}
* @param <K> Key type
* @param <V> Value type
* @return A new connection
* @since 5.1
*/
public <K, V> CompletableFuture<StatefulRediSearchSentinelConnection<K, V>> connectSentinelAsync(
RedisCodec<K, V> codec, RedisURI redisURI) {
assertNotNull(redisURI);
return transformAsyncConnectionException(connectSentinelAsync(codec, redisURI, redisURI.getTimeout()),
redisURI);
}
private <K, V> CompletableFuture<StatefulRediSearchSentinelConnection<K, V>> connectSentinelAsync(
RedisCodec<K, V> codec, RedisURI redisURI, Duration timeout) {
assertNotNull(codec);
checkValidRedisURI(redisURI);
ConnectionBuilder connectionBuilder = ConnectionBuilder.connectionBuilder();
connectionBuilder.clientOptions(ClientOptions.copyOf(getOptions()));
connectionBuilder.clientResources(clientResources);
DefaultEndpoint endpoint = new DefaultEndpoint(clientOptions, clientResources);
RedisChannelWriter writer = endpoint;
if (CommandExpiryWriter.isSupported(clientOptions)) {
writer = new CommandExpiryWriter(writer, clientOptions, clientResources);
}
StatefulRediSearchSentinelConnectionImpl<K, V> connection = newStatefulRediSearchSentinelConnection(writer,
codec, timeout);
logger.debug("Trying to get a Redis Sentinel connection for one of: " + redisURI.getSentinels());
connectionBuilder.endpoint(endpoint)
.commandHandler(() -> new CommandHandler(clientOptions, clientResources, endpoint))
.connection(connection);
connectionBuilder(getSocketAddressSupplier(redisURI), connectionBuilder, redisURI);
if (clientOptions.isPingBeforeActivateConnection()) {
connectionBuilder.enablePingBeforeConnect();
}
Mono<StatefulRediSearchSentinelConnection<K, V>> connect;
if (redisURI.getSentinels().isEmpty() && (isNotEmpty(redisURI.getHost()) || !isEmpty(redisURI.getSocket()))) {
channelType(connectionBuilder, redisURI);
connect = Mono.fromCompletionStage(initializeChannelAsync(connectionBuilder));
} else {
List<RedisURI> sentinels = redisURI.getSentinels();
validateUrisAreOfSameConnectionType(sentinels);
Mono<StatefulRediSearchSentinelConnection<K, V>> connectionLoop = Mono.defer(() -> {
RedisURI uri = sentinels.get(0);
channelType(connectionBuilder, uri);
return connectSentinel(connectionBuilder, uri);
});
for (int i = 1; i < sentinels.size(); i++) {
RedisURI uri = sentinels.get(i);
connectionLoop = connectionLoop.onErrorResume(t -> connectSentinel(connectionBuilder, uri));
}
connect = connectionLoop;
}
if (LettuceStrings.isNotEmpty(redisURI.getClientName())) {
connect = connect.doOnNext(c -> connection.setClientName(redisURI.getClientName()));
}
return connect.doOnError(e -> {
connection.close();
throw new RedisConnectionException("Cannot connect to a Redis Sentinel: " + redisURI.getSentinels(), e);
}).toFuture();
}
private static void validateUrisAreOfSameConnectionType(List<RedisURI> redisUris) {
boolean unixDomainSocket = false;
boolean inetSocket = false;
for (RedisURI sentinel : redisUris) {
if (sentinel.getSocket() != null) {
unixDomainSocket = true;
}
if (sentinel.getHost() != null) {
inetSocket = true;
}
}
if (unixDomainSocket && inetSocket) {
throw new RedisConnectionException("You cannot mix unix domain socket and IP socket URI's");
}
}
private <K, V> Mono<StatefulRediSearchSentinelConnection<K, V>> connectSentinel(ConnectionBuilder connectionBuilder,
RedisURI uri) {
connectionBuilder.socketAddressSupplier(getSocketAddressSupplier(uri));
SocketAddress socketAddress = clientResources.socketAddressResolver().resolve(uri);
logger.debug("Connecting to Redis Sentinel, address: " + socketAddress);
Mono<StatefulRediSearchSentinelConnection<K, V>> connectionMono = Mono
.fromCompletionStage(initializeChannelAsync(connectionBuilder));
return connectionMono.onErrorMap(CompletionException.class, Throwable::getCause) //
.doOnError(t -> logger.warn("Cannot connect Redis Sentinel at " + uri + ": " + t.toString())) //
.onErrorMap(e -> new RedisConnectionException("Cannot connect Redis Sentinel at " + uri, e));
}
/**
* Create a new instance of {@link StatefulRediSearchSentinelConnectionImpl} or
* a subclass.
* <p>
* Subclasses of {@link RedisClient} may override that method.
*
* @param channelWriter the channel writer
* @param codec codec
* @param timeout default timeout
* @param <K> Key-Type
* @param <V> Value Type
* @return new instance of StatefulRediSearchSentinelConnectionImpl
*/
protected <K, V> StatefulRediSearchSentinelConnectionImpl<K, V> newStatefulRediSearchSentinelConnection(
RedisChannelWriter channelWriter, RedisCodec<K, V> codec, Duration timeout) {
return new StatefulRediSearchSentinelConnectionImpl<>(channelWriter, codec, timeout);
}
}
|
<reponame>Sasheem/portfolio-website<filename>src/components/Work/workFrontEnd.js<gh_stars>0
import React from 'react';
import { useStaticQuery, graphql } from 'gatsby';
import Img from 'gatsby-image/withIEPolyfill';
import styled from 'styled-components';
import Github from '../../assets/github-brands.svg';
const ProjectLink = styled.a`
min-width: 18em;
height: 250px;
border-radius: 0.5rem;
margin-top: 1.5rem;
margin-bottom: 1.5rem;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
0 4px 6px -2px rgba(0, 0, 0, 0.05);
&:hover {
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1),
0 10px 10px -5px rgba(0, 0, 0, 0.04);
cursor: pointer;
transform: scale(1.1);
}
&:active {
transform: scale(0.98);
opacity: 0.8;
}
`;
const ProjectsFlex = styled.div`
display: flex;
flex-direction: column;
justify-content: space-between;
flex-wrap: wrap;
width: 100%;
@media only screen and (min-width: 768px) {
flex-direction: row;
}
`;
const Projects = styled.div`
display: grid;
grid-gap: 2em;
justify-items: center;
background-color: yellow;
@media only screen and (min-width: 768px) {
grid-template-columns: 1fr 1fr;
}
@media only screen and (min-width: 960px) {
grid-template-columns: 1fr 1fr 1fr;
}
`;
const WorkFrontEnd = () => {
const data = useStaticQuery(graphql`
fragment processProjectImage on File {
childImageSharp {
fluid(maxWidth: 325) {
...GatsbyImageSharpFluid
}
}
}
query {
projectOne: file(relativePath: { eq: "portfolio-web.png" }) {
...processProjectImage
}
projectTwo: file(relativePath: { eq: "unhoused-humanity-web.png" }) {
...processProjectImage
}
projectThree: file(relativePath: { eq: "sleep-out-2019-web.png" }) {
...processProjectImage
}
}
`);
const projectDataOne = data.projectOne.childImageSharp.fluid;
const projectDataTwo = data.projectTwo.childImageSharp.fluid;
const projectDataThree = data.projectThree.childImageSharp.fluid;
return (
<div
className="flex flex-col justify-center items-left mb-12"
name="work-dev"
>
<span id="work-dev" className="scroll-anchor" />
<section className="py-10 flex flex-col items-start bg-gray-1 px-responsive">
<h1 className="text-gray-8 text-2xl sm-text-4xl font-bold span spanTitle">
Front-End Web Development
</h1>
<p className="text-grey-6 text-left my-6 text-2xl-responsive leading-relaxed">
A few websites I have designed and coded.
</p>
<ProjectsFlex>
<ProjectLink
target="_blank"
href="https://github.com/Sasheem/Portfolio-Website"
>
<Img
fluid={projectDataOne}
alt="Portfolio Website"
objectFit="fill"
style={{
height: '100%',
width: '100%',
// minWidth: '325px',
borderRadius: 8,
}}
/>
</ProjectLink>
<ProjectLink
target="_blank"
// href="https://musing-joliot-870301.netlify.app/"
href="https://github.com/Sasheem/gatsby-unhoused-website"
>
<Img
fluid={projectDataTwo}
alt="Unhoused Humanity Website"
objectFit="fill"
style={{
height: '100%',
width: '100%',
borderRadius: 10,
}}
/>
</ProjectLink>
<ProjectLink target="_blank" href="https://sleepouttlh.org/">
<Img
fluid={projectDataThree}
alt="Sleep Out 2019 Website"
objectFit="fill"
style={{
height: '100%',
width: '100%',
borderRadius: 8,
}}
/>
</ProjectLink>
</ProjectsFlex>
<a
className="flex github linksmart font-medium px-4 py-3 my-6 items-center justify-start rounded-lg cursor-pointer overflow-hidden"
href="https://github.com/Sasheem"
target="_blank"
>
<div className="mr-2" style={{ height: 21, width: 21 }}>
<Github />
</div>
<p className="mx-2">Source code</p>
</a>
</section>
</div>
);
};
export default WorkFrontEnd;
|
//// react
import React, { useState, useEffect, useContext, useCallback } from 'react';
//// react native
//// react navigation
import { useFocusEffect } from '@react-navigation/native';
import { navigate } from '~/navigation/service';
//// language
//// ui, styles
//// contexts
import {
PostsContext,
AuthContext,
UIContext,
UserContext,
SettingsContext,
} from '~/contexts';
//// etc
//// screens, views
import { NotificationScreen } from '../screen/Notification';
interface Props { }
const Notification = (props: Props): JSX.Element => {
//// props
//// contexts
const { setPostRef, setPostDetails } = useContext(PostsContext);
const { userState, getNotifications } = useContext(UserContext);
const { authState } = useContext(AuthContext);
const { setAuthorParam } = useContext(UIContext);
const { settingsState } = useContext(SettingsContext);
//// states
const [username, setUsername] = useState('');
const [fetching, setFetching] = useState(false);
const [notifications, setNotifications] = useState(null);
//////// effects
//// focus event
// useFocusEffect(
// useCallback(() => {
// if (authState.loggedIn)
// setUsername(authState.currentCredentials.username);
// _fetchNotifications(authState.currentCredentials.username);
// }, []),
// );
//// username change event
useEffect(() => {
if (authState.loggedIn) {
// fetch new notifications data if the username changed,
if (notifications && username !== authState.currentCredentials.username) {
_fetchNotifications(authState.currentCredentials.username, true);
} else {
// otherwise use prefetched notifications if available
_fetchNotifications(authState.currentCredentials.username);
}
// set username
setUsername(authState.currentCredentials.username);
}
}, [authState.currentCredentials]);
//// fetch notifications
const _fetchNotifications = async (username: string, refresh?: boolean) => {
// clear notification
setNotifications(null);
setFetching(true);
let _notifications = null;
if (refresh || !userState.notificationData.fetched) {
_notifications = await getNotifications(username);
} else {
_notifications = userState.notificationData.notifications;
}
setNotifications(_notifications);
setFetching(false);
};
//// handle press item
const _handlePressItem = (author: string, permlink: string) => {
console.log(
'[notifications] _handlePressItem. author, permlink',
author,
permlink,
);
// check if permlink exists
if (permlink) {
// set post ref
setPostRef({ author, permlink });
// set post data to context
setPostDetails(null);
// navigate to the post
navigate({ name: 'PostDetails' });
} else {
// set author param
setAuthorParam(author);
// navigate to the author profile
navigate({ name: 'AuthorProfile' });
}
};
//// handle refresh list
const _handleRefresh = async () => {
// fetch notifications
_fetchNotifications(username, true);
};
return (
<NotificationScreen
notifications={notifications}
fetching={fetching}
username={authState.currentCredentials.username}
imageServer={settingsState.blockchains.image}
handlePressItem={_handlePressItem}
handleRefresh={_handleRefresh}
/>
);
};
export { Notification };
|
package web
import (
"encoding/json"
"net/http"
)
var version = "1.0.0" // quick and dirty for demos
type helloHandler struct {
helloService HelloWorldable
}
type helloMessage struct {
Message string `json:"message"`
Version string `json:"version"`
}
func NewHelloHandler(helloService HelloWorldable) *helloHandler {
return &helloHandler{
helloService: helloService,
}
}
func (hh *helloHandler) HelloEndpoint(w http.ResponseWriter, req *http.Request) {
query := req.URL.Query()
name := query.Get("name")
result, err := hh.helloService.Hello(name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
message := helloMessage{
Message: result,
Version: version,
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
json.NewEncoder(w).Encode(message)
}
|
<reponame>Charliocat/armeria
/*
* Copyright 2020 LINE Corporation
*
* LINE Corporation 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.client.zookeeper;
import static java.util.Objects.requireNonNull;
import java.time.Duration;
import java.util.function.Consumer;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import com.linecorp.armeria.client.endpoint.EndpointSelectionStrategy;
import com.linecorp.armeria.common.zookeeper.AbstractCuratorFrameworkBuilder;
import com.linecorp.armeria.common.zookeeper.NodeValueCodec;
/**
* Builds a {@link ZooKeeperEndpointGroup}.
*/
public final class ZooKeeperEndpointGroupBuilder extends AbstractCuratorFrameworkBuilder {
private final String zNodePath;
private EndpointSelectionStrategy selectionStrategy = EndpointSelectionStrategy.weightedRoundRobin();
private NodeValueCodec nodeValueCodec = NodeValueCodec.ofDefault();
ZooKeeperEndpointGroupBuilder(String zkConnectionStr, String zNodePath) {
super(zkConnectionStr);
this.zNodePath = zNodePath;
}
ZooKeeperEndpointGroupBuilder(CuratorFramework client, String zNodePath) {
super(client);
this.zNodePath = zNodePath;
}
/**
* Sets the {@link EndpointSelectionStrategy} of the {@link ZooKeeperEndpointGroup}.
*/
public ZooKeeperEndpointGroupBuilder selectionStrategy(EndpointSelectionStrategy selectionStrategy) {
this.selectionStrategy = requireNonNull(selectionStrategy, "selectionStrategy");
return this;
}
/**
* Sets the {@link NodeValueCodec} of the {@link ZooKeeperEndpointGroup}.
*/
public ZooKeeperEndpointGroupBuilder codec(NodeValueCodec nodeValueCodec) {
this.nodeValueCodec = requireNonNull(nodeValueCodec, "nodeValueCodec");
return this;
}
/**
* Returns a new {@link ZooKeeperEndpointGroup} created with the properties set so far.
*/
public ZooKeeperEndpointGroup build() {
final CuratorFramework client = buildCuratorFramework();
final boolean internalClient = !isUserSpecifiedCuratorFramework();
return new ZooKeeperEndpointGroup(selectionStrategy, client, zNodePath, nodeValueCodec, internalClient);
}
// Override the return type of the chaining methods in the superclass.
@Override
public ZooKeeperEndpointGroupBuilder connectTimeout(Duration connectTimeout) {
return (ZooKeeperEndpointGroupBuilder) super.connectTimeout(connectTimeout);
}
@Override
public ZooKeeperEndpointGroupBuilder connectTimeoutMillis(long connectTimeoutMillis) {
return (ZooKeeperEndpointGroupBuilder) super.connectTimeoutMillis(connectTimeoutMillis);
}
@Override
public ZooKeeperEndpointGroupBuilder sessionTimeout(Duration sessionTimeout) {
return (ZooKeeperEndpointGroupBuilder) super.sessionTimeout(sessionTimeout);
}
@Override
public ZooKeeperEndpointGroupBuilder sessionTimeoutMillis(long sessionTimeoutMillis) {
return (ZooKeeperEndpointGroupBuilder) super.sessionTimeoutMillis(sessionTimeoutMillis);
}
@Override
public ZooKeeperEndpointGroupBuilder customizer(Consumer<? super Builder> customizer) {
return (ZooKeeperEndpointGroupBuilder) super.customizer(customizer);
}
}
|
#!/bin/bash
iwpriv wfd0 drvdbg 0x20037
# change the mac address
ifconfig mlan0 hw ether 00:50:43:21:0e:08
ifconfig wfd0 hw ether 00:50:43:21:0e:08
ifconfig uap0 hw ether 00:50:43:21:0e:08
iwpriv wfd0 deepsleep 0
iwconfig wfd0 power off
iwpriv wfd0 bssrole 1
./uaputl.exe -i wfd0 sys_config config/uaputl_wifidirect.conf
iwpriv wfd0 bssrole 0
./wifidirectutl wfd0 wifidirect_config config/wifidirect.conf
./uaputl.exe -i wfd0 sys_cfg_protocol 32
./uaputl.exe -i wfd0 sys_cfg_cipher 8 8
./uaputl.exe -i wfd0 sys_cfg_wpa_passphrase 1234567890
./wifidirectutl wfd0 wifidirect_mode 1
|
#!/bin/bash
surf=fmripout/freesurfer/sub-TTTEMPSUB/surf
mris_convert $surf/lh.pial surface/left_pial.surf.gii
mris_convert $surf/rh.pial surface/right_pial.surf.gii
mris_convert $surf/lh.white surface/left_white.surf.gii
mris_convert $surf/rh.white surface/right_white.surf.gii
mris_convert $surf/lh.inflated surface/left_inflated.surf.gii
mris_convert $surf/rh.inflated surface/right_inflated.surf.gii
|
<reponame>daylanvig/ParliamentApp
export default class StringUtils {
/**
* Check if string is null (or undefined), or empty.
* @param value The string value to check
*/
public static isNullOrEmpty(value?: string | null): boolean {
return value == null || value === '';
}
} |
<filename>src/reducers/__tests__/test-index.js
import test from 'ava';
import sinon from 'sinon';
import proxyquire from 'proxyquire';
import navigation from '../navigation';
test('It calls combineReducers passing in the navigation', t => {
const stubbedCombineReducers = sinon.stub();
const index = proxyquire('../index', {
redux: {
combineReducers: stubbedCombineReducers
}
}).default;
const expected = true;
const actual = stubbedCombineReducers.calledWith({navigation});
t.deepEqual(expected, actual);
});
|
import numpy as np
def optimize(f, x_init):
# Set the learning rate
learning_rate = 0.01
# Initiate the function and its derivative
x = x_init
f_x = f(x)
f_prime_x = 2*x - 4
# Repeat the optimization routine
for i in range(1000):
# Calculate the new x
x_new = x - learning_rate * f_prime_x
# Calculate the new f(x)
f_x_new = f(x_new)
# Update the values if the new f(x) is greater
if f_x_new > f_x:
x = x_new
f_x = f_x_new
f_prime_x = 2*x - 4
return x
# Call the function
x_opt = optimize(lambda x: 2*(x**2) - 4*x, 10)
print('The optimized x is:', x_opt) |
def gini_coefficient(data):
n = len(data)
# Sort data
wealth = sorted(data, key=lambda x: x[1])
# Calculate cumulative totals
cum_sum = 0
cum_total = [0]
for i in range(n):
cum_sum += wealth[i][1]
cum_total.append(cum_sum)
# Calculate Gini coefficient
numerator = 0
for i in range(n):
numerator += (n + 1 - (2 * i) - 1) * wealth[i][1]
denomenator = (n ** 2) * cum_total[n]
gini = 1 - (numerator / denomenator)
return gini
# Calculate Gini coefficient
gini = gini_coefficient(data)
# Print Gini coefficient
print('My Gini coefficient is', gini) |
sudo pip install --upgrade pip
sudo pip install -r ./requirements.txt
|
/*
* Copyright (c) 1999-2008 <NAME> and <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include "base/cast.hh"
#include "debug/RubyNetwork.hh"
#include "mem/ruby/buffers/MessageBuffer.hh"
#include "mem/ruby/network/simple/PerfectSwitch.hh"
#include "mem/ruby/network/simple/SimpleNetwork.hh"
#include "mem/ruby/network/simple/Switch.hh"
#include "mem/ruby/slicc_interface/NetworkMessage.hh"
using namespace std;
const int PRIORITY_SWITCH_LIMIT = 128;
// Operator for helper class
bool
operator<(const LinkOrder& l1, const LinkOrder& l2)
{
return (l1.m_value < l2.m_value);
}
PerfectSwitch::PerfectSwitch(SwitchID sid, Switch *sw, uint32_t virt_nets)
: Consumer(sw)
{
m_switch_id = sid;
m_round_robin_start = 0;
m_wakeups_wo_switch = 0;
m_virtual_networks = virt_nets;
}
void
PerfectSwitch::init(SimpleNetwork *network_ptr)
{
m_network_ptr = network_ptr;
for(int i = 0;i < m_virtual_networks;++i)
{
m_pending_message_count.push_back(0);
}
}
void
PerfectSwitch::addInPort(const vector<MessageBuffer*>& in, Switch *sw)
{
assert(in.size() == m_virtual_networks);
NodeID port = m_in.size();
m_in.push_back(in);
for (int j = 0; j < m_virtual_networks; j++) {
m_in[port][j]->setConsumer(this);
m_in[port][j]->setClockObj(sw);
string desc = csprintf("[Queue from port %s %s %s to PerfectSwitch]",
to_string(m_switch_id), to_string(port), to_string(j));
m_in[port][j]->setDescription(desc);
m_in[port][j]->setIncomingLink(port);
m_in[port][j]->setVnet(j);
}
}
void
PerfectSwitch::addOutPort(const vector<MessageBuffer*>& out,
const NetDest& routing_table_entry)
{
assert(out.size() == m_virtual_networks);
// Setup link order
LinkOrder l;
l.m_value = 0;
l.m_link = m_out.size();
m_link_order.push_back(l);
// Add to routing table
m_out.push_back(out);
m_routing_table.push_back(routing_table_entry);
}
void
PerfectSwitch::clearRoutingTables()
{
m_routing_table.clear();
}
void
PerfectSwitch::clearBuffers()
{
for (int i = 0; i < m_in.size(); i++){
for(int vnet = 0; vnet < m_virtual_networks; vnet++) {
m_in[i][vnet]->clear();
}
}
for (int i = 0; i < m_out.size(); i++){
for(int vnet = 0; vnet < m_virtual_networks; vnet++) {
m_out[i][vnet]->clear();
}
}
}
void
PerfectSwitch::reconfigureOutPort(const NetDest& routing_table_entry)
{
m_routing_table.push_back(routing_table_entry);
}
PerfectSwitch::~PerfectSwitch()
{
}
void
PerfectSwitch::wakeup()
{
MsgPtr msg_ptr;
// Give the highest numbered link priority most of the time
m_wakeups_wo_switch++;
int highest_prio_vnet = m_virtual_networks-1;
int lowest_prio_vnet = 0;
int decrementer = 1;
NetworkMessage* net_msg_ptr = NULL;
// invert priorities to avoid starvation seen in the component network
if (m_wakeups_wo_switch > PRIORITY_SWITCH_LIMIT) {
m_wakeups_wo_switch = 0;
highest_prio_vnet = 0;
lowest_prio_vnet = m_virtual_networks-1;
decrementer = -1;
}
// For all components incoming queues
for (int vnet = highest_prio_vnet;
(vnet * decrementer) >= (decrementer * lowest_prio_vnet);
vnet -= decrementer) {
// This is for round-robin scheduling
int incoming = m_round_robin_start;
m_round_robin_start++;
if (m_round_robin_start >= m_in.size()) {
m_round_robin_start = 0;
}
if(m_pending_message_count[vnet] > 0) {
// for all input ports, use round robin scheduling
for (int counter = 0; counter < m_in.size(); counter++) {
// Round robin scheduling
incoming++;
if (incoming >= m_in.size()) {
incoming = 0;
}
// temporary vectors to store the routing results
vector<LinkID> output_links;
vector<NetDest> output_link_destinations;
// Is there a message waiting?
while (m_in[incoming][vnet]->isReady()) {
DPRINTF(RubyNetwork, "incoming: %d\n", incoming);
// Peek at message
msg_ptr = m_in[incoming][vnet]->peekMsgPtr();
net_msg_ptr = safe_cast<NetworkMessage*>(msg_ptr.get());
DPRINTF(RubyNetwork, "Message: %s\n", (*net_msg_ptr));
output_links.clear();
output_link_destinations.clear();
NetDest msg_dsts =
net_msg_ptr->getInternalDestination();
// Unfortunately, the token-protocol sends some
// zero-destination messages, so this assert isn't valid
// assert(msg_dsts.count() > 0);
assert(m_link_order.size() == m_routing_table.size());
assert(m_link_order.size() == m_out.size());
if (m_network_ptr->getAdaptiveRouting()) {
if (m_network_ptr->isVNetOrdered(vnet)) {
// Don't adaptively route
for (int out = 0; out < m_out.size(); out++) {
m_link_order[out].m_link = out;
m_link_order[out].m_value = 0;
}
} else {
// Find how clogged each link is
for (int out = 0; out < m_out.size(); out++) {
int out_queue_length = 0;
for (int v = 0; v < m_virtual_networks; v++) {
out_queue_length += m_out[out][v]->getSize();
}
int value =
(out_queue_length << 8) | (random() & 0xff);
m_link_order[out].m_link = out;
m_link_order[out].m_value = value;
}
// Look at the most empty link first
sort(m_link_order.begin(), m_link_order.end());
}
}
for (int i = 0; i < m_routing_table.size(); i++) {
// pick the next link to look at
int link = m_link_order[i].m_link;
NetDest dst = m_routing_table[link];
DPRINTF(RubyNetwork, "dst: %s\n", dst);
if (!msg_dsts.intersectionIsNotEmpty(dst))
continue;
// Remember what link we're using
output_links.push_back(link);
// Need to remember which destinations need this
// message in another vector. This Set is the
// intersection of the routing_table entry and the
// current destination set. The intersection must
// not be empty, since we are inside "if"
output_link_destinations.push_back(msg_dsts.AND(dst));
// Next, we update the msg_destination not to
// include those nodes that were already handled
// by this link
msg_dsts.removeNetDest(dst);
}
assert(msg_dsts.count() == 0);
//assert(output_links.size() > 0);
// Check for resources - for all outgoing queues
bool enough = true;
for (int i = 0; i < output_links.size(); i++) {
int outgoing = output_links[i];
if (!m_out[outgoing][vnet]->areNSlotsAvailable(1))
enough = false;
DPRINTF(RubyNetwork, "Checking if node is blocked ..."
"outgoing: %d, vnet: %d, enough: %d\n",
outgoing, vnet, enough);
}
// There were not enough resources
if (!enough) {
scheduleEvent(1);
DPRINTF(RubyNetwork, "Can't deliver message since a node "
"is blocked\n");
DPRINTF(RubyNetwork, "Message: %s\n", (*net_msg_ptr));
break; // go to next incoming port
}
MsgPtr unmodified_msg_ptr;
if (output_links.size() > 1) {
// If we are sending this message down more than
// one link (size>1), we need to make a copy of
// the message so each branch can have a different
// internal destination we need to create an
// unmodified MsgPtr because the MessageBuffer
// enqueue func will modify the message
// This magic line creates a private copy of the
// message
unmodified_msg_ptr = msg_ptr->clone();
}
// Enqueue it - for all outgoing queues
for (int i=0; i<output_links.size(); i++) {
int outgoing = output_links[i];
if (i > 0) {
// create a private copy of the unmodified
// message
msg_ptr = unmodified_msg_ptr->clone();
}
// Change the internal destination set of the
// message so it knows which destinations this
// link is responsible for.
net_msg_ptr = safe_cast<NetworkMessage*>(msg_ptr.get());
net_msg_ptr->getInternalDestination() =
output_link_destinations[i];
// Enqeue msg
DPRINTF(RubyNetwork, "Enqueuing net msg from "
"inport[%d][%d] to outport [%d][%d].\n",
incoming, vnet, outgoing, vnet);
m_out[outgoing][vnet]->enqueue(msg_ptr);
}
// Dequeue msg
m_in[incoming][vnet]->pop();
m_pending_message_count[vnet]--;
}
}
}
}
}
void
PerfectSwitch::storeEventInfo(int info)
{
m_pending_message_count[info]++;
}
void
PerfectSwitch::printStats(std::ostream& out) const
{
out << "PerfectSwitch printStats" << endl;
}
void
PerfectSwitch::clearStats()
{
}
void
PerfectSwitch::print(std::ostream& out) const
{
out << "[PerfectSwitch " << m_switch_id << "]";
}
|
<gh_stars>0
/**
* @class BtCheckbox
* @memberof module:plugins
* @description Applies Awesome Bootstrap Checkbox for checkbox and radio inputs.
* @param {object} [options]
* @param {string} [options.font='glyphicons']
* @param {string} [options.color='default']
*/
QueryBuilder.define('bt-checkbox', function(options) {
if (options.font == 'glyphicons') {
this.$el.addClass('bt-checkbox-glyphicons');
}
this.on('getRuleInput.filter', function(h, rule, name) {
var filter = rule.filter;
if ((filter.input === 'radio' || filter.input === 'checkbox') && !filter.plugin) {
h.value = '';
if (!filter.colors) {
filter.colors = {};
}
if (filter.color) {
filter.colors._def_ = filter.color;
}
var style = filter.vertical ? ' style="display:block"' : '';
var i = 0;
Utils.iterateOptions(filter.values, function(key, val) {
var color = filter.colors[key] || filter.colors._def_ || options.color;
var id = name + '_' + (i++);
h.value+= '\
<div' + style + ' class="' + filter.input + ' ' + filter.input + '-' + color + '"> \
<input type="' + filter.input + '" name="' + name + '" id="' + id + '" value="' + key + '"> \
<label for="' + id + '">' + val + '</label> \
</div>';
});
}
});
}, {
font: 'glyphicons',
color: 'default'
});
|
#!/bin/sh
# Copyright (c) 2014-2016 The Fastbitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
INPUT=$(cat /dev/stdin)
VALID=false
REVSIG=false
IFS='
'
for LINE in $(echo "$INPUT" | gpg --trust-model always "$@" 2>/dev/null); do
case "$LINE" in
"[GNUPG:] VALIDSIG "*)
while read KEY; do
[ "${LINE#?GNUPG:? VALIDSIG * * * * * * * * * }" = "$KEY" ] && VALID=true
done < ./contrib/verify-commits/trusted-keys
;;
"[GNUPG:] REVKEYSIG "*)
[ "$FASTBITCOIN_VERIFY_COMMITS_ALLOW_REVSIG" != 1 ] && exit 1
REVSIG=true
GOODREVSIG="[GNUPG:] GOODSIG ${LINE#* * *}"
;;
esac
done
if ! $VALID; then
exit 1
fi
if $VALID && $REVSIG; then
echo "$INPUT" | gpg --trust-model always "$@" | grep "\[GNUPG:\] \(NEWSIG\|SIG_ID\|VALIDSIG\)" 2>/dev/null
echo "$GOODREVSIG"
else
echo "$INPUT" | gpg --trust-model always "$@" 2>/dev/null
fi
|
'use-strict';
const Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const { list, create } = require('../controllers/courseBillingItemController');
const {
authorizeCourseBillingItemCreation,
} = require('./preHandlers/courseBillingItems');
exports.plugin = {
name: 'routes-course-billing-items',
register: async (server) => {
server.route({
method: 'GET',
path: '/',
options: { auth: { scope: ['config:vendor'] } },
handler: list,
});
server.route({
method: 'POST',
path: '/',
options: {
validate: {
payload: Joi.object({
name: Joi.string().required(),
}),
},
auth: { scope: ['config:vendor'] },
pre: [{ method: authorizeCourseBillingItemCreation }],
},
handler: create,
});
},
};
|
# Multicore stack
module load daint-mc
# Python 3 & mpi4py
module load cray-python/3.8.5.1
# Cython
module load PyExtensions/python3-CrayGNU-20.11
# h5py
module load h5py/2.10.0-CrayGNU-20.11-python3-parallel
# GSL for NEST
module load GSL/2.5-CrayGNU-20.11
|
import { async, TestBed } from '@angular/core/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { HttpService } from './http.service';
describe('HttpService', () => {
let httpService: HttpService;
let mockBackend: MockBackend;
beforeEach(() => TestBed.configureTestingModule({
providers: [
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
deps: [MockBackend, BaseRequestOptions]
},
HttpService
]
}));
beforeEach(() => {
httpService = TestBed.get(HttpService);
mockBackend = TestBed.get(MockBackend);
});
it('should init the service', () => {
expect(httpService.baseUrl)
.toBe('http://ponyracer.ninja-squad.com', 'Your service should have a field `baseUrl` correctly initialized');
expect(httpService.options.headers)
.toBe(httpService.headers, 'Your service should have a field `options` correctly initialized with the headers');
});
it('should do a GET request', async(() => {
const hardcodedRaces = [{ name: 'Paris' }, { name: 'Tokyo' }, { name: 'Lyon' }];
const response = new Response(new ResponseOptions({ body: hardcodedRaces }));
// return the response if we have a connection to the MockBackend
mockBackend.connections.subscribe(connection => {
expect(connection.request.url)
.toBe('http://ponyracer.ninja-squad.com/api/races?status=PENDING', 'The service should build the correct URL for a GET');
expect(connection.request.method).toBe(RequestMethod.Get);
expect(connection.request.headers.get('Authorization')).toBeNull();
connection.mockRespond(response);
});
httpService.get('/api/races?status=PENDING').subscribe((res) => {
expect(res).toBe(hardcodedRaces);
});
}));
it('should do a POST request', async(() => {
const user = { login: 'cedric' };
const response = new Response(new ResponseOptions({ body: user }));
// return the response if we have a connection to the MockBackend
mockBackend.connections.subscribe(connection => {
expect(connection.request.url)
.toBe('http://ponyracer.ninja-squad.com/api/users', 'The service should build the correct URL for a POST');
expect(connection.request.method).toBe(RequestMethod.Post);
expect(connection.request.headers.get('Authorization')).toBeNull();
connection.mockRespond(response);
});
httpService.post('/api/users', user).subscribe((res) => {
expect(res).toBe(user);
});
}));
it('should add/remove the JWT token to the headers', () => {
// will first return a 'secret' token, then nothing on second call
let firstCall = true;
spyOn(window.localStorage, 'getItem').and.callFake(() => {
if (firstCall) {
firstCall = false;
return JSON.stringify({ token: 'secret' });
}
return null;
});
httpService.addJwtTokenIfExists();
// so we should have a header the first time
expect(httpService.headers.get('Authorization'))
.toBe('Bearer secret', 'The `Authorization` header is not correct after adding the JWT token');
httpService.addJwtTokenIfExists();
// and no header the second time
expect(httpService.headers.get('Authorization')).toBeNull('The `Authorization` header should be null after removing the JWT token');
});
it('should do an authenticated GET request', async(() => {
spyOn(window.localStorage, 'getItem')
.and.returnValue(JSON.stringify({ token: 'secret' }));
const hardcodedRaces = [{ name: 'Paris' }, { name: 'Tokyo' }, { name: 'Lyon' }];
const response = new Response(new ResponseOptions({ body: hardcodedRaces }));
// return the response if we have a connection to the MockBackend
mockBackend.connections.subscribe(connection => {
expect(connection.request.url)
.toBe('http://ponyracer.ninja-squad.com/api/races?status=PENDING');
expect(connection.request.method).toBe(RequestMethod.Get);
expect(connection.request.headers.get('Authorization')).toBe('Bearer secret');
connection.mockRespond(response);
});
httpService.get('/api/races?status=PENDING').subscribe((res) => {
expect(res).toBe(hardcodedRaces);
});
}));
it('should do an authenticated DELETE request', async(() => {
spyOn(window.localStorage, 'getItem')
.and.returnValue(JSON.stringify({ token: 'secret' }));
const response = new Response(new ResponseOptions({ status: 204 }));
// return the response if we have a connection to the MockBackend
mockBackend.connections.subscribe(connection => {
expect(connection.request.url)
.toBe('http://ponyracer.ninja-squad.com/api/races/1/bets');
expect(connection.request.method).toBe(RequestMethod.Delete);
expect(connection.request.headers.get('Authorization')).toBe('Bearer secret');
connection.mockRespond(response);
});
httpService.delete('/api/races/1/bets').subscribe((res) => {
expect(res.status).toBe(204, 'The delete method should return the response (and not extract the JSON).');
});
}));
});
|
<reponame>improved-php-library/http-message
/*
+----------------------------------------------------------------------+
| HTTP Message PHP extension - Stream class |
+----------------------------------------------------------------------+
| Copyright (c) 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. |
+----------------------------------------------------------------------+
| Author: <NAME> <<EMAIL>> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "php.h"
#include "macros.h"
#include "stream.h"
#include "zend_exceptions.h"
#include "zend_interfaces.h"
#include "ext/psr/psr_http_message.h"
#include "ext/spl/spl_exceptions.h"
#if HAVE_HTTP_MESSAGE
zend_class_entry *HttpMessage_Stream_ce = NULL;
void stream_seek(zval *this, zend_long offset, zend_long whence, zval* return_value)
{
zval rv, *resource;
php_stream *stream;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(this), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream is %s",
Z_TYPE_P(resource) == IS_RESOURCE ? "closed" : "detached");
return;
}
if (whence > 3) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Invalid value for whence");
return;
}
php_stream_from_zval(stream, resource);
if (!stream->ops->seek || (stream->flags & PHP_STREAM_FLAG_NO_SEEK) != 0) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream is not seekable");
return;
};
php_stream_seek(stream, offset, whence);
}
/* __construct */
ZEND_BEGIN_ARG_INFO_EX(arginfo_HttpMessageStream_construct, 0, 0, 0)
ZEND_ARG_INFO(0, uri)
ZEND_END_ARG_INFO()
PHP_METHOD(Stream, __construct)
{
zval *input = NULL, resource;
char *file = NULL, *mode = NULL;
size_t mode_len = 0;
php_stream *stream;
ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 0, 2)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL(input)
Z_PARAM_STRING(mode, mode_len)
ZEND_PARSE_PARAMETERS_END();
if (UNEXPECTED(input != NULL && Z_TYPE_P(input) != IS_STRING && Z_TYPE_P(input) != IS_RESOURCE)) {
zend_type_error("Expected parameter 1 to be a string or resource, %s given ", zend_zval_type_name(input));
return;
}
if (input == NULL) {
if (open_temp_stream(&resource) == FAILURE) return;
} else if (Z_TYPE_P(input) == IS_STRING) {
file = Z_STRVAL_P(input);
file[Z_STRLEN_P(input)] = '\0';
stream = php_stream_open_wrapper(file, mode != NULL ? mode : "r", 0, NULL);
if (stream == NULL) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Failed to open '%s' stream", file);
return;
}
php_stream_to_zval(stream, &resource);
} else if (EXPECTED(IS_STREAM_RESOURCE(input))) {
ZVAL_COPY(&resource, input);
} else {
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Resource is not a stream");
return;
}
zend_update_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), &resource);
}
PHP_METHOD(Stream, __toString)
{
zval rv, *resource;
php_stream *stream;
zend_string *contents;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
RETURN_EMPTY_STRING();
}
php_stream_from_zval(stream, resource);
if (!string_contains_char(stream->mode, 'r') && !string_contains_char(stream->mode, '+')) {
RETURN_EMPTY_STRING();
}
if ((stream->ops->seek) && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
php_stream_seek(stream, 0, SEEK_SET);
}
// Special case for 'php://input'. Need to reopen the resource, because seek doesn't work.
if (
stream->wrapper != NULL &&
strcmp(stream->wrapper->wops->label, "PHP") == 0 &&
strcmp(stream->ops->label, "Input") == 0
) {
stream = php_stream_open_wrapper(stream->orig_path, stream->mode, 0, NULL);
php_stream_to_zval(stream, resource);
}
if ((contents = php_stream_copy_to_mem(stream, (ssize_t)PHP_STREAM_COPY_ALL, 0))) {
RETURN_STR(contents);
} else {
RETURN_EMPTY_STRING();
}
}
PHP_METHOD(Stream, close)
{
zval rv, *resource;
php_stream *stream;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (Z_TYPE_P(resource) != IS_RESOURCE) {
return;
}
if (IS_STREAM_RESOURCE(resource)) {
php_stream_from_zval(stream, resource);
php_stream_close(stream);
}
}
PHP_METHOD(Stream, detach)
{
zval rv, *resource;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
ZVAL_COPY(return_value, resource);
zend_update_property_null(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"));
}
PHP_METHOD(Stream, getSize)
{
zval rv, *resource;
php_stream *stream;
php_stream_statbuf ssb;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
RETURN_NULL();
}
php_stream_from_zval(stream, resource);
php_stream_stat(stream, &ssb);
RETURN_LONG(ssb.sb.st_size);
}
PHP_METHOD(Stream, tell)
{
zval rv, *resource;
php_stream *stream;
size_t pos;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream is %s",
Z_TYPE_P(resource) == IS_RESOURCE ? "closed" : "detached");
return;
}
php_stream_from_zval(stream, resource);
pos = php_stream_tell(stream);
RETURN_LONG(pos);
}
PHP_METHOD(Stream, eof)
{
zval rv, *resource;
php_stream *stream;
zend_bool eof;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
RETURN_TRUE;
}
php_stream_from_zval(stream, resource);
eof = php_stream_eof(stream);
RETURN_BOOL(eof);
}
PHP_METHOD(Stream, isSeekable)
{
zval rv, *resource;
php_stream *stream;
zend_bool seekable;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
RETURN_FALSE;
}
php_stream_from_zval(stream, resource);
seekable = (stream->ops->seek) && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0;
RETURN_BOOL(seekable);
}
PHP_METHOD(Stream, seek)
{
zend_long offset = 0, whence = SEEK_SET;
ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 1, 2)
Z_PARAM_LONG(offset)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(whence)
ZEND_PARSE_PARAMETERS_END();
stream_seek(getThis(), offset, whence, return_value);
}
PHP_METHOD(Stream, rewind)
{
stream_seek(getThis(), 0, SEEK_SET, return_value);
}
PHP_METHOD(Stream, isWritable)
{
zval rv, *resource;
php_stream *stream;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
RETURN_FALSE;
}
php_stream_from_zval(stream, resource);
RETURN_BOOL(stream_is_writable(stream));
}
PHP_METHOD(Stream, write)
{
zval rv, *resource;
char *input = NULL;
size_t len = 0, ret = 0;
php_stream *stream;
ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 1, 1)
Z_PARAM_STRING(input, len)
ZEND_PARSE_PARAMETERS_END();
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream is %s",
Z_TYPE_P(resource) == IS_RESOURCE ? "closed" : "detached");
return;
}
php_stream_from_zval(stream, resource);
if (!stream_is_writable(stream)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream not writable");
return;
}
if (len > 0) {
ret = php_stream_write(stream, input, len);
}
RETURN_LONG(ret);
}
PHP_METHOD(Stream, isReadable)
{
zval rv, *resource;
php_stream *stream;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
RETURN_FALSE;
}
php_stream_from_zval(stream, resource);
RETURN_BOOL(stream_is_readable(stream));
}
PHP_METHOD(Stream, read)
{
zval rv, *resource;
php_stream *stream;
zend_long len = 0;
zend_string *contents;
ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 1, 1)
Z_PARAM_LONG(len)
ZEND_PARSE_PARAMETERS_END();
if (len < 0) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Length parameter must be equal or greater than 0");
return;
}
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream is %s",
Z_TYPE_P(resource) == IS_RESOURCE ? "closed" : "detached");
return;
}
php_stream_from_zval(stream, resource);
if (!string_contains_char(stream->mode, 'r') && !string_contains_char(stream->mode, '+')) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream not readable");
return;
}
if ((contents = php_stream_copy_to_mem(stream, (size_t)len, 0))) {
RETURN_STR(contents);
} else {
RETURN_EMPTY_STRING();
}
}
PHP_METHOD(Stream, getContents)
{
zval rv, *resource;
php_stream *stream;
zend_string *contents;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
if (!IS_STREAM_RESOURCE(resource)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream is %s",
Z_TYPE_P(resource) == IS_RESOURCE ? "closed" : "detached");
return;
}
php_stream_from_zval(stream, resource);
if (!string_contains_char(stream->mode, 'r') && !string_contains_char(stream->mode, '+')) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Stream not readable");
return;
}
if ((contents = php_stream_copy_to_mem(stream, (size_t)PHP_STREAM_COPY_ALL, 0))) {
RETURN_STR(contents);
} else {
RETURN_EMPTY_STRING();
}
}
PHP_METHOD(Stream, getMetadata)
{
zval rv, fname, *resource, *zvalue;
zend_string *key = NULL;
resource = zend_read_property(HttpMessage_Stream_ce, PROPERTY_ARG(getThis()), ZEND_STRL("stream"), 0, &rv);
ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_STR(key)
ZEND_PARSE_PARAMETERS_END();
if (!IS_STREAM_RESOURCE(resource)) {
if (key == NULL) {
array_init(return_value);
} else {
RETVAL_NULL();
}
return;
}
ZVAL_STRING(&fname, "stream_get_meta_data");
call_user_function(NULL, NULL, &fname, return_value, 1, resource);
if (key != NULL) {
zvalue = zend_hash_find(Z_ARR(*return_value), key);
if (zvalue == NULL) {
ZVAL_NULL(return_value);
} else {
ZVAL_COPY(return_value, zvalue);
}
}
}
/* Define HttpMessage\Stream class */
static const zend_function_entry stream_functions[] = {
PHP_ME(Stream, __construct, arginfo_HttpMessageStream_construct, ZEND_ACC_PUBLIC)
HTTP_MESSAGE_ME(Stream, __toString)
HTTP_MESSAGE_ME(Stream, close)
HTTP_MESSAGE_ME(Stream, detach)
HTTP_MESSAGE_ME(Stream, getSize)
HTTP_MESSAGE_ME(Stream, tell)
HTTP_MESSAGE_ME(Stream, eof)
HTTP_MESSAGE_ME(Stream, isSeekable)
HTTP_MESSAGE_ME(Stream, seek)
HTTP_MESSAGE_ME(Stream, rewind)
HTTP_MESSAGE_ME(Stream, isWritable)
HTTP_MESSAGE_ME(Stream, write)
HTTP_MESSAGE_ME(Stream, isReadable)
HTTP_MESSAGE_ME(Stream, read)
HTTP_MESSAGE_ME(Stream, getContents)
HTTP_MESSAGE_ME(Stream, getMetadata)
PHP_FE_END
};
PHP_MINIT_FUNCTION(http_message_stream)
{
zend_class_entry ce;
zend_class_entry *interface = HTTP_MESSAGE_PSR_INTERFACE("stream");
ASSERT_HTTP_MESSAGE_INTERFACE_FOUND(interface, "Stream");
INIT_NS_CLASS_ENTRY(ce, "HttpMessage", "Stream", stream_functions);
HttpMessage_Stream_ce = zend_register_internal_class(&ce);
zend_class_implements(HttpMessage_Stream_ce, 1, interface);
/* Properties */
zend_declare_property_null(HttpMessage_Stream_ce, ZEND_STRL("stream"), ZEND_ACC_PRIVATE);
return SUCCESS;
}
#endif
|
def generate_prime(n):
for num in range(2, n+1):
# for each number, check if it is prime
for i in range(2, num):
if (num % i == 0):
break
else:
# print it if it is prime
print(num) |
#!/bin/bash -ex
HELM_VERSION="2.14.1"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR/../
export PATH="$PWD/testbin:$PATH"
if [ -x "$(command -v busybox)" ]; then
export IS_BUSYBOX=1
fi
main() {
if [ "$IS_BUSYBOX" != "1" ]; then
export HELM_HOME="$PWD/.helm"
install_helm
fi
package_test_charts
}
install_helm() {
if [ ! -f "testbin/helm" ]; then
mkdir -p testbin/
[ "$(uname)" == "Darwin" ] && PLATFORM="darwin" || PLATFORM="linux"
TARBALL="helm-v${HELM_VERSION}-${PLATFORM}-amd64.tar.gz"
wget "https://storage.googleapis.com/kubernetes-helm/${TARBALL}"
tar -C testbin/ -xzf $TARBALL
rm -f $TARBALL
pushd testbin/
UNCOMPRESSED_DIR="$(find . -mindepth 1 -maxdepth 1 -type d)"
mv $UNCOMPRESSED_DIR/helm .
rm -rf $UNCOMPRESSED_DIR
chmod +x ./helm
popd
helm init --client-only
# remove any repos that come out-of-the-box (i.e. "stable")
helm repo list | sed -n '1!p' | awk '{print $1}' | xargs helm repo remove
fi
}
package_test_charts() {
pushd testdata/charts/
for d in $(find . -maxdepth 1 -mindepth 1 -type d); do
pushd $d
helm package --sign --key helm-test --keyring ../../pgp/helm-test-key.secret .
popd
done
# add another version to repo for metric tests
helm package --sign --key helm-test --keyring ../pgp/helm-test-key.secret --version 0.2.0 -d mychart/ mychart/.
popd
}
main
|
<gh_stars>1-10
/*
* Copyright (c) 2017 <NAME>
*
* 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 net.kebernet.configuration.client.service;
import net.kebernet.configuration.client.model.Device;
import java.util.List;
/**
* Created by rcooper on 7/3/17.
*/
public interface DiscoveryService {
/**
* Adds a callback that will be notified whenever new devices are discovered.
* This will always occur asyncronously.
* @param callback Callback to receive notifications.
*/
void listenForDevices(DeviceListCallback callback);
/**
* Lists the currently discovered devices.
* This will always happen asyncronously.
* @param callback Callback for current known devices
*/
void listKnownDevices(DeviceListCallback callback);
/**
* Sets an error callback. This will provide messages that can be presented to the user
* when an error occurs inside the DiscoveryService service.
* @param callback ErrorCallback
*/
void setErrorCallback(ErrorCallback callback);
/**
* Refreshes/rediscovers devices. This will need to be called at startup.
*/
void refresh();
/**
* A callback for device lists.
*/
interface DeviceListCallback {
/**
* If this callback is being used as a listener
* the return value will indicate if the listener should continue listening.
* @param devices A list of recently discovered devices.
* @return "true" if the listener should continue to listen for more discoveries, or
* "false" if it is completed.
*/
boolean onDevices(List<Device> devices);
}
/**
* A callback that can be used to present the user with error messages about the
* internal state of the DiscoveryService services
*/
interface ErrorCallback{
/**
* @param message Message to present to user
*/
void onError(String message);
}
}
|
#!/bin/sh
docker run --rm -v /data -v /var/run/docker.sock:/docker.sock -t mirage:latest
|
#!/bin/sh
# wait-for-postgres.sh
set -e
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "db" -U "$POSTGRES_USER" -c '\q'; do
>&2 echo "Postgres is unavailable - sleeping"
sleep 1
done
>&2 echo "Postgres is up - executing command"
exec "$@" |
<gh_stars>1-10
import Vue from 'vue'
import DevelopApp from './dev/develop-app.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(DevelopApp)
}).$mount('#app')
|
from pycoop import Player, Task, Team
# Create players
alice = Player("Alice", {"coding": 8, "communication": 7}, 100)
bob = Player("Bob", {"coding": 9, "design": 6}, 120)
charlie = Player("Charlie", {"communication": 9, "design": 7}, 110)
# Create tasks
bug_fixing = Task("Bug Fixing", "coding", 30)
ui_design = Task("UI Design", "design", 25)
client_meeting = Task("Client Meeting", "communication", 20)
code_review = Task("Code Review", "coding", 35)
# Assign players to tasks
team = Team()
team.add_player(alice)
team.add_player(bob)
team.add_player(charlie)
team.assign_task(bug_fixing, alice)
team.assign_task(ui_design, bob)
team.assign_task(client_meeting, charlie)
team.assign_task(code_review, alice)
# Calculate team performance
total_skill_level = sum(player.get_skill_level() for player in team.get_assigned_players())
remaining_energy_levels = {player.get_name(): player.get_energy_level() for player in team.get_players()}
print("Total skill level of assigned players:", total_skill_level)
print("Remaining energy levels of players:", remaining_energy_levels) |
<gh_stars>1-10
package org.owasp.dependencycheck.analyzer;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.nodeaudit.Advisory;
import org.owasp.dependencycheck.data.nodeaudit.NpmAuditParser;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.Settings;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class PnpmAuditAnalyzerTest extends BaseTest
{
@Test
public void testNpmAuditParserCompatibility() throws IOException, JSONException
{
NpmAuditParser npmAuditParser = new NpmAuditParser();
JSONObject vulnsAuditJson = new JSONObject(IOUtils.toString(getResourceAsStream(this, "pnpmaudit/pnpm-audit.json"), "UTF-8"));
List<Advisory> advisories = npmAuditParser.parse(vulnsAuditJson);
assertThat(advisories.size(), is(2));
}
@Test
public void testSupportsFiles() {
PnpmAuditAnalyzer analyzer = new PnpmAuditAnalyzer();
assertThat(analyzer.accept(new File("package-lock.json")), is(false));
assertThat(analyzer.accept(new File("npm-shrinkwrap.json")), is(false));
assertThat(analyzer.accept(new File("yarn.lock")), is(false));
assertThat(analyzer.accept(new File("pnpm-lock.yaml")), is(true));
}
}
|
#!/bin/bash
# Copyright 2019 The Kubernetes 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.
# Tries to build all the executables to verify that they can in fact be built.
PACKAGES=(
"slack-event-log"
"slack-moderator"
"slack-report-message"
"slack-welcomer"
"slack-post-message"
)
go-build() {
target=$(mktemp)
pushd "./$1" > /dev/null
GO111MODULE=on go build -o "${target}"
ret=$?
popd > /dev/null
rm -f "${target}"
return ${ret}
}
ret=0
for pkg in "${PACKAGES[@]}"; do
go-build "${pkg}"
result=$?
if [[ ${result} -ne "0" ]]; then
echo "Failed to build ${pkg}"
ret=1
fi
done
exit ${ret}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.spiral = void 0;
var spiral = {
"viewBox": "0 0 24 24",
"children": [{
"name": "path",
"attribs": {
"d": "M12 11.8c1-.4.7-1.8 0-2.4-1.1-.9-2.7-.4-3.4.8-1.5 2.4.9 5 3.4 4.9 2.7-.2 4.3-2.9 3.7-5.4-.7-3-3.9-4.5-6.7-3.6-2.6.8-4.2 3.5-4 6.2.3 3 2.6 5.4 5.5 5.9 2.8.5 5.7-.8 7.2-3.2.7-1.1 1.2-2.4 1.2-3.8 0-.5.5-1 1.1-.9.8 0 1 .8.9 1.4-.4 4.7-4.5 8.6-9.3 8.6-5.9 0-10.5-6.2-8-11.8 2.5-5.4 10.3-6.5 13.3-1.2 1.5 2.5 1.2 5.8-.9 7.9-2 2-5.3 2.4-7.7.7-2.2-1.6-2.9-4.9-1.1-7.2 1.7-2.3 5.5-2.4 7 .2 1.1 1.9 0 5.2-2.5 4.9-1.6 0-3-1.7-2.1-3.2.6-.9 1.9-.6 2.3.1.2.8.1 1.1.1 1.1z"
},
"children": []
}]
};
exports.spiral = spiral; |
import React, { useState } from "react";
const LoginForm = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch("/api/login", {
method: "POST",
body: JSON.stringify({
username,
password,
}),
});
const data = await response.json();
if (data.success) {
// login successful
// proceed to homepage
} else {
// login failed
setError(data.message);
}
} catch (error) {
console.log(error);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<input
type="password"
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button type="submit">Log In</button>
{error ? <span>{error}</span> : null}
</form>
);
};
export default LoginForm; |
python setup.py install --home=./
cp lib/python/fastmmap.so fastmmap.so
|
import subprocess
# Install python-dotenv package
subprocess.run(['pip3', 'install', 'python-dotenv'])
# Copy files and set permissions
commands = [
['cp', '-pv', '/opt/tontgbot/sbot.sh', '/etc/init.d/tontgbot'],
['chmod', '-v', '+x', '/etc/init.d/tontgbot'],
['cp', '-pv', '/opt/tontgbot/tontgbot.service', '/etc/systemd/system'],
['chmod', '-v', '+x', '/opt/tontgbot/bot.py']
]
for cmd in commands:
result = subprocess.run(cmd)
if result.returncode == 0:
print(f"Command {' '.join(cmd)} executed successfully")
else:
print(f"Error executing command {' '.join(cmd)}")
# Download speedtest-cli and set permissions
subprocess.run(['wget', '-O', '/opt/tontgbot/speedtest-cli', 'https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py'])
subprocess.run(['chmod', '+x', '/opt/tontgbot/speedtest-cli'])
# Start service and check status
subprocess.run(['service', 'tontgbot', 'start'])
status = subprocess.run(['service', 'tontgbot', 'status'])
if status.returncode == 0:
print("tontgbot service started successfully")
else:
print("Error starting tontgbot service") |
#!/usr/bin/env bash
gcc -o demo main.c sum.c
|
class Player:
def refresh(self):
debug("REFRESH")
def read_input(self):
user_input = input("Input: ")
class MediaPlayer(Player):
def play_media(self, media_file):
print(f"Playing media: {media_file}")
def refresh(self):
super().refresh()
# Custom media player interface refresh logic here
def read_input(self):
super().read_input()
# Custom media player input capture logic here
# Usage
media_player = MediaPlayer()
media_player.play_media("example.mp3")
media_player.refresh()
media_player.read_input() |
<filename>fallen/Editor/Source/PrPiTab.cpp
#include "Editor.hpp"
#include "PrPiTab.hpp"
#include "engine.h"
#include "math.h"
#include "FileReq.hpp"
#include "c:\fallen\headers\io.h"
#include "c:\fallen\headers\memory.h"
//#include "collide.hpp" //needed for ele_shift
extern void matrix_transformZMY(Matrix31* result, Matrix33* trans, Matrix31* mat2);
extern void matrix_transform(struct Matrix31* result, struct Matrix33* trans,struct Matrix31* mat2);
extern void matrix_transform_small(struct Matrix31* result, struct Matrix33* trans,struct SMatrix31* mat2);
// static counter;
//#define ShowWorkWindow(x) {DrawLineC(0+(counter-1)&255,0,WorkWindowWidth-1,WorkWindowHeight-1,0);DrawLineC(0+(counter++)&255,0,WorkWindowWidth-1,WorkWindowHeight-1,255);DrawLineC(0,WorkWindowHeight-1,WorkWindowWidth-1,0,255); ShowWorkWindow(x);}
//---------------------------------------------------------------
//debug stuff
void cross_work_window(void)
{
DrawLineC(0,0,WorkWindowWidth-1,WorkWindowHeight-1,WHITE_COL);
DrawLineC(0,WorkWindowHeight-1,WorkWindowWidth-1,0,WHITE_COL);
}
extern void scan_apply_ambient(SLONG face,SLONG x,SLONG y,SLONG z,SLONG extra);
//---------------------------------------------------------------
#define CTRL_PRIM_LOAD_BACKGROUND 1
#define CTRL_PRIM_SAVE 2
#define CTRL_PRIM_X_AXIS_FREE 3
#define CTRL_PRIM_Y_AXIS_FREE 4
#define CTRL_PRIM_Z_AXIS_FREE 5
#define CTRL_PRIM_GRID_ON 6
#define CTRL_PRIM_ERASE_MAP 7
#define CTRL_PRIM_V_SLIDE_PRIM 8
#define CTRL_PRIM_MODE_MENU 9
#define CTRL_PRIM_MODE_TEXT 10
#define CTRL_PRIM_REPLACE 11
#define CTRL_PRIM_COLLIDE_NONE 12
#define CTRL_PRIM_COLLIDE_BOX 13
#define CTRL_PRIM_COLLIDE_CYLINDER 14
#define CTRL_PRIM_COLLIDE_SMALLBOX 15
#define CTRL_PRIM_SHADOW_NONE 16
#define CTRL_PRIM_SHADOW_BOXEDGE 17
#define CTRL_PRIM_SHADOW_CYLINDER 18
#define CTRL_PRIM_SHADOW_FOURLEGS 19
#define CTRL_PRIM_SHADOW_FULLBOX 20
#define CTRL_PRIM_FLAG_LAMPOST 21
#define CTRL_PRIM_FLAG_GLARE 22
#define CTRL_PRIM_GRID_MAX 23
#define CTRL_PRIM_GRID_CORNER 24
#define CTRL_PRIM_FLAG_ON_FLOOR 25
#define CTRL_PRIM_FLAG_TREE 26
#define CTRL_PRIM_VIEW_SIDE 27
#define CTRL_PRIM_FLAG_JUST_FLOOR 28
#define CTRL_PRIM_FLAG_INSIDE 29
#define CTRL_PRIM_GROW 30
#define CTRL_PRIM_SHRINK 31
#define CTRL_PRIM_DAMAGABLE 32
#define CTRL_PRIM_LEANS 33
#define CTRL_PRIM_CRUMPLES 34
#define CTRL_PRIM_EXPLODES 35
#define CTRL_PRIM_CENTRE_PIVOT 36
MenuDef2 prim_mode_menu[] =
{
{"Single Prims"},{"Multi Prims"},{"unused"},{"Anim Prims"},{"Morph Prims"},{"!"}
};
ControlDef prim_pick_tab_def[] =
{
{ BUTTON, 0, "Load A BackGround", 10, 473, 0, 0 },
{ BUTTON, 0, "Save selected prim", 10, 485, 0, 0 },
{ CHECK_BOX, 0, "X Free", 10, 310, 0, 10 },
{ CHECK_BOX, 0, "Y Free", 10, 323, 0, 10 },
{ CHECK_BOX, 0, "Z Free", 10, 336, 0, 10 },
{ CHECK_BOX, 0, "Grid Mode", 10, 362, 0, 10 },
{ BUTTON, 0, "Remove Prim", 190, 401, 0, 0 },
{ V_SLIDER, 0, "", 272, 40, 0, 257 },
{ PULLDOWN_MENU, 0, "Prim mode", 10, 10, 0, 0, prim_mode_menu},
{ STATIC_TEXT, 0, "Current mode : ", 10, 24, 0, 0 },
{ BUTTON, 0, "Replace Selected Prim" , 10, 460, 0, 0 },
{ CHECK_BOX, 0, "Collide none", 100, 310, 0, 10 },
{ CHECK_BOX, 0, "Collide box", 100, 323, 0, 10 },
{ CHECK_BOX, 0, "Collide cylinder", 100, 336, 0, 10 },
{ CHECK_BOX, 0, "Collide small box", 100, 349, 0, 10 },
{ CHECK_BOX, 0, "Shadow none", 190, 310, 0, 10 },
{ CHECK_BOX, 0, "Shadow box edge", 190, 323, 0, 10 },
{ CHECK_BOX, 0, "Shadow cylinder", 190, 336, 0, 10 },
{ CHECK_BOX, 0, "Shadow fourlegs", 190, 349, 0, 10 },
{ CHECK_BOX, 0, "Shadow full box", 190, 362, 0, 10 },
{ CHECK_BOX, 0, "Flag lampost", 100, 362, 0, 10 },
{ CHECK_BOX, 0, "Flag GLARE", 100, 375, 0, 10 },
{ CHECK_BOX, 0, "RHS", 10, 349, 0, 10 },
{ CHECK_BOX, 0, "Corners", 10, 375, 0, 10 },
{ CHECK_BOX, 0, "Flag on Roof/floor", 100, 388, 0, 10 },
{ CHECK_BOX, 0, "Flag tree", 100, 414, 0, 10 },
{ CHECK_BOX, 0, "Side View", 200, 440, 0, 10 },
{ CHECK_BOX, 0, "Flag on floor", 100, 401, 0, 10 },
{ CHECK_BOX, 0, "Inside", 200, 455, 0, 10 },
{ BUTTON, 0, "Grow", 140, 460, 0, 10 },
{ BUTTON, 0, "Shrink", 140, 473, 0, 10 },
{ CHECK_BOX, 0, "Damagable", 10, 395, 0, 10 },
{ CHECK_BOX, 0, "Leans", 10, 408, 0, 10 },
{ CHECK_BOX, 0, "Crumples", 10, 421, 0, 10 },
{ CHECK_BOX, 0, "Explodes", 10, 434, 0, 10 },
{ BUTTON, 0, "Centre Pivot", 140, 486, 0, 10 },
{ 0 }
};
PrimPickTab *the_primpicktab;
void redraw_all_prims(void);
UWORD prim_count[256];
UWORD prim_diff=0;
//---------------------------------------------------------------
/*
static SLONG angle_x=0;
void set_user_rotate(SLONG ax,SLONG ay,SLONG az)
{
angle_x=ax;
// Stop the compiler complaining.
ay = ay;
az = az;
}
void apply_user_rotates(struct PrimPoint *point)
{
SLONG rx,rz;
rx=point->X*COS(angle_x)-point->Z*SIN(angle_x);
rz=point->X*SIN(angle_x)+point->Z*COS(angle_x);
point->X=rx>>16;
point->Z=rz>>16;
}
*/
SLONG angle_prim_y=0;
void rotate_prim_thing(UWORD thing)
{
// anglex=map_things[thing].AngleY;
if(LastKey==KB_H)
{
LastKey=0;
angle_prim_y+=64;
angle_prim_y=((angle_prim_y+2048)&2047);
}
if(LastKey==KB_J)
{
LastKey=0;
angle_prim_y-=64;
angle_prim_y=((angle_prim_y+2048)&2047);
}
map_things[thing].AngleY=angle_prim_y;
/*
SLONG c0;
struct PrimObject *p_obj,*p_obj_o;
struct PrimPoint p;
SLONG sp,ep,offset_p;
p_obj =&prim_objects[map_things[thing].IndexOther];
p_obj_o =&prim_objects[map_things[thing].IndexOrig];
if( (p_obj->EndPoint-p_obj->StartPoint)!=(p_obj_o->EndPoint-p_obj_o->StartPoint) )
return;
sp=p_obj->StartPoint;
ep=p_obj->EndPoint;
offset_p=sp-p_obj_o->StartPoint;
if(LastKey==KB_H)
{
LastKey=0;
angle_x+=64;
angle_x=((angle_x+2048)&2047);
}
if(LastKey==KB_J)
{
LastKey=0;
angle_x-=64;
angle_x=((angle_x+2048)&2047);
}
for(c0=sp;c0<ep;c0++)
{
p=prim_points[c0-offset_p];
apply_user_rotates(&p);
prim_points[c0]=p;
}
map_things[thing].AngleX=angle_x;
*/
}
PrimPickTab::PrimPickTab(EditorModule *parent)
{
Parent=parent;
the_primpicktab=this;
PrimRect.SetRect(14,40,257,257);
InitControlSet(prim_pick_tab_def);
ListPos=0;
CurrentPrim=0;
UpdatePrimInfo();
AxisMode=3;
GridFlag=0;
GridMax=0;
GridCorner=0;
View2Mode=0;
PrimTabMode = PRIM_MODE_SINGLE;
SetControlState(CTRL_PRIM_X_AXIS_FREE,CTRL_SELECTED);
SetControlState(CTRL_PRIM_Y_AXIS_FREE,CTRL_SELECTED);
SetControlState(CTRL_PRIM_Z_AXIS_FREE,CTRL_SELECTED);
SetControlState(CTRL_PRIM_VIEW_SIDE, CTRL_DESELECTED);
((CVSlider*)GetControlPtr(CTRL_PRIM_V_SLIDE_PRIM))->SetValueRange(0,266/3);
((CVSlider*)GetControlPtr(CTRL_PRIM_V_SLIDE_PRIM))->SetCurrentValue(0);
((CVSlider*)GetControlPtr(CTRL_PRIM_V_SLIDE_PRIM))->SetUpdateFunction(redraw_all_prims);
Axis=X_AXIS|Y_AXIS|Z_AXIS;
PrimScale=2688;
BackScale=40;
UpdatePrimInfo();
}
PrimPickTab::~PrimPickTab()
{
UBYTE blah = 1;
}
//---------------------------------------------------------------
void PrimPickTab::UpdatePrimInfo(void)
{
//
// Checks/unchecks the collide buttons.
//
SetControlState(CTRL_PRIM_COLLIDE_NONE, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_COLLIDE_BOX, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_COLLIDE_CYLINDER, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_COLLIDE_SMALLBOX, CTRL_DESELECTED);
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
switch(prim_objects[CurrentPrim].coltype)
{
case PRIM_COLLIDE_NONE: SetControlState(CTRL_PRIM_COLLIDE_NONE, CTRL_SELECTED); break;
case PRIM_COLLIDE_BOX: SetControlState(CTRL_PRIM_COLLIDE_BOX, CTRL_SELECTED); break;
case PRIM_COLLIDE_CYLINDER: SetControlState(CTRL_PRIM_COLLIDE_CYLINDER, CTRL_SELECTED); break;
case PRIM_COLLIDE_SMALLBOX: SetControlState(CTRL_PRIM_COLLIDE_SMALLBOX, CTRL_SELECTED); break;
}
}
//
// Checks/unchecks the shadow buttons.
//
SetControlState(CTRL_PRIM_SHADOW_NONE, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_SHADOW_BOXEDGE, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_SHADOW_CYLINDER, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_SHADOW_FOURLEGS, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_SHADOW_FULLBOX, CTRL_DESELECTED);
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
switch(prim_objects[CurrentPrim].shadowtype)
{
case PRIM_SHADOW_NONE: SetControlState(CTRL_PRIM_SHADOW_NONE, CTRL_SELECTED); break;
case PRIM_SHADOW_BOXEDGE: SetControlState(CTRL_PRIM_SHADOW_BOXEDGE, CTRL_SELECTED); break;
case PRIM_SHADOW_CYLINDER: SetControlState(CTRL_PRIM_SHADOW_CYLINDER, CTRL_SELECTED); break;
case PRIM_SHADOW_FOURLEGS: SetControlState(CTRL_PRIM_SHADOW_FOURLEGS, CTRL_SELECTED); break;
case PRIM_SHADOW_FULLBOX: SetControlState(CTRL_PRIM_SHADOW_FULLBOX, CTRL_SELECTED); break;
}
}
//
// The prim flags.
//
SetControlState(CTRL_PRIM_FLAG_LAMPOST, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_FLAG_GLARE, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_FLAG_ON_FLOOR, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_FLAG_TREE, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_FLAG_JUST_FLOOR, CTRL_DESELECTED);
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
if (prim_objects[CurrentPrim].flag & PRIM_FLAG_LAMPOST ) {SetControlState(CTRL_PRIM_FLAG_LAMPOST, CTRL_SELECTED);}
if (prim_objects[CurrentPrim].flag & PRIM_FLAG_GLARE) {SetControlState(CTRL_PRIM_FLAG_GLARE, CTRL_SELECTED);}
if (prim_objects[CurrentPrim].flag & PRIM_FLAG_ON_FLOOR) {SetControlState(CTRL_PRIM_FLAG_ON_FLOOR, CTRL_SELECTED);}
if (prim_objects[CurrentPrim].flag & PRIM_FLAG_JUST_FLOOR) {SetControlState(CTRL_PRIM_FLAG_JUST_FLOOR, CTRL_SELECTED);}
if (prim_objects[CurrentPrim].flag & PRIM_FLAG_TREE) {SetControlState(CTRL_PRIM_FLAG_TREE, CTRL_SELECTED);}
}
if (edit_info.Inside )
{
SetControlState(CTRL_PRIM_FLAG_INSIDE, CTRL_SELECTED);
}
else
{
SetControlState(CTRL_PRIM_FLAG_INSIDE, CTRL_DESELECTED);
}
//
// Checks/unchecks the damageable flags.
//
SetControlState(CTRL_PRIM_DAMAGABLE, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_LEANS, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_CRUMPLES, CTRL_DESELECTED);
SetControlState(CTRL_PRIM_EXPLODES, CTRL_DESELECTED);
if (prim_objects[CurrentPrim].damage & PRIM_DAMAGE_DAMAGABLE)
{
SetControlState(CTRL_PRIM_DAMAGABLE, CTRL_SELECTED);
if (prim_objects[CurrentPrim].damage & PRIM_DAMAGE_LEAN) {SetControlState(CTRL_PRIM_LEANS, CTRL_SELECTED);}
if (prim_objects[CurrentPrim].damage & PRIM_DAMAGE_CRUMPLE) {SetControlState(CTRL_PRIM_CRUMPLES, CTRL_SELECTED);}
if (prim_objects[CurrentPrim].damage & PRIM_DAMAGE_EXPLODES) {SetControlState(CTRL_PRIM_EXPLODES, CTRL_SELECTED);}
}
//
// This crashes?!...
//
// ((CStaticText*)GetControlPtr(CTRL_PRIM_MODE_TEXT))->SetString1(prim_mode_menu[PrimTabMode].ItemText);
}
//---------------------------------------------------------------
void PrimPickTab::DrawTabContent(void)
{
EdRect content_rect;
if(PrimTabMode==PRIM_MODE_SINGLE)
((CVSlider*)GetControlPtr(CTRL_PRIM_V_SLIDE_PRIM))->SetValueRange(0,266/3);
else
((CVSlider*)GetControlPtr(CTRL_PRIM_V_SLIDE_PRIM))->SetValueRange(0,next_prim_multi_object+9);
content_rect = ContentRect;
content_rect.ShrinkRect(1,1);
content_rect.FillRect(CONTENT_COL);
// ShowAngles();
/*
if(ValueButton)
ValueButton->DrawValueGadget();
*/
DrawPrims();
DrawControlSet();
}
//---------------------------------------------------------------
void PrimPickTab::DrawAPrimInRect(ULONG prim,SLONG x,SLONG y,SLONG w,SLONG h)
{
CBYTE *text;
SLONG *flags; //[560];
struct SVector *res; //[560]; //max points per object?
SLONG c0;
struct PrimObject *p_obj;
SLONG sp,ep;
SLONG min_x=999999,max_x=-999999,min_y=999999,max_y=-999999;
SLONG width,height,scale,scale_y;
EdRect rect;
SLONG os;
flags=(SLONG*)MemAlloc(sizeof(SLONG)*13000);
if(flags==0)
return;
res=(struct SVector*)MemAlloc(sizeof(struct SVector)*13000);
if(res==0)
{
MemFree(flags);
return;
}
os=engine.Scale;
engine.Scale=1000;
//set clip to content window
SetWorkWindowBounds (
ContentLeft()+PrimRect.GetLeft()+x+1,
ContentTop()+PrimRect.GetTop()+y+1,
w,
h
);
rect.SetRect(0,0,w,h);
if(prim==CurrentPrim)
rect.FillRect(LOLITE_COL);
// rect.HiliteRect(LOLITE_COL,LOLITE_COL);
// SetWorkWindowBounds(ContentLeft()+x,ContentTop()+y,w,h);
/*
SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1);
rect.SetRect(x,y,w,h);
if(prim==CurrentPrim)
rect.FillRect(HILITE_COL);
else
rect.FillRect(LOLITE_COL);
rect.HiliteRect(LOLITE_COL,LOLITE_COL);
SetWorkWindowBounds(ContentLeft()+x,ContentTop()+y,w,h);
*/
set_camera();
// p_rect->FillRect(CONTENT_COL);
p_obj =&prim_objects[prim];
sp=p_obj->StartPoint;
ep=p_obj->EndPoint;
for(c0=sp;c0<ep;c0++)
{
struct SVector pp;
pp.X=prim_points[c0].X;
pp.Y=prim_points[c0].Y;
pp.Z=prim_points[c0].Z;
//transform all points for this Object
flags[c0-sp]=rotate_point_gte(&pp,&res[c0-sp]);
if(res[c0-sp].X<min_x)
min_x=res[c0-sp].X;
if(res[c0-sp].X>max_x)
max_x=res[c0-sp].X;
if(res[c0-sp].Y<min_y)
min_y=res[c0-sp].Y;
if(res[c0-sp].Y>max_y)
max_y=res[c0-sp].Y;
}
width=max_x-min_x;
height=max_y-min_y;
if(width==0||height==0)
{
}
else
{
CBYTE str[100];
scale =(w<<16)/width;
scale_y=(h<<16)/height;
if(scale_y<scale)
scale=scale_y;
scale=(scale*200)>>8;
engine.Scale=(1000*scale)>>16;
draw_a_prim_at(prim,0,0,0,0);
render_view(1);
text = prim_names[prim];
sprintf(str,"(%d,%d) %s",prim,prim<256?prim_count[prim]:0,text);
DrawBoxC(rect.GetLeft()+1,rect.GetTop()+1,QTStringWidth(text),QTStringHeight()+1,0);
QuickText(rect.GetLeft()+1,rect.GetTop()+1,str,TEXT_COL);
rect.OutlineRect(0);
}
engine.Scale=os;
MemFree(res);
MemFree(flags);
}
void PrimPickTab::DrawABuildingInRect(ULONG prim,SLONG x,SLONG y,SLONG w,SLONG h)
{
CBYTE *text;
SLONG *flags; //[560];
struct SVector *res; //[560]; //max points per object?
SLONG c0;
struct BuildingObject *p_obj;
SLONG sp,ep;
SLONG min_x=999999,max_x=-999999,min_y=999999,max_y=-999999;
SLONG width,height,scale,scale_y;
EdRect rect;
SLONG os;
flags=(SLONG*)MemAlloc(sizeof(SLONG)*3000);
if(flags==0)
return;
res=(struct SVector*)MemAlloc(sizeof(struct SVector)*3000);
if(res==0)
{
MemFree(flags);
return;
}
os=engine.Scale;
engine.Scale=1000;
SetWorkWindowBounds (
ContentLeft()+PrimRect.GetLeft()+x+1,
ContentTop()+PrimRect.GetTop()+y+1,
w,
h
);
rect.SetRect(0,0,w,h);
if(prim==CurrentPrim)
rect.FillRect(LOLITE_COL);
set_camera();
p_obj =&building_objects[prim];
sp=p_obj->StartPoint;
ep=p_obj->EndPoint;
LogText(" build in rect prim %d sp %d ep %d \n",prim,sp,ep);
for(c0=sp;c0<ep;c0++)
{
struct SVector pp;
pp.X=prim_points[c0].X;
pp.Y=prim_points[c0].Y;
pp.Z=prim_points[c0].Z;
//transform all points for this Object
flags[c0-sp]=rotate_point_gte(&pp,&res[c0-sp]);
if(res[c0-sp].X<min_x)
min_x=res[c0-sp].X;
if(res[c0-sp].X>max_x)
max_x=res[c0-sp].X;
if(res[c0-sp].Y<min_y)
min_y=res[c0-sp].Y;
if(res[c0-sp].Y>max_y)
max_y=res[c0-sp].Y;
}
width=max_x-min_x;
height=max_y-min_y;
LogText(" build widh %d height %d \n",width,height);
if(width==0||height==0)
{
}
else
{
scale =(w<<16)/width;
scale_y=(h<<16)/height;
if(scale_y<scale)
scale=scale_y;
scale=(scale*200)>>8;
engine.Scale=(1000*scale)>>16;
draw_a_building_at(prim,0,0,0);
render_view(1);
// text = prim_objects[prim].ObjectName;
// DrawBoxC(rect.GetLeft()+1,rect.GetTop()+1,QTStringWidth(text),QTStringHeight()+1,0);
// QuickText(rect.GetLeft()+1,rect.GetTop()+1,text,TEXT_COL);
rect.OutlineRect(0);
engine.Scale=os;
}
MemFree(res);
MemFree(flags);
}
//---------------------------------------------------------------
void PrimPickTab::DrawAMultiPrimInRect(ULONG prim,SLONG x,SLONG y,SLONG w,SLONG h)
{
SLONG c0,c1,c2,
num_points,
max_x,max_y,
min_x,min_y,
end_point,
scale,
scale_y,
start_point,
temp_scale,
temp_x,
temp_y,
temp_z,
width,height,
*flags;
EdRect bounds_rect,
outline_rect;
struct KeyFrame *the_frame;
struct KeyFrameElement *the_element;
struct Matrix31 offset;
struct Matrix33 r_matrix;
struct PrimObject *the_obj;
struct SVector *rotate_vectors,
t_vector,
t_vector2;
// This bit bodged in for now.
extern struct KeyFrameChunk *test_chunk;
if(!test_chunk->MultiObject)
return;
the_frame = &test_chunk->KeyFrames[0];
//
c1 = 0;
flags = (SLONG*)MemAlloc(sizeof(SLONG)*3000);
ERROR_MSG(flags,"Unable to allocate memory for DrawKeyFrame");
rotate_vectors = (struct SVector*)MemAlloc(sizeof(struct SVector)*3000);
ERROR_MSG(flags,"Unable to allocate memory for DrawKeyFrame");
min_x = min_y = 999999;
max_x = max_y = -999999;
temp_scale = engine.Scale;
temp_x = engine.X;
temp_y = engine.Y;
temp_z = engine.Z;
engine.X = 0;
engine.Y = 0;
engine.Z = 0;
engine.Scale = 5000;
engine.ShowDebug= 0;
engine.BucketSize= MAX_BUCKETS>>4;
SetWorkWindowBounds (
ContentLeft()+PrimRect.GetLeft()+x+1,
ContentTop()+PrimRect.GetTop()+y+1,
w,
h
);
bounds_rect.SetRect(0,0,w,h);
if(prim==CurrentPrim)
bounds_rect.FillRect(LOLITE_COL);
/*
outline_rect.SetRect(
0,0,
bounds_rect.GetWidth(),bounds_rect.GetHeight()
);
*/
set_camera();
set_camera_to_base();
rotate_obj(0,0,0,&r_matrix);
for(c2=0,c0=prim_multi_objects[prim].StartObject;c0<prim_multi_objects[prim].EndObject;c0++)
{
the_obj = &prim_objects[c0];
start_point = the_obj->StartPoint;
end_point = the_obj->EndPoint;
num_points = end_point-start_point;
the_element = &the_frame->FirstElement[c2++];
offset.M[0] = the_element->OffsetX;
offset.M[1] = the_element->OffsetY;
offset.M[2] = the_element->OffsetZ;
matrix_transformZMY((struct Matrix31*)&t_vector,&r_matrix, &offset);
engine.X -= t_vector.X<<8;
engine.Y -= t_vector.Y<<8;
engine.Z -= t_vector.Z<<8;
for(c1=0;c1<num_points;c1++)
{
matrix_transform_small((struct Matrix31*)&t_vector2,&r_matrix,(struct SMatrix31*)&prim_points[c1]);
flags[c1] = rotate_point_gte(&t_vector2,&rotate_vectors[c1]);
if(rotate_vectors[c1].X<min_x)
min_x = rotate_vectors[c1].X;
if(rotate_vectors[c1].X>max_x)
max_x = rotate_vectors[c1].X;
if(rotate_vectors[c1].Y<min_y)
min_y = rotate_vectors[c1].Y;
if(rotate_vectors[c1].Y>max_y)
max_y = rotate_vectors[c1].Y;
}
engine.X += t_vector.X<<8;
engine.Y += t_vector.Y<<8;
engine.Z += t_vector.Z<<8;
}
width = max_x-min_x;
height = max_y-min_y;
if(width>0 && height>0)
{
scale = (bounds_rect.GetWidth()<<16)/width;
scale_y = (bounds_rect.GetHeight()<<16)/height;
if(scale_y<scale)
scale = scale_y;
scale = (scale*900)>>8;
engine.Scale = (5000*scale)>>16;
}
for(c2=0,c0=prim_multi_objects[prim].StartObject;c0<prim_multi_objects[prim].EndObject;c0++)
{
the_element = &the_frame->FirstElement[c2++];
test_draw(c0,0,0,0,0,the_element,the_element,&r_matrix, NULL, NULL, NULL, NULL, NULL);
}
render_view(1);
bounds_rect.OutlineRect(0);
engine.X = temp_x;
engine.Y = temp_y;
engine.Z = temp_z;
engine.Scale = temp_scale;
engine.ShowDebug= 1;
engine.BucketSize= MAX_BUCKETS;
MemFree(rotate_vectors);
MemFree(flags);
}
//---------------------------------------------------------------
// for both views
SLONG PrimPickTab::HiLightObjects(SLONG x,SLONG y,SLONG w,SLONG h)
{
SLONG mx,my,mz;
SLONG screen_change=0;
SLONG wwx,wwy,www,wwh;
wwx=WorkWindowRect.Left;
wwy=WorkWindowRect.Top;
www=WorkWindowRect.Width;
wwh=WorkWindowRect.Height;
mx=(engine.X>>8)>>ELE_SHIFT;
my=(engine.Y>>8)>>ELE_SHIFT;
mz=(engine.Z>>8)>>ELE_SHIFT;
SetWorkWindowBounds(x,y,w-1,h/2-3);
set_camera_plan();
screen_change=hilight_map_things(MAP_THING_TYPE_PRIM);
screen_change|=hilight_map_things(MAP_THING_TYPE_ANIM_PRIM);
SetWorkWindowBounds(x,y+h/2+4,w-1,h/2-4);
if(View2Mode)
{
set_camera_side();
}
else
{
set_camera_front();
}
screen_change|=hilight_map_things(MAP_THING_TYPE_PRIM);
screen_change|=hilight_map_things(MAP_THING_TYPE_ANIM_PRIM);
SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT
return(screen_change);
}
void PrimPickTab::DrawModuleContent(SLONG x,SLONG y,SLONG w,SLONG h)
{
SLONG wwx,
wwy,
www,
wwh;
EdRect drawrect;
RedrawModuleContent=0;
// Back up clipping rect.
wwx = WorkWindowRect.Left;
wwy = WorkWindowRect.Top;
www = WorkWindowRect.Width;
wwh = WorkWindowRect.Height;
/*
View1.SetRect(x,y,w-1,h/2-8);
View2.SetRect(x,y+h/2+8,w-1,h/2-16);
SetWorkWindowBounds (
View1.GetLeft(),
View1.GetTop(),
View1.GetWidth(),
View1.GetHeight()
);
View1.FillRect(CONTENT_COL);
View1.OutlineRect(0);
SetWorkWindowBounds (
View2.GetLeft(),
View2.GetTop(),
View2.GetWidth(),
View2.GetHeight()
);
View2.FillRect(CONTENT_COL);
View2.OutlineRect(0);
*/
View1.SetRect(x,y,w-1,h/2-3);
View2.SetRect(x,y+h/2+4,w-1,h/2-4);
SetWorkWindowBounds(x,y,w-1,h/2-3);
drawrect.SetRect(0,0,w-1,h/2-3);
drawrect.FillRect(CONTENT_COL_BR);
drawrect.HiliteRect(HILITE_COL,HILITE_COL);
set_camera_plan();
extern void find_map_clip(SLONG *minx,SLONG *maxx,SLONG *minz,SLONG *maxz);
{
SLONG minx,maxx,minz,maxz;
find_map_clip(&minx,&maxx,&minz,&maxz);
edit_info.MinX=minx;
edit_info.MinZ=minz;
edit_info.MaxX=maxx;
edit_info.MaxZ=maxz;
edit_info.Clipped|=1;
}
draw_editor_map(0);
render_view(1);
switch(PrimTabMode)
{
case PRIM_MODE_SINGLE:
case PRIM_MODE_MULTI:
case PRIM_MODE_ANIM_KEY:
case PRIM_MODE_ANIM_MORPH:
hilight_map_things(MAP_THING_TYPE_PRIM);
hilight_map_things(MAP_THING_TYPE_ANIM_PRIM);
break;
// case PRIM_MODE_BACK:
// hilight_map_backgrounds(0);
break;
}
SetWorkWindowBounds(x,y+h/2+4,w-1,h/2-4);
drawrect.SetRect(0,0,w-1,h/2-4);
// drawrect.FillRect(LOLITE_COL);
drawrect.FillRect(CONTENT_COL_BR);
drawrect.HiliteRect(HILITE_COL,HILITE_COL);
if(View2Mode)
{
set_camera_side();
}
else
{
set_camera_front();
}
draw_editor_map(0);
render_view(1);
switch(PrimTabMode)
{
case PRIM_MODE_SINGLE:
case PRIM_MODE_MULTI:
case PRIM_MODE_ANIM_KEY:
case PRIM_MODE_ANIM_MORPH:
hilight_map_things(MAP_THING_TYPE_PRIM);
hilight_map_things(MAP_THING_TYPE_ANIM_PRIM);
break;
// case PRIM_MODE_BACK:
// hilight_map_backgrounds(0);
break;
}
{
CBYTE str[50];
sprintf(str, "Current prim %d", CurrentPrim);
QuickTextC(10, 40, str, RED_COL);
QuickTextC(11, 41, str, WHITE_COL);
}
// Restore clipping rect.
SetWorkWindowBounds(wwx,wwy,www,wwh);
edit_info.Clipped&=~1;
}
void PrimPickTab::DrawPrims(void)
{
SLONG ox,oy,oz,x,y,prim=1;
SLONG wwx,wwy,www,wwh;
SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1);
PrimRect.FillRect(ACTIVE_COL);
PrimRect.HiliteRect(LOLITE_COL,HILITE_COL);
{
SLONG c0;
memset(prim_count,0,512);
prim_diff=0;
for(c0=0;c0<MAX_MAP_THINGS;c0++)
{
struct MapThing *t_mthing;
t_mthing=&map_things[c0];
switch(t_mthing->Type)
{
case MAP_THING_TYPE_PRIM:
if(t_mthing->IndexOther<256)
{
prim_count[t_mthing->IndexOther]++;
if(prim_count[t_mthing->IndexOther]==1)
prim_diff++;
}
break;
}
}
}
{
CBYTE str[100];
sprintf(str," %d..%d DIFFERENT PRIMS %d",next_prim_point,MAX_PRIM_POINTS,prim_diff);
QuickTextC(1,1,str,0);
}
wwx=WorkWindowRect.Left;
wwy=WorkWindowRect.Top;
www=WorkWindowRect.Width;
wwh=WorkWindowRect.Height;
// SetWorkWindowBounds(PrimRect.GetLeft()+1,PrimRect.GetTop()+1,PrimRect.GetWidth()-1,PrimRect.GetHeight()-1);
// PrimRect.FillRect(CONTENT_COL);
// PrimRect.HiliteRect(LOLITE_COL,LOLITE_COL);
ox=engine.X;
oy=engine.Y;
oz=engine.Z;
engine.X=0;
engine.Y=0;
engine.Z=0;
engine.ShowDebug=0;
engine.BucketSize=MAX_BUCKETS>>4;
prim = (((CVSlider*)GetControlPtr(CTRL_PRIM_V_SLIDE_PRIM))->GetCurrentValue()*3)+1;
if(PrimTabMode==PRIM_MODE_ANIM_KEY)
{
EdRect frame_rect,rect;
struct Matrix33 r_matrix;
rotate_obj(0,0,0,&r_matrix);
for(y=1;y<255;y+=85)
for(x=1;x<255;x+=85)
{
SetWorkWindowBounds (ContentLeft()+PrimRect.GetLeft()+x+1,
ContentTop()+PrimRect.GetTop()+y+1,
85,85);
rect.SetRect(0,0,85,85);
if(prim==CurrentPrim)
rect.FillRect(LOLITE_COL);
extern void drawkeyframeboxgamechunk(UWORD multi_object,EdRect *bounds_rect,struct GameKeyFrame *the_frame,struct Matrix33 *r_matrix,SLONG person_id,struct GameKeyFrameChunk *the_chunk);
if(anim_chunk[prim].MultiObject[0])
drawkeyframeboxgamechunk(anim_chunk[prim].MultiObject[0],&rect,anim_chunk[prim].AnimList[1],&r_matrix,0,&anim_chunk[prim]);
prim++;
}
}
else
if(PrimTabMode==PRIM_MODE_SINGLE)
{
EdRect frame_rect,rect;
struct Matrix33 r_matrix;
rotate_obj(0,0,0,&r_matrix);
for(y=1;y<255;y+=85)
for(x=1;x<255;x+=85)
{
if(prim < next_prim_object)
DrawAPrimInRect(prim++,x,y,85,85);
}
}
else
{
for(y=1;y<255;y+=85)
for(x=1;x<255;x+=85)
{
if(prim < next_prim_multi_object)
DrawAMultiPrimInRect(prim++,x,y,85,85);
}
}
engine.ShowDebug=1;
engine.BucketSize=MAX_BUCKETS;
// draw_a_prim_at(3,0,0,0);
engine.X=ox;
engine.Y=oy;
engine.Z=oz;
/*
{
SetWorkWindowBounds(ContentLeft(),ContentTop(),300,300);
CBYTE str[100];
sprintf(str,"CURRENT_PRIM= %d dtv1 %d dtv2 %d x %d y %d z %d",CurrentPrim,DragThingView1,DragThingView2,engine.MousePosX,engine.MousePosY,engine.MousePosZ);
DrawBox(20,20,300,10,0);
QuickTextC(20+1,20+1,str,255);
}
*/
SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT
RedrawTabContent=0;
}
void PrimPickTab::UpdatePrimPickWindow(void)
{
if(LockWorkScreen())
{
DrawControlSet();
DrawPrims();
UnlockWorkScreen();
}
ShowWorkWindow(0);
}
void redraw_all_prims(void)
{
the_primpicktab->DrawTabContent();
}
//---------------------------------------------------------------
void PrimPickTab::HandleTab(MFPoint *current_point)
{
SLONG update = 0;
ModeTab::HandleTab(current_point);
/*
if(Keys[KB_PMINUS])
{
if(TextureZoom<8)
{
TextureZoom++;
update = 1;
}
}
else if(Keys[KB_PPLUS])
{
if(TextureZoom>0)
{
TextureZoom--;
update = 1;
}
}
if(Keys[KB_P4])
{
if(TextureX>0)
{
TextureX--;
update = 1;
}
}
else if(Keys[KB_P6])
{
if(TextureX<(256-(1<<TextureZoom)))
{
TextureX++;
update = 1;
}
}
if(Keys[KB_P8])
{
if(TextureY>0)
{
TextureY--;
update = 1;
}
}
else if(Keys[KB_P2])
{
if(TextureY<(256-(1<<TextureZoom)))
{
TextureY++;
update = 1;
}
}
*/
if(Keys[KB_U])
{
Keys[KB_U]=0;
MyUndo.DoUndo(ShiftFlag?1:0);
RedrawModuleContent=1;
}
if(RedrawTabContent||update)
{
UpdatePrimPickWindow();
}
KeyboardInterface();
}
inline SLONG is_point_in_box(SLONG x,SLONG y,SLONG left,SLONG top,SLONG w,SLONG h)
{
if(x>left&&x<left+w&&y>top&&y<top+h)
return(1);
else
return(0);
}
//---------------------------------------------------------------
SLONG PrimPickTab::KeyboardInterface(void)
{
if(Keys[KB_TAB])
{
Keys[KB_TAB]=0;
AxisMode++;
if(AxisMode>3)
AxisMode=0;
switch(AxisMode)
{
case 0:
SetControlState(CTRL_PRIM_X_AXIS_FREE,CTRL_SELECTED);
SetControlState(CTRL_PRIM_Y_AXIS_FREE,CTRL_DESELECTED);
SetControlState(CTRL_PRIM_Z_AXIS_FREE,CTRL_DESELECTED);
Axis=X_AXIS;
break;
case 1:
SetControlState(CTRL_PRIM_X_AXIS_FREE,CTRL_DESELECTED);
SetControlState(CTRL_PRIM_Y_AXIS_FREE,CTRL_SELECTED);
SetControlState(CTRL_PRIM_Z_AXIS_FREE,CTRL_DESELECTED);
Axis=Y_AXIS;
break;
case 2:
SetControlState(CTRL_PRIM_X_AXIS_FREE,CTRL_DESELECTED);
SetControlState(CTRL_PRIM_Y_AXIS_FREE,CTRL_DESELECTED);
SetControlState(CTRL_PRIM_Z_AXIS_FREE,CTRL_SELECTED);
Axis=Z_AXIS;
break;
case 3:
SetControlState(CTRL_PRIM_X_AXIS_FREE,CTRL_SELECTED);
SetControlState(CTRL_PRIM_Y_AXIS_FREE,CTRL_SELECTED);
SetControlState(CTRL_PRIM_Z_AXIS_FREE,CTRL_SELECTED);
Axis=X_AXIS|Y_AXIS|Z_AXIS;
break;
}
SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1);
DrawControlSet();
ShowWorkWindow(0);
}
return(0);
}
void find_things_min_point(SLONG drag,SLONG *px,SLONG *py,SLONG *pz)
{
SLONG c0;
SLONG mx,my,mz;
*px=99999;
*py=99999;
*pz=99999;
if(drag)
{
SLONG sp,ep;
sp=prim_objects[drag].StartPoint;
ep=prim_objects[drag].EndPoint;
for(c0=sp;c0<ep;c0++)
{
if(prim_points[c0].X<*px)
*px=prim_points[c0].X;
if(prim_points[c0].Y<*py)
*py=prim_points[c0].Y;
if(prim_points[c0].Z<*pz)
*pz=prim_points[c0].Z;
}
}
}
void find_things_max_point(SLONG drag,SLONG *px,SLONG *py,SLONG *pz)
{
SLONG c0;
SLONG mx,my,mz;
*px=-99999;
*py=-99999;
*pz=-99999;
if(drag)
{
SLONG sp,ep;
sp=prim_objects[drag].StartPoint;
ep=prim_objects[drag].EndPoint;
for(c0=sp;c0<ep;c0++)
{
if(prim_points[c0].X>*px)
*px=prim_points[c0].X;
if(prim_points[c0].Y>*py)
*py=prim_points[c0].Y;
if(prim_points[c0].Z>*pz)
*pz=prim_points[c0].Z;
}
}
}
void find_things_min_point_corner(SLONG drag,SLONG *px,SLONG *py,SLONG *pz)
{
SLONG c0;
SLONG mx,my,mz;
SLONG dist,mdist=99999,best=0;
*py=99999;
if(drag)
{
SLONG sp,ep;
sp=prim_objects[drag].StartPoint;
ep=prim_objects[drag].EndPoint;
for(c0=sp;c0<ep;c0++)
{
if(prim_points[c0].Y<*py)
*py=prim_points[c0].Y;
dist=prim_points[c0].X+prim_points[c0].Z;
if(dist<mdist)
{
mdist=dist;
best=c0;
}
}
}
if(best)
{
*px=prim_points[best].X;
// *py=prim_points[best].Y;
*pz=prim_points[best].Z;
}
}
void find_things_max_point_corner(SLONG drag,SLONG *px,SLONG *py,SLONG *pz)
{
SLONG c0;
SLONG mx,my,mz;
SLONG dist,mdist=-99999,best=0;
*py=-99999;
if(drag)
{
SLONG sp,ep;
sp=prim_objects[drag].StartPoint;
ep=prim_objects[drag].EndPoint;
for(c0=sp;c0<ep;c0++)
{
if(prim_points[c0].Y>*py)
*py=prim_points[c0].Y;
dist=prim_points[c0].X+prim_points[c0].Z;
if(dist>mdist)
{
mdist=dist;
best=c0;
}
}
}
if(best)
{
*px=prim_points[best].X;
// *py=prim_points[best].Y;
*pz=prim_points[best].Z;
}
}
//
// button 0 is left
// button 1 is right (for creating a new prim identical to the last
SLONG PrimPickTab::DragAPrim(UBYTE flags,MFPoint *clicked_point,SLONG button)
{
static UBYTE col=0;
SLONG screen_change=0;
MFPoint local_point;
SLONG x,y,w,h;
SLONG drag;
SLONG wwx,wwy,www,wwh;
SLONG ox,oy,oz;
SLONG px=0,py=0,pz=0;
// Stop compiler moaning.
flags = flags;
wwx=WorkWindowRect.Left;
wwy=WorkWindowRect.Top;
www=WorkWindowRect.Width;
wwh=WorkWindowRect.Height;
x=Parent->ContentLeft();
y=Parent->ContentTop();
w=Parent->ContentWidth();
h=Parent->ContentHeight();
col++;
SetWorkWindowBounds(x,y,w-1,h/2-3);
set_camera_plan();
local_point = *clicked_point;
/*
switch(PrimTabMode)
{
case PRIM_MODE_SINGLE:
drag=select_map_things(clicked_point,MAP_THING_TYPE_PRIM);
break;
case PRIM_MODE_MULTI:
break;
case PRIM_MODE_SINGLE:
case PRIM_MODE_ANIM_KEY:
case PRIM_MODE_ANIM_MORPH:
drag=select_map_things(clicked_point,MAP_THING_TYPE_PRIM);
if(drag==0)
drag=select_map_things(clicked_point,MAP_THING_TYPE_ANIM_PRIM);
break;
// case PRIM_MODE_BACK:
// drag=select_map_backgrounds(clicked_point,0);
break;
}
*/
extern void find_map_clip(SLONG *minx,SLONG *maxx,SLONG *minz,SLONG *maxz);
{
SLONG minx,maxx,minz,maxz;
find_map_clip(&minx,&maxx,&minz,&maxz);
edit_info.MinX=minx;
edit_info.MinZ=minz;
edit_info.MaxX=maxx;
edit_info.MaxZ=maxz;
edit_info.Clipped|=1;
}
drag=select_map_things(clicked_point,MAP_THING_TYPE_PRIM);
if(drag==0)
drag=select_map_things(clicked_point,MAP_THING_TYPE_ANIM_PRIM);
if(!drag)
{
SetWorkWindowBounds(x,y+h/2+4,w-1,h/2-4);
if(View2Mode)
{
set_camera_side();
}
else
{
set_camera_front();
}
local_point =*clicked_point;
local_point.Y-=h/2;
drag=select_map_things(&local_point,MAP_THING_TYPE_PRIM);
if(drag==0)
drag=select_map_things(&local_point,MAP_THING_TYPE_ANIM_PRIM);
/*
switch(PrimTabMode)
{
case PRIM_MODE_SINGLE:
case PRIM_MODE_MULTI:
case PRIM_MODE_ANIM_KEY:
case PRIM_MODE_ANIM_MORPH:
drag=select_map_things(&local_point,MAP_THING_TYPE_PRIM);
if(drag==0)
drag=select_map_things(&local_point,MAP_THING_TYPE_ANIM_PRIM);
break;
// case PRIM_MODE_BACK:
// drag=select_map_backgrounds(&local_point,0);
break;
}
*/
}
if(drag)
{
SLONG index;
index=map_things[drag].IndexOther;
if(GridCorner)
{
if(GridMax)
{
find_things_max_point_corner(index,&px,&py,&pz);
}
else
{
find_things_min_point_corner(index,&px,&py,&pz);
}
}
else
{
if(GridMax)
{
find_things_max_point(index,&px,&py,&pz);
}
else
{
find_things_min_point(index,&px,&py,&pz);
}
}
}
engine.MousePosX=map_things[drag].X;
engine.MousePosY=map_things[drag].Y;
engine.MousePosZ=map_things[drag].Z;
ox=map_things[drag].X;
oy=map_things[drag].Y;
oz=map_things[drag].Z;
if(drag) //drag in plan view
{
SLONG offset_x,offset_y,offset_z;
SLONG in=1;
if(button)
{
SLONG old_thing;
old_thing=drag;
// right button so create a new identical prim and drag it
drag=place_prim_at(map_things[drag].IndexOther,map_things[drag].X,map_things[drag].Y,map_things[drag].Z);
if(drag==0)
return(0);
map_things[drag].AngleY=map_things[old_thing].AngleY;
map_things[drag].X-engine.MousePosX;
}
SetWorldMouse(0);
offset_x=map_things[drag].X-engine.MousePosX;
offset_y=map_things[drag].Y-engine.MousePosY;
offset_z=map_things[drag].Z-engine.MousePosZ;
// set_user_rotate(map_things[drag].AngleX,0,0);
angle_prim_y=map_things[drag].AngleY;
while(SHELL_ACTIVE && ( (button==0) ? LeftButton : RightButton))
{
SLONG nx,ny,nz;
in=SetWorldMouse(0);
nx=map_things[drag].X;
ny=map_things[drag].Y;
nz=map_things[drag].Z;
if(GridFlag)
{
SLONG grid_and;
grid_and=~(HALF_ELE_SIZE-1);
if(Axis&X_AXIS)
nx=((engine.MousePosX+offset_x)&grid_and)-px;
if(py<0)
{
if(Axis&Y_AXIS)
ny=((engine.MousePosY+offset_y)&grid_and)+((-py)&0x7f);
}
else
{
if(Axis&Y_AXIS)
ny=((engine.MousePosY+offset_y)&grid_and)-((py)&0x7f);
}
if(Axis&Z_AXIS)
nz=((engine.MousePosZ+offset_z)&grid_and)-(pz);
}
else
{
if(Axis&X_AXIS)
nx=engine.MousePosX+offset_x;
if(Axis&Y_AXIS)
ny=engine.MousePosY+offset_y;
if(Axis&Z_AXIS)
nz=engine.MousePosZ+offset_z;
}
if(PrimTabMode==PRIM_MODE_BACK)
{
map_things[drag].X=nx;
map_things[drag].Y=ny;
map_things[drag].Z=nz;
// LogText("Drag To nx %d ny %d nz %d \n",nx,ny,nz);
}
else
move_thing_on_cells(drag,nx,ny,nz);
DrawModuleContent(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight());
SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight());
ShowWorkWindow(0);
screen_change=1;
SetWorkWindowBounds(this->ContentLeft()+1,this->ContentTop()+1,this->ContentWidth(),this->ContentHeight());
// ContentRect.FillRect(CONTENT_COL);
DrawBox(0,0,this->ContentWidth(),this->ContentHeight(),CONTENT_COL);
set_camera();
draw_editor_map(0);
render_view(1);
ShowWorkWindow(0);
editor_user_interface(0);
KeyboardInterface();
if(PrimTabMode!=PRIM_MODE_BACK)
rotate_prim_thing(drag);
}
if(!in)
{
delete_thing(drag);
}
MyUndo.MoveObject(0,drag,ox,oy,oz);
}
SetWorkWindowBounds(this->ContentLeft()+1,this->ContentTop()+1,this->ContentWidth(),this->ContentHeight());
DrawBox(0,0,this->ContentWidth(),this->ContentHeight(),CONTENT_COL);
// ContentRect.FillRect(CONTENT_COL);
UpdatePrimPickWindow();
SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT
edit_info.Clipped&=~1;
return(screen_change);
}
SLONG PrimPickTab::DragEngine(UBYTE flags,MFPoint *clicked_point)
{
SLONG wwx,wwy,www,wwh;
SLONG screen_change=0;
SLONG last_world_mouse;
wwx=WorkWindowRect.Left;
wwy=WorkWindowRect.Top;
www=WorkWindowRect.Width;
wwh=WorkWindowRect.Height;
{
SLONG start_x=0,start_y=0,start_z=0,flag=0;
SLONG old_x,old_y,old_z;
SLONG nx,ny,nz;
old_x=nx=engine.X;
old_y=ny=engine.Y;
old_z=nz=engine.Z;
while(SHELL_ACTIVE && MiddleButton)
{
last_world_mouse=SetWorldMouse(0);
if(last_world_mouse)
{
if(!flag)
{
flag=1;
start_x=engine.MousePosX<<8;
start_y=engine.MousePosY<<8;
start_z=engine.MousePosZ<<8;
}
nx=engine.MousePosX<<8;
ny=engine.MousePosY<<8;
nz=engine.MousePosZ<<8;
engine.X = (old_x+(-nx+start_x));
engine.Y = (old_y+(-ny+start_y));
engine.Z = (old_z+(-nz+start_z));
// engine.Z=nz<<8;
DrawModuleContent(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight());
SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth(),Parent->ContentHeight());
ShowWorkWindow(0);
screen_change=1;
engine.X=old_x;
engine.Y=old_y;
engine.Z=old_z;
}
}
if(flag)
{
engine.X= (old_x+(-nx+start_x));
engine.Y= (old_y+(-ny+start_y));
engine.Z= (old_z+(-nz+start_z));
}
}
return(screen_change);
}
extern SLONG calc_edit_height_at(SLONG x,SLONG z);
SLONG PrimPickTab::HandleModuleContentClick(MFPoint *clicked_point,UBYTE flags,SLONG x,SLONG y,SLONG w,SLONG h)
{
SWORD thing;
// Stop compiler moaning.
x = x;
y = y;
w = w;
h = h;
switch(flags)
{
case NO_CLICK:
break;
case LEFT_CLICK:
if(CurrentPrim==0)
{
DragAPrim(flags,clicked_point,0);
}
else
{
SetWorldMouse(1);
// set_user_rotate(0,0,0);
angle_prim_y=0;
switch(PrimTabMode)
{
case PRIM_MODE_SINGLE:
if(ShiftFlag|| (prim_objects[CurrentPrim].flag & PRIM_FLAG_ON_FLOOR) )
{
SLONG px,py,pz,y;
find_things_min_point(CurrentPrim,&px,&py,&pz);
extern SLONG find_alt_for_this_pos(SLONG x,SLONG z);
y=find_alt_for_this_pos(engine.MousePosX,engine.MousePosZ);
//y=calc_edit_height_at(engine.MousePosX,engine.MousePosZ);
y-=py;
thing=place_prim_at(CurrentPrim,engine.MousePosX,y,engine.MousePosZ);
if(ShiftFlag)
map_things[thing].Flags|=FLAG_EDIT_PRIM_ON_FLOOR;
}
else
if(ShiftFlag|| (prim_objects[CurrentPrim].flag & PRIM_FLAG_JUST_FLOOR) )
{
SLONG px,py,pz,y;
find_things_min_point(CurrentPrim,&px,&py,&pz);
extern SLONG find_alt_for_this_pos(SLONG x,SLONG z);
//y=find_alt_for_this_pos(engine.MousePosX,engine.MousePosZ);
y=calc_edit_height_at(engine.MousePosX,engine.MousePosZ);
y-=py;
thing=place_prim_at(CurrentPrim,engine.MousePosX,y,engine.MousePosZ);
// map_things[thing].Flags|=FLAG_EDIT_PRIM_ON_FLOOR;
}
else
{
thing=place_prim_at(CurrentPrim,engine.MousePosX,engine.MousePosY,engine.MousePosZ);
}
break;
case PRIM_MODE_ANIM_KEY:
SLONG place_anim_prim_at(UWORD prim,SLONG x,SLONG y,SLONG z);
if(ShiftFlag)
{
SLONG px,py,pz,y;
/* HERE HERE HERE */ find_things_min_point(CurrentPrim,&px,&py,&pz);
extern SLONG find_alt_for_this_pos(SLONG x,SLONG z);
y=find_alt_for_this_pos(px,pz);
// y=find_alt_for_this_pos(engine.MousePosX,engine.MousePosZ);
// y=calc_edit_height_at(engine.MousePosX,engine.MousePosZ);
y-=py;
thing=place_prim_at(CurrentPrim,engine.MousePosX,y,engine.MousePosZ);
}
else
{
thing=place_anim_prim_at(CurrentPrim,engine.MousePosX,engine.MousePosY,engine.MousePosZ);
}
break;
}
MyUndo.PlaceObject(0,CurrentPrim,thing,engine.MousePosX,engine.MousePosY,engine.MousePosZ);
CurrentPrim=0;
UpdatePrimInfo();
return(1);
}
break;
case RIGHT_CLICK:
if(CurrentPrim==0)
DragAPrim(flags,clicked_point,1);
// Right click in content.
break;
case MIDDLE_CLICK:
DragEngine(flags,clicked_point);
break;
}
return(0);
}
UWORD PrimPickTab::HandleTabClick(UBYTE flags,MFPoint *clicked_point)
{
UWORD control_id;
Control *current_control;
MFPoint local_point;
// This is a fudge to update the front screen buffer.
ShowWorkScreen(0);
switch(flags)
{
case NO_CLICK:
break;
case LEFT_CLICK:
SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1);
local_point = *clicked_point;
GlobalToLocal(&local_point);
if(PrimRect.PointInRect(&local_point))
{
SLONG max,
x,
y,
prim = (((CVSlider*)GetControlPtr(CTRL_PRIM_V_SLIDE_PRIM))->GetCurrentValue()*3)+1;
switch(PrimTabMode)
{
case PRIM_MODE_SINGLE:
max = next_prim_object; //next_prim_object
max=266;
break;
case PRIM_MODE_MULTI:
max = next_prim_multi_object;
break;
case PRIM_MODE_ANIM_KEY:
case PRIM_MODE_ANIM_MORPH:
max=256;
}
for(y=1;y<255;y+=85)
for(x=1;x<255;x+=85)
{
if(prim < max)
if(is_point_in_box(local_point.X,local_point.Y,PrimRect.GetLeft()+x,PrimRect.GetTop()+y,85,85))
{
if(CurrentPrim!=prim)
{
RedrawTabContent=1;
CurrentPrim=prim;
UpdatePrimInfo();
extern SLONG HMTAB_current_prim;
HMTAB_current_prim = prim;
}
else
{
CurrentPrim=0;
UpdatePrimInfo();
}
UpdatePrimPickWindow();
}
prim++;
}
}
else
{
current_control = GetControlList();
while(current_control)
{
if(!(current_control->GetFlags()&CONTROL_INACTIVE) && current_control->PointInControl(&local_point))
{
// Handle control.
control_id = current_control->TrackControl(&local_point);
HandleControl(control_id);
// Tidy up display.
if(LockWorkScreen())
{
DrawTab();
UnlockWorkScreen();
}
ShowWorkWindow(0);
return control_id;
}
current_control = current_control->GetNextControl();
}
}
break;
case RIGHT_CLICK:
SetWorkWindowBounds(ContentLeft()+1,ContentTop()+1,ContentWidth()-1,ContentHeight()-1);
local_point = *clicked_point;
GlobalToLocal(&local_point);
break;
}
return 0;
}
//---------------------------------------------------------------
SLONG PrimPickTab::SetWorldMouse(ULONG flag)
{
MFPoint mouse_point;
MFPoint local_point;
SLONG wwx,wwy,www,wwh;
wwx=WorkWindowRect.Left;
wwy=WorkWindowRect.Top;
www=WorkWindowRect.Width;
wwh=WorkWindowRect.Height;
mouse_point.X = MouseX;
mouse_point.Y = MouseY;
local_point = mouse_point;
Parent->GlobalToLocal(&local_point);
if(is_point_in_box(local_point.X,local_point.Y,0,0,Parent->ContentWidth()-1,Parent->ContentHeight()/2))
{
SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth()-1,Parent->ContentHeight()/2-3);
set_camera_plan();
calc_world_pos_plan(local_point.X,local_point.Y);
if(flag)
engine.MousePosY=engine.Y>>8;
SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT
return(1);
}
else
if(is_point_in_box(local_point.X,local_point.Y,0,Parent->ContentHeight()/2,Parent->ContentWidth()-1,Parent->ContentHeight()/2))
{
SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+Parent->ContentHeight()/2+3,Parent->ContentWidth()-1,Parent->ContentHeight()/2-4);
if(View2Mode)
{
set_camera_side();
}
else
{
set_camera_front();
}
calc_world_pos_front(local_point.X,local_point.Y-Parent->ContentHeight()/2);
if(flag)
engine.MousePosZ=engine.Z>>8;
SetWorkWindowBounds(wwx,wwy,www,wwh); //RESTORE CLIP RECT
return(1);
}
/*
SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+1,Parent->ContentWidth()-1,Parent->ContentHeight()/2-3);
set_camera_plan();
point.X=engine.MousePosX;
point.Y=engine.MousePosY;
point.Z=engine.MousePosZ;
rotate_point_gte(&point,&out);
DrawLineC(out.X-10,out.Y,out.X+10,out.Y,1);
DrawLineC(out.X,out.Y-10,out.X,out.Y+10,1);
SetWorkWindowBounds(Parent->ContentLeft()+1,Parent->ContentTop()+Parent->ContentHeight()/2+3,Parent->ContentWidth()-1,Parent->ContentHeight()/2-4);
set_camera_front();
point.X=engine.MousePosX;
point.Y=engine.MousePosY;
point.Z=engine.MousePosZ;
rotate_point_gte(&point,&out);
DrawLineC(out.X-10,out.Y,out.X+10,out.Y,1);
DrawLineC(out.X,out.Y-10,out.X,out.Y+10,1);
ShowWorkWindow(0);
*/
return(0);
}
void add_a_background_thing(UWORD prim,SLONG x,SLONG y,SLONG z)
{
UWORD map_thing;
struct MapThing *p_mthing;
map_thing=find_empty_map_thing();
if(!map_thing)
return;
p_mthing=TO_MTHING(map_thing);
p_mthing->X=x;
p_mthing->Y=y;
p_mthing->Z=z;
p_mthing->IndexOther=prim;
p_mthing->IndexNext=background_prim;
background_prim=map_thing;
set_things_faces(map_thing);
p_mthing->Type=MAP_THING_TYPE_PRIM;
scan_function=scan_apply_ambient;
scan_map_thing(map_thing);
}
extern void clear_map2(void);
void PrimPickTab::HandleControl(UWORD control_id)
{
switch(control_id&0xff)
{
/*
case CTRL_PRIM_APPEND_NEW:
{
FileRequester *fr;
CBYTE fname[100];
clear_map2();
// clear_prims();
load_all_prims("allprim.sav");
fr=new FileRequester("objects\\","*.*","Load A Prim","hello");
if(fr->Draw())
{
strcpy(fname,fr->Path);
strcat(fname,fr->FileName);
read_asc(fname,100,1);
compress_prims();
record_prim_status();
save_all_prims("allprim.sav");
}
delete fr;
UpdatePrimPickWindow();
RequestUpdate();
}
break;
*/
case CTRL_PRIM_REPLACE:
if(CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
FileRequester *fr;
CBYTE fname[100];
clear_map2();
// clear_prims();
load_all_individual_prims();
fr=new FileRequester("objects\\","*.*","Load A Prim","hello");
if(fr->Draw())
{
SLONG temp;
strcpy(fname,fr->Path);
strcat(fname,fr->FileName);
temp=next_prim_object;
next_prim_object=CurrentPrim;
read_asc(fname,100,1);
next_prim_object=temp;
compress_prims();
record_prim_status();
save_prim_object(CurrentPrim);
//save_all_individual_prims();
}
delete fr;
UpdatePrimPickWindow();
RequestUpdate();
}
break;
case CTRL_PRIM_SAVE:
if (CurrentPrim)
{
// revert_to_prim_status();
save_prim_object(CurrentPrim);
//save_all_individual_prims();
}
break;
case CTRL_PRIM_X_AXIS_FREE:
ToggleControlSelectedState(CTRL_PRIM_X_AXIS_FREE);
if(Axis&X_AXIS)
Axis&=~X_AXIS;
else
Axis|=X_AXIS;
break;
case CTRL_PRIM_Y_AXIS_FREE:
ToggleControlSelectedState(CTRL_PRIM_Y_AXIS_FREE);
if(Axis&Y_AXIS)
Axis&=~Y_AXIS;
else
Axis|=Y_AXIS;
break;
case CTRL_PRIM_Z_AXIS_FREE:
ToggleControlSelectedState(CTRL_PRIM_Z_AXIS_FREE);
if(Axis&Z_AXIS)
Axis&=~Z_AXIS;
else
Axis|=Z_AXIS;
break;
case CTRL_PRIM_GRID_ON:
ToggleControlSelectedState(CTRL_PRIM_GRID_ON);
GridFlag^=1;
break;
case CTRL_PRIM_GRID_MAX:
ToggleControlSelectedState(CTRL_PRIM_GRID_MAX);
GridMax^=1;
break;
case CTRL_PRIM_GRID_CORNER:
ToggleControlSelectedState(CTRL_PRIM_GRID_CORNER);
GridCorner^=1;
break;
case CTRL_PRIM_LOAD_BACKGROUND:
/*
{
FileRequester *fr;
CBYTE fname[100];
fr=new FileRequester("data\\","*.asc","Load A Prim","hello");
if(fr->Draw())
{
UWORD temp;
strcpy(fname,fr->Path);
strcat(fname,fr->FileName);
read_asc(fname,640,1);
temp=copy_prim_to_end(next_prim_object-1,0,0);
add_a_background_thing(temp,HALF_ELE_SIZE+(512<<ELE_SHIFT),HALF_ELE_SIZE+(64<<ELE_SHIFT),HALF_ELE_SIZE+(3<<ELE_SHIFT));
// add_a_background_thing(next_prim_object-1,HALF_ELE_SIZE+(512<<ELE_SHIFT),HALF_ELE_SIZE+(64<<ELE_SHIFT),HALF_ELE_SIZE+(3<<ELE_SHIFT));
delete_last_prim();
}
UpdatePrimPickWindow();
delete fr;
RequestUpdate();
edit_info.amb_dx=-128;
edit_info.amb_dy=128;
edit_info.amb_dz=-128;
edit_info.amb_bright=256;
edit_info.amb_offset=0;
// edit_info.amb_flag=1;
// scan_map();
}
*/
break;
case CTRL_PRIM_ERASE_MAP:
if(CurrentPrim && CurrentPrim<256&&prim_count[CurrentPrim])
{
SLONG c0;
for(c0=0;c0<MAX_MAP_THINGS;c0++)
{
struct MapThing *t_mthing;
t_mthing=&map_things[c0];
switch(t_mthing->Type)
{
case MAP_THING_TYPE_PRIM:
if(t_mthing->IndexOther==CurrentPrim)
{
delete_thing(c0);
prim_count[CurrentPrim]=0;
}
break;
}
}
}
// save_map("data/bak.map",1);
// clear_map();
// RequestUpdate();
break;
case CTRL_PRIM_MODE_MENU:
PrimTabMode = (control_id>>8)-1;
switch(PrimTabMode)
{
case PRIM_MODE_SINGLE:
case PRIM_MODE_MULTI:
case PRIM_MODE_ANIM_KEY:
case PRIM_MODE_ANIM_MORPH:
// BackScale=engine.Scale;
// engine.Scale=PrimScale;
// RequestUpdate();
break;
// case PRIM_MODE_BACK:
// PrimScale=engine.Scale;
// engine.Scale=BackScale;
// RequestUpdate();
// break;
}
UpdatePrimInfo();
break;
case CTRL_PRIM_MODE_TEXT:
break;
/*
AngleY++;
break;
case CTRL_CAM_BUTTON_ZPLUS:
AngleZ++;
break;
case CTRL_CAM_BUTTON_XMINUS:
AngleX--;
break;
case CTRL_CAM_BUTTON_YMINUS:
AngleY--;
break;
case CTRL_CAM_BUTTON_ZMINUS:
AngleZ--;
break;
*/
case CTRL_PRIM_COLLIDE_NONE:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].coltype = PRIM_COLLIDE_NONE;
UpdatePrimInfo();
}
break;
case CTRL_PRIM_COLLIDE_BOX:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].coltype = PRIM_COLLIDE_BOX;
UpdatePrimInfo();
}
break;
case CTRL_PRIM_COLLIDE_CYLINDER:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].coltype = PRIM_COLLIDE_CYLINDER;
UpdatePrimInfo();
}
break;
case CTRL_PRIM_COLLIDE_SMALLBOX:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].coltype = PRIM_COLLIDE_SMALLBOX;
UpdatePrimInfo();
}
break;
case CTRL_PRIM_SHADOW_NONE: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].shadowtype = PRIM_SHADOW_NONE;} UpdatePrimInfo(); break;
case CTRL_PRIM_SHADOW_BOXEDGE: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].shadowtype = PRIM_SHADOW_BOXEDGE;} UpdatePrimInfo(); break;
case CTRL_PRIM_SHADOW_CYLINDER: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].shadowtype = PRIM_SHADOW_CYLINDER;} UpdatePrimInfo(); break;
case CTRL_PRIM_SHADOW_FOURLEGS: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].shadowtype = PRIM_SHADOW_FOURLEGS;} UpdatePrimInfo(); break;
case CTRL_PRIM_SHADOW_FULLBOX: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].shadowtype = PRIM_SHADOW_FULLBOX;} UpdatePrimInfo(); break;
case CTRL_PRIM_FLAG_LAMPOST: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].flag ^= PRIM_FLAG_LAMPOST; UpdatePrimInfo();} break;
case CTRL_PRIM_FLAG_GLARE: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].flag ^= PRIM_FLAG_GLARE; UpdatePrimInfo();} break;
case CTRL_PRIM_FLAG_TREE: if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE) {prim_objects[CurrentPrim].flag ^= PRIM_FLAG_TREE; UpdatePrimInfo();} break;
case CTRL_PRIM_FLAG_ON_FLOOR:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].flag ^= PRIM_FLAG_ON_FLOOR;
if(prim_objects[CurrentPrim].flag & PRIM_FLAG_ON_FLOOR)
{
prim_objects[CurrentPrim].flag &=~ PRIM_FLAG_JUST_FLOOR;
}
UpdatePrimInfo();
}
break;
case CTRL_PRIM_FLAG_JUST_FLOOR:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].flag ^= PRIM_FLAG_JUST_FLOOR;
if(prim_objects[CurrentPrim].flag & PRIM_FLAG_JUST_FLOOR)
{
prim_objects[CurrentPrim].flag &=~ PRIM_FLAG_ON_FLOOR;
}
UpdatePrimInfo();
}
break;
case CTRL_PRIM_FLAG_INSIDE:
{
edit_info.Inside^=1;
UpdatePrimInfo();
}
break;
case CTRL_PRIM_VIEW_SIDE:
if(View2Mode==0)
{
View2Mode=1;
SetControlState(CTRL_PRIM_VIEW_SIDE, CTRL_SELECTED);
}
else
{
View2Mode=0;
SetControlState(CTRL_PRIM_VIEW_SIDE, CTRL_DESELECTED);
}
break;
case CTRL_PRIM_GROW:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
SLONG i;
PrimObject *po;
//
// Grow the selected prim.
//
po = &prim_objects[CurrentPrim];
for (i = po->StartPoint; i < po->EndPoint; i++)
{
prim_points[i].X += prim_points[i].X >> 2;
prim_points[i].Y += prim_points[i].Y >> 2;
prim_points[i].Z += prim_points[i].Z >> 2;
}
void update_modules(void);
update_modules();
}
break;
case CTRL_PRIM_SHRINK:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
SLONG i;
PrimObject *po;
//
// Shrink the selected prims.
//
po = &prim_objects[CurrentPrim];
for (i = po->StartPoint; i < po->EndPoint; i++)
{
prim_points[i].X -= prim_points[i].X >> 2;
prim_points[i].Y -= prim_points[i].Y >> 2;
prim_points[i].Z -= prim_points[i].Z >> 2;
}
void update_modules(void);
update_modules();
}
break;
case CTRL_PRIM_DAMAGABLE:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].damage ^= PRIM_DAMAGE_DAMAGABLE;
UpdatePrimInfo();
}
break;
case CTRL_PRIM_LEANS:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].damage ^= PRIM_DAMAGE_LEAN;
prim_objects[CurrentPrim].damage |= PRIM_DAMAGE_DAMAGABLE;
if (prim_objects[CurrentPrim].damage & PRIM_DAMAGE_LEAN)
{
prim_objects[CurrentPrim].damage &= ~PRIM_DAMAGE_CRUMPLE;
}
UpdatePrimInfo();
}
break;
case CTRL_PRIM_CRUMPLES:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].damage ^= PRIM_DAMAGE_CRUMPLE;
prim_objects[CurrentPrim].damage |= PRIM_DAMAGE_DAMAGABLE;
if (prim_objects[CurrentPrim].damage & PRIM_DAMAGE_CRUMPLE)
{
prim_objects[CurrentPrim].damage &= ~PRIM_DAMAGE_LEAN;
}
UpdatePrimInfo();
}
break;
case CTRL_PRIM_EXPLODES:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
prim_objects[CurrentPrim].damage |= PRIM_DAMAGE_DAMAGABLE;
prim_objects[CurrentPrim].damage ^= PRIM_DAMAGE_EXPLODES;
UpdatePrimInfo();
}
break;
case CTRL_PRIM_CENTRE_PIVOT:
if (CurrentPrim && PrimTabMode == PRIM_MODE_SINGLE)
{
SLONG i;
SLONG min_x = +INFINITY;
SLONG min_y = +INFINITY;
SLONG min_z = +INFINITY;
SLONG max_x = -INFINITY;
SLONG max_y = -INFINITY;
SLONG max_z = -INFINITY;
SLONG mid_x;
SLONG mid_y;
SLONG mid_z;
PrimObject *po;
//
// Shrink the selected prims.
//
po = &prim_objects[CurrentPrim];
for (i = po->StartPoint; i < po->EndPoint; i++)
{
if (prim_points[i].X < min_x) {min_x = prim_points[i].X;}
if (prim_points[i].Y < min_y) {min_y = prim_points[i].Y;}
if (prim_points[i].Z < min_z) {min_z = prim_points[i].Z;}
if (prim_points[i].X > max_x) {max_x = prim_points[i].X;}
if (prim_points[i].Y > max_y) {max_y = prim_points[i].Y;}
if (prim_points[i].Z > max_z) {max_z = prim_points[i].Z;}
}
mid_x = min_x + max_x >> 1;
mid_y = min_y + max_y >> 1;
mid_z = min_z + max_z >> 1;
for (i = po->StartPoint; i < po->EndPoint; i++)
{
prim_points[i].X -= mid_x;
prim_points[i].Y -= mid_y;
prim_points[i].Z -= mid_z;
}
void update_modules(void);
update_modules();
}
break;
}
}
//---------------------------------------------------------------
|
<reponame>notandrewkaye/Latitude_colors<filename>Latitude_colors.sketchplugin/Contents/Resources/assets/common.js<gh_stars>100-1000
/*----------------------------------------------------------
Copyright 2017 <NAME>
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.
----------------------------------------------------------*/
function removeSwatches() {
$("#swatches").empty();
}
function initSwatches(title) {
$("#title").text(title);
// init
$("#swatches button").eq(0).addClass("focus");
updateInterface($("#swatches button").eq(0).text(), $("#swatches button").eq(0).attr("title"));
$("#swatches button").each(function(){
$(this).click(function(){
if ($(this).text() != "") {
$("#swatches button.focus").each(function(){
$(this).removeClass("focus");
});
$(this).addClass("focus");
updateInterface($(this).text(), $(this).attr("title"));
}
});
});
function updateInterface(hex, name) {
$("#colorPreview").css("backgroundColor", "#" + hex);
$("#colorName").text(name);
$("#colorHex").text("#" + hex.toUpperCase());
$("#icon_fill").attr("onclick", "window.location.hash='" + hex.toUpperCase() + "-fill-'" + " + new Date().getTime();");
$("#icon_stroke").attr("onclick", "window.location.hash='" + hex.toUpperCase() + "-stroke-'" + " + new Date().getTime();");
$("#icon_add").attr("onclick", "window.location.hash='" + hex.toUpperCase() + "-add-'" + " + new Date().getTime();");
$("#icon_copy").attr("onclick", "window.location.hash='" + hex.toUpperCase() + "-copy-'" + " + new Date().getTime();");
$("#icon_save").attr("onclick", "window.location.hash='save-to-system-'" + " + new Date().getTime();");
}
// Search
var options = {
valueNames: [
"palette",
{ name: "name", attr: "title" }
]
};
var colorList = new List("container", options);
}
function getAllColors() {
var colors = [];
$("#swatches button").each(function(){
if ($(this).text() != "") {
colors.push([
$(this).attr("title"),
$(this).text()
]);
}
});
return JSON.stringify(colors);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.