text
stringlengths 1
1.05M
|
|---|
#!/bin/bash
# ******************************************
# Developer: Quang Nguyen Phu
# Date: 05-12-2020
# ******************************************
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash –
sudo apt-get install -y nodejs;
sudo apt-get install -y build-essential;
echo "****************************************** 08-setup-nodejs-10x.sh: Done!!!!!";
|
<reponame>zonesgame/StendhalArcClient
package mindustry.io;
import arc.assets.*;
import arc.assets.loaders.*;
import arc.assets.loaders.resolvers.*;
import arc.files.*;
public class SavePreviewLoader extends TextureLoader{
public SavePreviewLoader(){
super(new AbsoluteFileHandleResolver());
}
@Override
public void loadAsync(AssetManager manager, String fileName, Fi file, TextureParameter parameter){
try{
super.loadAsync(manager, fileName, file.sibling(file.nameWithoutExtension()), parameter);
}catch(Exception e){
e.printStackTrace();
file.sibling(file.nameWithoutExtension()).delete();
}
}
}
|
<gh_stars>0
// Brunch automatically concatenates all files in your
// watched paths. Those paths can be configured at
// config.paths.watched in "brunch-config.js".
//
// However, those files will only be executed if
// explicitly imported. The only exception are files
// in vendor, which are never wrapped in imports and
// therefore are always executed.
// Import dependencies
//
// If you no longer want to use a dependency, remember
// to also remove its path from "config.paths.watched".
import 'phoenix_html'
import { Socket } from 'phoenix'
import Vue from 'vue'
import axios from 'axios'
//Globaly available channel
Vue.prototype.$appChannel = null
Vue.mixin({
data: function() {
return {
appChannel() {
return this.$appChannel;
}
}
}
})
//Contains all components
import './components'
new Vue({
el: '#mr',
data: {
socket: {},
username: 'Adam',
password: '<PASSWORD>',
token: "",
feedback: ""
},
methods: {
login: function() {
axios.get("http://localhost:4000/api/token/" + this.username + "/" + this.password)
.then(
response => {
console.log(response)
if (response.data.result === "ok") {
console.log(response.data.token)
let token = response.data.token
this.socket = new Socket(
"ws://localhost:4000/socket",
{
params: {
token: token
}
}
)
this.socket.connect()
this.socket.onError(() => {
console.log("error. disconnecting.")
socket.disconnect()
return null
})
this.$appChannel = this.socket.channel("app:xx", {})
this.$appChannel.join()
.receive("ok", resp => { console.log("Joined successfully", resp) })
.receive("error", resp => { console.log("Unable to join", resp) })
}
else {
console.log(response.data.result)
return null
}
})
.catch(err => console.log(err))
},
tryit: function(){
console.log("pushing")
this.$appChannel.push("deck:list", { x: "y" })
}
}
});
// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".
|
#! /bin/sh
err=0
for s in pgq pgq_node pgq_coop londiste pgq_ext; do
code_hash=$(git log --raw -n 1 sql/$s/functions | head -1)
fn="sql/$s/functions/$s.version.sql"
ver_hash=$(git log --raw -n 1 "$fn" | head -1)
test "${code_hash}" = "${ver_hash}" || echo "$s has code changes, needs new version"
ver_func=$(sed -n "s/.*return *'\(.*\)';/\1/;T;p" $fn)
ver_control=$(sed -n "s/default_version = '\(.*\)'/\1/;T;p" sql/$s/$s.control)
ver_make=$(sed -n "s/EXT_VERSION = \(.*\)/\1/;T;p" sql/$s/Makefile)
if test "${ver_func}|${ver_control}" = "${ver_make}|${ver_make}"; then
echo "$s: $ver_control"
else
echo "$s: version mismatch"
echo " Makefile: $ver_make"
echo " version(): $ver_func"
echo " control: $ver_control"
err=1
fi
done
exit $err
|
import React, {Component} from 'react';
import {View, Text, FlatList, StyleSheet} from 'react-native';
import {Actions} from 'react-native-router-flux';
import AddPeople from './AddPeople';
import Button from '../components/common/Button';
class InvitePeople extends Component{
state = {
data: [
{
name: "Bob",
phone: "111-111-1111",
cruise_id: "12345"
},
{
name: "Benny",
phone: "222-111-2221",
cruise_id: "53233"
}
],
showModal: false,
};
onSubmitAddPeople(name, phone, cruise_id){
const newData = this.state.data;
newData.push({
name: "Joe",
phone: "444-444-4444",
cruise_id: "83794"
});
this.setState({ data: newData, showModal: false });
}
onCloseModal(){
this.setState({ showModal: false });
}
render(){
const {
invitePeople,
invitePeople__title,
invitePeople__container,
invitePeople__group,
invitePeople__Label,
invitePeople__plusBtn,
invitePeople__label,
invitePeople__btn,
margin } = styles;
return(
<View style={invitePeople}>
<Text style={invitePeople__title}>Invite</Text>
<View style={invitePeople__container}>
<View style={invitePeople__group}>
<Text style={invitePeople__label}>Name</Text>
<FlatList
keyExtractor={item => item.cruise_id}
data={this.state.data}
renderItem={({ item }) => {
return (
<Text style={margin}>{item.name}</Text>
)}} />
<Button
buttonStyle={invitePeople__plusBtn}
textStyle={invitePeople__Label}
value="+"
onPress={() => this.setState({ showModal: true })} />
</View>
<View style={invitePeople__group}>
<Text style={invitePeople__label}>Phone</Text>
<FlatList
keyExtractor={item => item.cruise_id}
data={this.state.data}
renderItem={({ item }) => {
return (
<Text style={margin}>{item.phone}</Text>
)}} />
</View>
<View style={invitePeople__group}>
<Text style={invitePeople__label}>Cruise_ID</Text>
<FlatList
keyExtractor={item => item.cruise_id}
data={this.state.data}
renderItem={({ item }) => {
return (
<Text style={margin}>{item.cruise_id}</Text>
)}} />
</View>
</View>
<Button
buttonStyle={invitePeople__btn}
textStyle={invitePeople__Label}
value="Continue"
onPress={() => Actions.selectTrip()}/>
<AddPeople
visible={this.state.showModal}
onCancel={this.onCloseModal.bind(this)}
onAdd={this.onSubmitAddPeople.bind(this)} />
</View>
);
};
};
const styles = StyleSheet.create({
invitePeople:{
marginTop: 20
},
invitePeople__title:{
fontSize: 30,
fontWeight: "bold",
marginLeft: 5
},
invitePeople__container:{
flexDirection: "row",
justifyContent: "space-around"
},
invitePeople__group:{
},
invitePeople__label:{
fontSize: 20
},
invitePeople__btn:{
width: 300,
alignSelf: "center",
backgroundColor: "#000000",
borderRadius: 5,
padding: 10,
marginTop: 30
},
invitePeople__plusBtn:{
alignSelf: "center",
backgroundColor: "#000000",
borderRadius: 100,
paddingHorizontal: 15,
paddingVertical: 10,
marginTop: 5
},
invitePeople__Label:{
fontSize: 15,
fontWeight: "bold",
textAlign: "center",
color: "#ffffff"
},
margin:{
marginVertical: 10
}
});
export default InvitePeople;
|
<filename>index.js
// Copyright (c) 2017-19 <NAME> <<EMAIL>>
// Copyright (c) 2019 <NAME> <<EMAIL>>
/**
* Node.js' `require` function on steroids:
* - Ability to search for a module in multiple directories
* - Ability to search using both absolute and relative paths
* - Ability to search using a prefix
* @module acquire
*/
function acquire (moduleName, options) {
if (typeof moduleName !== 'string') {
throw new Error('fatal: module name expected')
}
options = options || {}
const toArray = require('array-back')
const prefix = options.prefix
const paths = options.paths ? toArray(options.paths) : undefined
const orignalModulePaths = module.paths
if (paths && paths.length) {
module.paths = module.paths.concat(paths)
}
let output = null
if (prefix) {
try {
output = acquire(`${prefix}${moduleName}`, { paths })
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
output = acquire(moduleName, { paths })
} else {
throw err
}
}
} else {
output = tryEachPath(moduleName, { paths })
if (output === null) {
output = loadAsLocalPath(moduleName, { paths })
}
if (output === null) {
output = loadAsRegularRequire(moduleName, { paths })
}
}
module.paths = orignalModulePaths
if (output === null) {
const err = new Error('unable to find ' + moduleName)
err.code = 'MODULE_NOT_FOUND'
throw err
} else {
return output
}
}
function loadAsLocalPath (moduleName, options) {
const path = require('path')
let output
try {
output = require(path.resolve(moduleName), options)
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
output = null
} else {
throw err
}
}
return output
}
function loadAsRegularRequire (moduleName, options) {
let output
try {
/* workaround for node issue #28077 */
if (options && options.paths) {
output = require(require.resolve(moduleName, options))
} else {
output = require(require.resolve(moduleName))
}
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
output = null
} else {
throw err
}
}
return output
}
function tryEachPath (moduleName, options) {
const path = require('path')
let output = null
for (const p of options.paths || []) {
const fullPath = path.resolve(p, moduleName)
output = loadAsRegularRequire(fullPath)
if (output !== null) break
}
return output
}
module.exports = acquire
|
<reponame>anteins/Blunted2
// written by <NAME> 2008 - 2014
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#include "frame.hpp"
#include "../windowmanager.hpp"
namespace blunted {
Gui2Frame::Gui2Frame(Gui2WindowManager *windowManager, const std::string &name, float x_percent, float y_percent, float width_percent, float height_percent, bool background) : Gui2View(windowManager, name, x_percent, y_percent, width_percent, height_percent) {
if (background) {
Gui2Image *bg = new Gui2Image(windowManager, name + "_frame", 0, 0, width_percent, height_percent);
this->AddView(bg);
bg->LoadImage("media/menu/backgrounds/black.png");
bg->Show();
}
}
Gui2Frame::~Gui2Frame() {
}
}
|
#!/bin/bash
echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin
if [[ -n "${TRAVIS_TAG}" ]];then
docker build --pull -t travisghansen/kubernetes-pfsense-controller:${TRAVIS_TAG} .
docker push travisghansen/kubernetes-pfsense-controller:${TRAVIS_TAG}
elif [[ "${TRAVIS_BRANCH}" == "master" ]];then
docker build --pull -t travisghansen/kubernetes-pfsense-controller:latest .
docker push travisghansen/kubernetes-pfsense-controller:latest
else
docker build --pull -t travisghansen/kubernetes-pfsense-controller:${TRAVIS_BRANCH} .
docker push travisghansen/kubernetes-pfsense-controller:${TRAVIS_BRANCH}
fi
|
package net.hasor.solon.boot.test;
import net.hasor.test.spring.mod1.*;
import net.hasor.core.AppContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.Aop;
import org.noear.solon.test.SolonJUnit4ClassRunner;
import org.noear.solon.test.SolonTest;
import java.util.HashSet;
import java.util.Set;
@RunWith(SolonJUnit4ClassRunner.class)
@SolonTest(BootEnableHasor_2.class)
public class BootEnableHasor_2_Test {
@Inject
private AppContext appContext;
@Test
public void contextLoads() {
Set<Class<?>> hasType = new HashSet<>();
Aop.beanForeach((bw) -> {
hasType.add(bw.clz());
});
//
//
assert appContext.getBindInfo(TestModuleA.class) == null;
assert !hasType.contains(TestModuleA.class);
//
//
assert appContext.getBindInfo(TestModuleB.class) == null;
assert !hasType.contains(TestModuleB.class);
//
//
assert appContext.getBindInfo(TestModuleC.class) == null;
assert !hasType.contains(TestModuleC.class);
//
//
assert appContext.getBindInfo(TestModuleD.class) == null;
assert !hasType.contains(TestModuleD.class);
}
@Test
public void contextLoads21() {
Set<Class<?>> hasType = new HashSet<>();
Aop.beanForeach((bw) -> {
hasType.add(bw.clz());
});
//
//
// 有DimModule、在ComponentScan范围内、在EnableHasor范围外、无Component
assert appContext.getBindInfo(TestDimModuleA.class) != null; // 范围外不加载
assert hasType.contains(TestDimModuleA.class);// 无Component,Spring 中不存在它。
}
@Test
public void contextLoads22() {
Set<Class<?>> hasType = new HashSet<>();
Aop.beanForeach((bw) -> {
hasType.add(bw.clz());
});
//
//
// 有DimModule、在ComponentScan范围内、在EnableHasor范围外、有Component
assert appContext.getBindInfo(TestDimModuleB.class) != null; // 虽然 Hasor 扫描范围外,但是Hasor 会加载 Spring Bean 中所有 DimModule 的 Module
assert hasType.contains(TestDimModuleB.class);
TestDimModuleB dimModuleB = appContext.getInstance(TestDimModuleB.class);
assert dimModuleB != null;
}
@Test
public void contextLoads23() {
Set<Class<?>> hasType = new HashSet<>();
Aop.beanForeach((bw) -> {
hasType.add(bw.clz());
});
//
//
// 无DimModule、在ComponentScan范围内、在EnableHasor范围外、有Component
assert appContext.getBindInfo(TestDimModuleC.class) == null; // 不是一个有效的 Module
assert hasType.contains(TestDimModuleC.class);// 是Spring Bean
TestDimModuleC dimModuleC_1 = appContext.getInstance(TestDimModuleC.class);
TestDimModuleC dimModuleC_2 = Aop.get(TestDimModuleC.class);
//assert dimModuleC_1.getApplicationContext() == null;// Hasor 当成普通 Bean 创建
}
}
|
<filename>src/utils/node/schema-customization.service.js
/*
* Human Cell Atlas
* https://www.humancellatlas.org/
*
* Basic service supporting gatsby-node schema customization.
*/
const moment = require("moment-timezone");
/**
* Returns the bubble date, as an array i.e. [month, date, year]
* for easy rendering of the date in bubble format.
*
* @param source
* @returns {[string,string,string]}
*/
const buildDateBubbleField = function buildDateBubbleField(source) {
const {sessions, timezone} = source || {};
if ( !sessions ) {
return [];
}
/* Grab a set of sessions. */
const setOfSessions = getSetOfSessions(sessions, timezone);
/* Grab the first session. */
const firstSession = getFirstSession(setOfSessions);
/* Format the first session and return as a string array [MMM, DD, YYYY]. */
return firstSession.format("MMM DD YYYY").split(" ");
};
/**
* Returns the start date, taken from the earliest "session" date.
*
*
* @param source
* @returns {*}
*/
const buildDateStartField = function buildDateStartField(source) {
const {sessions, timezone} = source || {};
if ( !sessions ) {
return "";
}
/* Grab a set of sessions. */
const setOfSessions = getSetOfSessions(sessions, timezone);
/* Grab the first session. */
const firstSession = getFirstSession(setOfSessions);
/* Return formatted first session. */
return firstSession.toDate();
};
const buildSessionsDisplayField = function buildSessionsDisplayField(source) {
const {sessions, timezone} = source || {};
if ( !sessions ) {
return [];
}
/* Return reformatted sessions into a string array. */
return reformatToDisplayableSessions(sessions, timezone);
};
/**
* Converts a date value to a moment object.
*
* @param date
* @param timezone
* @returns {*}
*/
function convertSessionDateToMoment(date, timezone = "") {
if ( !date ) {
return "";
}
return moment.tz(date, ["D MMM YYYY h:mm A", "D MMM YYYY"], timezone);
}
/**
* Returns a set of sessions, each session as a moment object.
*
* @param sessions
* @param timezone
* @returns {*}
*/
function getSetOfSessions(sessions, timezone) {
/* Grab a complete set of sessions. */
const setOfSessions = new Set();
sessions.forEach(session => {
const {sessionEnd, sessionStart} = session || {};
if ( sessionEnd ) {
setOfSessions.add(convertSessionDateToMoment(session.sessionEnd, timezone));
}
if ( sessionStart ) {
setOfSessions.add(convertSessionDateToMoment(session.sessionStart, timezone));
}
});
return setOfSessions;
}
/**
* Returns the earliest session as a moment object.
*
* @param setOfSessions
* @returns {*}
*/
function getFirstSession(setOfSessions) {
/* Sort the sessions ASC. */
const sortedSessions = [...setOfSessions].sort((moment01, moment02) => moment01.diff(moment02));
/* Return the first session. */
return sortedSessions.shift();
}
/**
* Returns the sessions in a FE displayable format.
*
* @param sessions
* @param timezone
* @returns {Array}
*/
function reformatToDisplayableSessions(sessions, timezone) {
return sessions.map(session => {
const {sessionEnd, sessionStart} = session || {};
/* Grab the various formatting styles for display of each session. */
const formatByTimeWithPeriod = "h:mm A";
const formatByTimeWithTZ = `${formatByTimeWithPeriod} zz`;
const formatByDate = "dddd MMMM D YYYY";
const formatByTime24Hr = "HH:mm"; // Used to check if time is specified for event
/* Start and end sessions. */
/* Both start and end sessions are expected to have time values. */
/* i.e. A start session without a time, having an end session (also without a time, but perhaps on the next day)
* is indicative of improper use of the frontmatter field "sessions". */
/* Returns the session display string e.g. "Friday July 17 2020 09:16 AM to 11:45 AM EST". */
if ( sessionStart && sessionEnd ) {
/* Format the session start and end display strings. */
const startDisplayStr = convertSessionDateToMoment(sessionStart, timezone).format(`${formatByDate} ${formatByTimeWithPeriod}`);
const endDisplayStr = convertSessionDateToMoment(sessionEnd, timezone).format(formatByTimeWithTZ);
return `${startDisplayStr} to ${endDisplayStr}`;
}
/* Start session only. */
/* Returns either "Friday Jul 17 2020 09:16 AM EST" if a time is specified
* or "Friday Jul 17 2020" if no time has been specified with the start session. */
if ( sessionStart ) {
/* Grab the session start moment. */
const startMoment = convertSessionDateToMoment(sessionStart, timezone);
/* Returns the start session without time, if no time has been specified. */
/* e.g. "Friday Jul 17 2020". */
if ( startMoment.format(formatByTime24Hr) === "00:00" ) {
return startMoment.format(formatByDate);
}
/* Returns the start session with time. */
/* e.g. "Friday Jul 17 2020 09:16 AM". */
return convertSessionDateToMoment(sessionStart, timezone).format(`${formatByDate} ${formatByTimeWithTZ}`);
}
return "";
})
}
module.exports.buildDateBubbleField = buildDateBubbleField;
module.exports.buildDateStartField = buildDateStartField;
module.exports.buildSessionsDisplayField = buildSessionsDisplayField;
|
<reponame>INC-PSTORE/psafe<filename>frontend/app/containers/SignPage/reducer.js
/*
* Sign Page reducer
*/
import {
CHANGE_SIGNATURE,
CHANGE_VALIDATE_FORM,
CHANGE_DATA_TO_SIGN,
UPDATE_APPROVE_ROWS,
UPDATE_SELECTED_ROW,
} from './constants';
import {func} from "prop-types";
import {UPDATE_WALLETS_ROWS} from "../Wallets/constants";
// The initial state of the ShieldingPage
export const initialState = {
error: null,
dataToSign: '',
signature: '',
validateForm: null,
rows: null,
selectedRow: null,
};
function signReducer(state = initialState, action) {
switch (action.type) {
case CHANGE_VALIDATE_FORM:
return {
...state,
validateForm: action.validateForm,
}
case CHANGE_SIGNATURE:
return {
...state,
signature: action.signature,
}
case CHANGE_DATA_TO_SIGN:
return {
...state,
dataToSign: action.dataToSign,
}
case UPDATE_APPROVE_ROWS:
return {
...state,
rows: action.rows,
}
case UPDATE_SELECTED_ROW:
return {
...state,
selectedRow: action.selectedRow,
}
default:
return state;
}
}
export default signReducer;
|
package dbr
// Builder builds sql in one dialect like MySQL/PostgreSQL
// e.g. XxxBuilder
type Builder interface {
Build(Dialect, Buffer) error
}
// BuildFunc is an adapter to allow the use of ordinary functions as Builder
type BuildFunc func(Dialect, Buffer) error
// Build implements Builder interface
func (b BuildFunc) Build(d Dialect, buf Buffer) error {
return b(d, buf)
}
|
struct Transaction {
let transactionIndex: Quantity
let blockHash: EthData
let blockNumber: Quantity
let cumulativeGasUsed: Quantity
let gasUsed: Quantity
func totalGasCost() -> Quantity {
return cumulativeGasUsed - gasUsed
}
}
|
<reponame>potados99/tarvern-pin-archiver<gh_stars>1-10
import Discord from "discord.js";
import { onReady } from "./routes/ready";
import { onMessage } from "./routes/message";
import { onMessageUpdate } from "./routes/update";
import config from "../config";
import { onReactionAdd } from "./routes/reaction";
import { messagesFetched, reactionsFetched } from "./utils/message";
export default async function startBot() {
const client = new Discord.Client({ partials: ["MESSAGE", "REACTION"] }); // Listen for changes(update, reaction) on previous messages.
client.on("ready", async () => {
await onReady(client);
});
client.on("message", async (message) => {
await onMessage(message);
});
client.on("messageUpdate", async (rawBefore, rawAfter) => {
const [before, after] = await messagesFetched(rawBefore, rawAfter);
await onMessageUpdate(client, before, after);
});
client.on("messageReactionAdd", async (rawReaction) => {
const [reaction] = await reactionsFetched(rawReaction);
await onReactionAdd(reaction);
});
await client.login(config.auth.token);
}
|
<reponame>guuguuit/NikeBot
package nike.platform.order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class OrderController {
@Autowired
OrderDao orderDao;
@RequestMapping("order")
public String order(Model model, @RequestParam(name = "page",defaultValue ="0" ) Integer page, @RequestParam(name = "style_color",defaultValue ="" ) String style_color) {
page=page==null?0:page;
if(style_color!=null&&!"".equals(style_color))
model.addAttribute("orders",orderDao.findAllByStyleColor(PageRequest.of(page, 100),style_color));
else
model.addAttribute("orders",orderDao.findAll(PageRequest.of(page, 100) ));
model.addAttribute("style_color",style_color);
return "order";
}
/***
*/
@RequestMapping("orderdelete")
public String orderdelete(Model model, @RequestParam(name = "style_color",defaultValue ="" ) String style_color) {
if(style_color!=null)
orderDao.deleteByStyleColor(style_color);
return "redirect:/order";
}
}
|
#!/usr/bin/env bash
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2021-10-21 15:30:28 +0100 (Thu, 21 Oct 2021)
#
# https://github.com/HariSekhon/bash-tools
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn and optionally send me feedback to help steer this or other code I publish
#
# https://www.linkedin.com/in/HariSekhon
#
set -euo pipefail
[ -n "${DEBUG:-}" ] && set -x
srcdir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck disable=SC1090
. "$srcdir/lib/utils.sh"
# shellcheck disable=SC2034,SC2154
usage_description="
Counts the total number of running Docker containers on the current Kubernetes cluster in the current namespace
Specify the --namespace or use --all-namespaces to get the total across all namespaces, including the kube-system namespace
Requires kubectl to be in \$PATH and configured
"
# used by usage() in lib/utils.sh
# shellcheck disable=SC2034
usage_args="<--namespace blah | --all-namespaces>"
help_usage "$@"
kubectl get pods "$@" --field-selector status.phase=Running -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.name}{"\n"}' |
wc -l |
sed 's/[[:space:]]*//'
|
<gh_stars>1-10
package org.mnode.jot.schema;
/**
* Represents a persistent entity associated with one or more jots.
*/
public interface Entity extends PropertyAccessor {
<T extends Entity> T name(String name);
}
|
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for USN-1958-1
#
# Security announcement date: 2013-09-18 00:00:00 UTC
# Script generation date: 2017-01-01 21:03:25 UTC
#
# Operating System: Ubuntu 12.04 LTS
# Architecture: x86_64
#
# Vulnerable packages fix on version:
# - language-selector-common:0.79.4
#
# Last versions recommanded by security team:
# - language-selector-common:0.79.4
#
# CVE List:
# - CVE-2013-1066
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo apt-get install --only-upgrade language-selector-common=0.79.4 -y
|
<gh_stars>0
import static org.junit.Assert.*;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javafx.beans.InvalidationListener;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import hu.unideb.inf.MainApp;
import hu.unideb.inf.model.Paint;
import hu.unideb.inf.model.Surface;
import org.junit.Before;
import org.junit.Test;
public class Test1 {
MainApp mainApp;
@Before
public void setUp() throws Exception {
mainApp = new MainApp();
mainApp.setFile(new File( getClass().getResource("/data.xml").toURI()));
}
@Test
public void testStreamToString() {
assertNotNull("Test file missing",
getClass().getResource("/data.xml"));
}
@Test
public void testCalcSurface(){
Surface surface = new Surface("Wall", 4.0, 1.0, 2);
mainApp.getNotToPaintSurfaceData().clear();
mainApp.getNotToPaintSurfaceData().add(surface);
mainApp.getAllSurfaceData().clear();
mainApp.getAllSurfaceData().add(surface);
assertTrue(mainApp.calculateSurface() == 0.0);
Surface surface2 = new Surface("Wall", 2.0, 1.0, 2);
mainApp.getNotToPaintSurfaceData().clear();
mainApp.getNotToPaintSurfaceData().add(surface2);
assertTrue(mainApp.calculateSurface() == 4);
mainApp.getNotToPaintSurfaceData().clear();
mainApp.getNotToPaintSurfaceData().add(surface);
mainApp.getAllSurfaceData().clear();
mainApp.getAllSurfaceData().add(surface2);
assertTrue(mainApp.calculateSurface() == -4);
}
@Test
public void testReadFile() throws URISyntaxException{
assertTrue(new File( getClass().getResource("/data.xml").toURI())!= null);
assertTrue(mainApp.getPaintData().size()>0);
}
@Test
public void testEqual() {
Paint paint = new Paint();
paint.setBrand("Snezka");
paint.setName("White");
paint.setColor("FFFFFF");
paint.setSize(5.0);
paint.setPrice(5.3);
Paint paint2 = new Paint();
paint2.setBrand("Snezka");
paint2.setName("White");
paint2.setColor("FFFFFF");
paint2.setSize(5.0);
paint2.setPrice(5.3);
assertEquals(paint, paint2);
paint.setBrand("Snezka");
paint.setName("White");
paint.setColor("FFFFFF");
paint.setSize(5.0);
paint.setPrice(5.3);
paint2.setBrand("Snezka");
paint2.setName("White");
paint2.setColor("FFFFFA");
paint2.setSize(5.0);
paint2.setPrice(5.3);
assertNotEquals(paint, paint2);
}
@Test
public void testHashCode() {
Paint paint = new Paint();
paint.setBrand("Snezka");
paint.setName("White");
paint.setColor("FFFFFF");
paint.setSize(5.0);
paint.setPrice(5.3);
assertTrue(paint.hashCode() == paint.hashCode());
Paint paint2 = new Paint();
paint2.setBrand("Snezka");
paint2.setName("White");
paint2.setColor("FFFFFA");
paint2.setSize(5.0);
paint2.setPrice(5.3);
assertFalse(paint.hashCode() == paint2.hashCode());
}
@Test
public void testUniqueBrands(){
List<Paint> list = mainApp.getUniqueBrands();
for(int i =0; i<list.size(); i++){
for(int j = 0; j<list.size(); j++)
if(i!=j)
assertFalse(list.get(i).getBrand().equals(list.get(j).getBrand()));
}
}
@Test
public void testCost(){
//without surface
assertTrue(0 == mainApp.calculateCost(mainApp.getPaintData().get(0)));
Surface surface = new Surface("Wall", 4.1, 1.0, 2);
mainApp.getAllSurfaceData().add(surface);
Paint p = new Paint();
p.setBrand("testBrand");
p.setColor("FFAA00");
p.setPrice(10.0);
p.setSize(10.0);
//1 litre = 10 > 4.1*2
assertTrue(10 == mainApp.calculateCost(p));
}
@Test
public void testCheapestOfThisColor(){
mainApp.getPaintData().clear();
Paint paint = new Paint();
paint.setBrand("Sniezka");
paint.setName("White");
paint.setColor("FFFFFF");
paint.setSize(5.0);
paint.setPrice(5.3);
Paint paint2 = new Paint();
paint2.setBrand("TestBrand");
paint2.setName("White");
paint2.setColor("FFFFFF");
paint2.setSize(10.0);
paint2.setPrice(5.3);
mainApp.getPaintData().add(paint2);
mainApp.getPaintData().add(paint);
assertEquals(paint2,mainApp.cheapestOfThisColor(paint));
Paint paint3 = new Paint();
paint3.setBrand("Cheapest");
paint3.setName("White");
paint3.setColor("FFFFFF");
paint3.setSize(10.0);
paint3.setPrice(5.2);
mainApp.getPaintData().add(paint3);
assertEquals(paint3,mainApp.cheapestOfThisColor(paint));
}
@Test
public void calcRequredLitres(){
Surface surface = new Surface("TestWall", 12.3, 1.0, 2);
mainApp.getAllSurfaceData().clear();
mainApp.getNotToPaintSurfaceData().clear();
mainApp.getAllSurfaceData().add(surface);
assertEquals(5, mainApp.calculateRequredLitres(5), 0.000001);
surface = new Surface("TestWall", 1.1, 2.0, 1);
mainApp.getAllSurfaceData().clear();
mainApp.getNotToPaintSurfaceData().clear();
mainApp.getAllSurfaceData().add(surface);
assertEquals(1, mainApp.calculateRequredLitres(5), 0.000001);
}
@Test
public void testReqiredNumber(){
assertEquals("1 of 1l ", mainApp.calcRequiredNumberOfPaints(10, 10));
assertEquals("10 of 10l ", mainApp.calcRequiredNumberOfPaints(100, 1));
assertEquals("1 of 10l 1 of 5l 1 of 2l ",
mainApp.calcRequiredNumberOfPaints(17, 1));
}
}
|
<filename>micropython-1.5/bare-arm/main.c
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "py/nlr.h"
#include "py/compile.h"
#include "py/runtime.h"
#include "py/repl.h"
void do_str(const char *src, mp_parse_input_kind_t input_kind) {
mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, src, strlen(src), 0);
if (lex == NULL) {
return;
}
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
qstr source_name = lex->source_name;
mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
mp_obj_t module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, true);
mp_call_function_0(module_fun);
nlr_pop();
} else {
// uncaught exception
mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val);
}
}
int main(int argc, char **argv) {
mp_init();
do_str("print('hello world!', list(x+1 for x in range(10)), end='eol\\n')", MP_PARSE_SINGLE_INPUT);
do_str("for i in range(10):\n print(i)", MP_PARSE_FILE_INPUT);
mp_deinit();
return 0;
}
void gc_collect(void) {
}
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
return NULL;
}
mp_import_stat_t mp_import_stat(const char *path) {
return MP_IMPORT_STAT_NO_EXIST;
}
mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) {
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) {
}
void NORETURN __fatal_error(const char *msg) {
while (1);
}
#ifndef NDEBUG
void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line);
__fatal_error("Assertion failed");
}
#endif
/*
int _lseek() {return 0;}
int _read() {return 0;}
int _write() {return 0;}
int _close() {return 0;}
void _exit(int x) {for(;;){}}
int _sbrk() {return 0;}
int _kill() {return 0;}
int _getpid() {return 0;}
int _fstat() {return 0;}
int _isatty() {return 0;}
*/
void *malloc(size_t n) {return NULL;}
void *calloc(size_t nmemb, size_t size) {return NULL;}
void *realloc(void *ptr, size_t size) {return NULL;}
void free(void *p) {}
int printf(const char *m, ...) {return 0;}
void *memcpy(void *dest, const void *src, size_t n) {return NULL;}
int memcmp(const void *s1, const void *s2, size_t n) {return 0;}
void *memmove(void *dest, const void *src, size_t n) {return NULL;}
void *memset(void *s, int c, size_t n) {return NULL;}
int strcmp(const char *s1, const char* s2) {return 0;}
int strncmp(const char *s1, const char* s2, size_t n) {return 0;}
size_t strlen(const char *s) {return 0;}
char *strcat(char *dest, const char *src) {return NULL;}
char *strchr(const char *dest, int c) {return NULL;}
#include <stdarg.h>
int vprintf(const char *format, va_list ap) {return 0;}
int vsnprintf(char *str, size_t size, const char *format, va_list ap) {return 0;}
#undef putchar
int putchar(int c) {return 0;}
int puts(const char *s) {return 0;}
void _start(void) {main(0, NULL);}
|
#!/bin/bash
# Update the packages
sudo apt-get update
# Install git
sudo apt-get install git
# Check installation
git --version
|
# baseline
export save=./results/joint_confidence_loss/${RANDOM}/
mkdir -p $save
python ./src/run_joint_confidence.py --outf $save --dataroot ./data 2>&1 | tee $save/log.txt
|
#!/bin/bash
# Run the converter utility to convert .etlt -> .plan
# The "Converting the models to TensorRT" part of this guide is wrong: https://developer.nvidia.com/blog/fast-tracking-hand-gesture-recognition-ai-applications-with-pretrained-models-from-ngc/
# Use tao-converter instead: https://github.com/NVIDIA-AI-IOT/tao-toolkit-triton-apps/blob/fc7e222c036354498e53a8ed11b5cf7c0a3e5239/scripts/download_and_convert.sh
docker run --gpus=1 --rm \
--volume $PWD/trtis_model_repo/hcgesture_tlt/1:/models \
nvcr.io/nvidia/tao/tao-cv-inference-pipeline:v0.3-ga-server-utilities \
tao-converter \
-k nvidia_tlt \
-t fp16 \
-p input_1,1x3x160x160,1x3x160x160,2x3x160x160 \
-e /models/model.plan \
/models/model.etlt
|
if [ -n "$ANDROID_NDK" ]; then
export NDK=${ANDROID_NDK}
elif [ -n "$ANDROID_NDK_HOME" ]; then
export NDK=${ANDROID_NDK_HOME}
elif [ -n "$ANDROID_NDK_HOME" ]; then
export NDK=${ANDROID_NDK_HOME}
else
export NDK=/Applications/Unity/Hub/Editor/2019.4.0f1/PlaybackEngines/AndroidPlayer/NDK
fi
if [ ! -d "$NDK" ]; then
echo "Please set ANDROID_NDK environment to the root of NDK."
exit 1
fi
function build() {
API=$1
ABI=$2
TOOLCHAIN_ANME=$3
BUILD_PATH=build_android_${ABI}
cmake -H. -B${BUILD_PATH} -DANDROID_ABI=${ABI} -DCMAKE_TOOLCHAIN_FILE=${NDK}/build/cmake/android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=${API} -DANDROID_TOOLCHAIN=clang -DANDROID_TOOLCHAIN_NAME=${TOOLCHAIN_ANME}
cmake --build ${BUILD_PATH} --config Release
cp ${BUILD_PATH}/libkernal.so output/android/libs/${ABI}/libkernal.so
# cp ${BUILD_PATH}/libkernal.so ../unity/Assets/Plugins/kernal/Android/libs/${ABI}/libkernal.so
}
build android-16 armeabi-v7a arm-linux-androideabi-4.9
build android-16 arm64-v8a arm-linux-androideabi-clang
build android-16 x86 x86-4.9
|
<filename>commons-warp/src/main/java/com/github/hinsteny/commons/warp/http/utils/ParamsUtil.java
package com.github.hinsteny.commons.warp.http.utils;
import com.github.hinsteny.commons.core.exception.BusinessException;
import com.github.hinsteny.commons.core.utils.ReflectUtil;
import com.github.hinsteny.commons.warp.http.exception.HttpErrorCode;
import com.github.hinsteny.commons.warp.http.request.IgnoreParam;
import com.google.common.base.Strings;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* http参数工具类.
*
* @author Hinsteny
* @version ParamsUtil: 2019-08-12 15:39 All rights reserved.$
*/
public abstract class ParamsUtil {
private static final Logger logger = LoggerFactory.getLogger(ParamsUtil.class);
public ParamsUtil() {
}
/**
* 把键值对集合拼接成http-get请求url参数
* @param paramsMap
* @return
* @throws UnsupportedEncodingException
*/
public static String getParamsString(Map<String, String> paramsMap) {
if (null == paramsMap || paramsMap.size() == 0) {
return "";
}
final StringBuilder result = new StringBuilder("?");
paramsMap.forEach((key, value)->{
try {
result.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("拼接http-get请求字符串异常");
}
});
return result.substring(0, result.length() - 1);
}
/**
* 把一个对象类中的属性转化为键值对
* @param object
* @return
* @throws BusinessException
*/
public static Map<String, String> toParamMap(Object object) throws BusinessException {
Map<String, String> paramsMap = new HashMap<>(16);
try {
Field[] declaredFields = object.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
paramsMap.put(field.getName(), field.get(object) == null ? Strings.nullToEmpty(null) : field.get(object).toString());
}
} catch (Exception e) {
logger.error("异常", e);
throw new BusinessException(HttpErrorCode.BEAN_CONVERT_TO_MAP_ERROR.getCode(), "转化http参数出错");
}
return paramsMap;
}
/**
* 把一个对象类中的属性转化为键值对
* @param object
* @return
* @throws BusinessException
*/
public static Map<String, String> toParamMapIgnore(Object object) throws BusinessException {
Map<String, String> paramsMap = new HashMap<>(16);
try {
List<Field> declaredFields = ReflectUtil.getAccessibleFields(object);
for (Field field : declaredFields) {
field.setAccessible(true);
//如果加了transient或者忽略注解,就忽略掉这些Field参数
if (!Modifier.isTransient(field.getModifiers()) && field.getAnnotation(IgnoreParam.class) == null) {
paramsMap.put(field.getName(), field.get(object) == null ? Strings.nullToEmpty(null) : field.get(object).toString());
}
}
} catch (Exception e) {
logger.error("异常", e);
throw new BusinessException(HttpErrorCode.BEAN_CONVERT_TO_MAP_ERROR.getCode(), "转化http参数出错");
}
return paramsMap;
}
}
|
<reponame>gtm7712/team-project-d-2191-swen-261-11-d
package com.webcheckers.ui;
import com.webcheckers.model.*;
import com.webcheckers.util.Message;
import com.webcheckers.util.MoveValidator;
import com.webcheckers.util.ValidationResult;
import spark.Request;
import spark.Response;
import spark.Route;
import com.google.gson.Gson;
/**
* ui controller for validating moves
*/
public class PostValidateMoveRoute implements Route {
private final Gson gson;
/**
* Constructor that initializes the gson
* @param gson gson to be used by route
*/
public PostValidateMoveRoute(final Gson gson ){
this.gson = gson;
}
@Override
public Object handle(Request request, Response response) {
Player currentPlayer = request.session().attribute("Player");
Game game = currentPlayer.getGame();
MoveValidator validate = new MoveValidator(game);
String move = request.queryParams("actionData");
int startR = Character.getNumericValue(move.charAt(16));
int startC = Character.getNumericValue(move.charAt(25));
int endR = Character.getNumericValue(move.charAt(41));
int endC = Character.getNumericValue(move.charAt(50));
Move madeMove;
if(currentPlayer.equals(game.getWhitePlayer())){
madeMove= new Move(new Position(7-startR, startC), new Position(7-endR, endC));
}
else {
madeMove = new Move(new Position(startR, startC), new Position(endR, endC));
}
if(game.isComplete())
return gson.toJson(new Message("Move already made", Message.Type.ERROR));
ValidationResult result = validate.validateMove(madeMove);
if(result.wasJump()){
request.session().attribute("jumped", result.wasJump());
}
switch (result.getTurnResult()) {
case COMPLETE:
game.makeMove(madeMove);
request.session().attribute("jumped", false);
game.setComplete();
break;
case CONTINUE:
game.makeMove(madeMove);
break;
case KING:
game.makeMove(madeMove);
game.kingPiece(madeMove.getEnd());
request.session().attribute("jumped", false);
game.setComplete();
break;
case FAIL:
return gson.toJson(new Message(validate.msg, Message.Type.ERROR));
}
if (result.wasJump()) {
game.makeMove(new Move(validate.getMidpoint(madeMove), new Position(-1, -1)));
}
return gson.toJson(new Message("Nice Move!", Message.Type.INFO));
}
}
|
def calculate_total(order_items, tax_rate):
total = 0.00
for item in order_items:
total += (item["Price"] * item["Qty"])
total += total * tax_rate
return total
order_items = [{"Name":"Apples","Price":2.00,"Qty":2},{"Name":"Milk","Price":2.50,"Qty":1},{"Name":"Eggs","Price":3.00,"Qty":6}]
tax_rate = 0.08
total = calculate_total(order_items, tax_rate)
print(total)
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-N-IP/7-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-N-IP/7-512+512+512-SWS-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_within_sentences_first_third_sixth --eval_function last_sixth_eval
|
# frozen_string_literal: true
module MTUV
VERSION = '2.4.72'
end
|
import axios from 'axios';
import { get } from 'lodash';
// create "middleware"
const express = require('express');
const router = express.Router();
// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', new Date().toUTCString());
next();
});
// define the home page route
router.get('/', (req, res) => {
console.log('api --------------------');
res.send('Birds home page');
});
// define the about route
router.get('/users', async (req, res) => {
const { data } = await axios.get(
'https://jsonplaceholder.typicode.com/users'
);
res.json(data);
});
router.get('/users/:id', async (req, res) => {
const {
params: { id }
} = req;
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com/users/${id}`
);
res.json(data);
});
router.get('/login', async (req, res) => {
let result = {};
try {
result = await axios.post(
'https://stgadmin-expenso.paxanimi.ai/server/api/api/login',
{
email: '<EMAIL>',
password: '<PASSWORD>'
}
);
} catch (err) {
console.log(err);
}
res.json({ data: get(result, 'data', '') });
});
// https://stgadmin-expenso.paxanimi.ai/server/api
module.exports = router;
|
#!/usr/bin/env bash
version=$1
echo "Releasing version ==> " + $version
mvn clean package -DskipTests
docker stop $(docker ps -a | grep "manjesh80/geolocation-consul-lb" | awk '{print $1}')
docker rm $(docker ps -a | grep "manjesh80/geolocation-consul-lb" | awk '{print $1}')
docker rmi -f $(docker images | grep "manjesh80/geolocation-consul-lb" | awk '{print $3}' )
docker build -t manjesh80/geolocation-consul-lb -t manjesh80/geolocation-consul-lb:$version .
docker push manjesh80/geolocation-consul-lb:latest
docker push manjesh80/geolocation-consul-lb:$version
|
// Generated by Haxe 3.4.4
(function () { "use strict";
var Main = function() {
this.document = window.document;
var _gthis = this;
console.log("Example VanillaJS");
this.document.addEventListener("DOMContentLoaded",function(event) {
console.log("VanillaJs DOM ready");
var div = _gthis.document.getElementById("container-1");
div.style.opacity = Std.string(0.5);
var request = new XMLHttpRequest();
request.open("GET","https://api.nasa.gov/planetary/apod?concept_tags=True&api_key=DEMO_KEY",true);
request.onload = function() {
if(request.status >= 200 && request.status < 400) {
var json = request.responseText;
console.log("json: " + json);
} else {
console.log("oeps: status: " + request.status + " // json: " + request.responseText);
}
};
request.onerror = function() {
console.log("error");
};
request.send();
var _el = _gthis.document.getElementsByClassName("image-container")[0];
var _btnShow = _gthis.document.getElementById("fade-in");
var _btnHide = _gthis.document.getElementById("fade-out");
_gthis.fadeIn(_el);
_btnShow.addEventListener("click",function() {
_gthis.fadeIn(_el);
},false);
_btnHide.addEventListener("click",function() {
_gthis.fadeOut(_el);
},false);
});
};
Main.__name__ = true;
Main.main = function() {
var main = new Main();
};
Main.prototype = {
fadeIn: function(pElement,pOpacity) {
var _gthis = this;
if(pOpacity == null) {
pOpacity = 0;
} else {
pOpacity += 0.1;
}
pElement.style.opacity = pOpacity == null ? "null" : "" + pOpacity;
if(pOpacity < 1) {
haxe_Timer.delay(function() {
_gthis.fadeIn(pElement,pOpacity);
},100);
} else {
console.log("Stop fadein");
}
}
,fadeOut: function(pElement,pOpacity) {
var _gthis = this;
if(pOpacity == null) {
pOpacity = 1;
} else {
pOpacity -= 0.1;
}
pElement.style.opacity = pOpacity == null ? "null" : "" + pOpacity;
if(pOpacity > 0) {
haxe_Timer.delay(function() {
_gthis.fadeOut(pElement,pOpacity);
},100);
} else {
console.log("Stop fadeOut");
}
}
};
Math.__name__ = true;
var Std = function() { };
Std.__name__ = true;
Std.string = function(s) {
return js_Boot.__string_rec(s,"");
};
var haxe_Timer = function(time_ms) {
var me = this;
this.id = setInterval(function() {
me.run();
},time_ms);
};
haxe_Timer.__name__ = true;
haxe_Timer.delay = function(f,time_ms) {
var t = new haxe_Timer(time_ms);
t.run = function() {
t.stop();
f();
};
return t;
};
haxe_Timer.prototype = {
stop: function() {
if(this.id == null) {
return;
}
clearInterval(this.id);
this.id = null;
}
,run: function() {
}
};
var js_Boot = function() { };
js_Boot.__name__ = true;
js_Boot.__string_rec = function(o,s) {
if(o == null) {
return "null";
}
if(s.length >= 5) {
return "<...>";
}
var t = typeof(o);
if(t == "function" && (o.__name__ || o.__ename__)) {
t = "object";
}
switch(t) {
case "function":
return "<function>";
case "object":
if(o instanceof Array) {
if(o.__enum__) {
if(o.length == 2) {
return o[0];
}
var str = o[0] + "(";
s += "\t";
var _g1 = 2;
var _g = o.length;
while(_g1 < _g) {
var i = _g1++;
if(i != 2) {
str += "," + js_Boot.__string_rec(o[i],s);
} else {
str += js_Boot.__string_rec(o[i],s);
}
}
return str + ")";
}
var l = o.length;
var i1;
var str1 = "[";
s += "\t";
var _g11 = 0;
var _g2 = l;
while(_g11 < _g2) {
var i2 = _g11++;
str1 += (i2 > 0 ? "," : "") + js_Boot.__string_rec(o[i2],s);
}
str1 += "]";
return str1;
}
var tostr;
try {
tostr = o.toString;
} catch( e ) {
return "???";
}
if(tostr != null && tostr != Object.toString && typeof(tostr) == "function") {
var s2 = o.toString();
if(s2 != "[object Object]") {
return s2;
}
}
var k = null;
var str2 = "{\n";
s += "\t";
var hasp = o.hasOwnProperty != null;
for( var k in o ) {
if(hasp && !o.hasOwnProperty(k)) {
continue;
}
if(k == "prototype" || k == "__class__" || k == "__super__" || k == "__interfaces__" || k == "__properties__") {
continue;
}
if(str2.length != 2) {
str2 += ", \n";
}
str2 += s + k + " : " + js_Boot.__string_rec(o[k],s);
}
s = s.substring(1);
str2 += "\n" + s + "}";
return str2;
case "string":
return o;
default:
return String(o);
}
};
String.__name__ = true;
Array.__name__ = true;
Main.main();
})();
|
import Cookie from 'js-cookie';
/**
* Aliases Cookie.get(). See https://github.com/js-cookie/js-cookie#basic-usage for more info.
*
* @param {string} name Name of the cookie
* @return {string} Cookie value
*/
export default function getCookie(name) {
return Cookie.get(name);
}
|
#!/usr/bin/env bash
set -e
source development.env
yes | npx http-server \
-S \
-p 9000 \
-C $(find $CERTS_DIR/ -name "$DOMAIN*" -not -name "*key*") \
-K $(find $CERTS_DIR/ -name "$DOMAIN*" -name "*key*")
|
<reponame>lindseymysse/e-y-e<filename>EYE.js
class EYE extends HTMLElement {
connectedCallback(){
this.details = document.createElement('details')
this.details.innerHTML = `<summary> </summary>`
// Devices
this.devices_el = document.createElement('details')
this.devices_el.innerHTML = `<summary>Devices</summary>`
this.details.appendChild(this.devices_el)
this.devices = document.createElement('eye-devices')
this.devices_el.appendChild(this.devices)
this.devices.addEventListener('audio-input-device-changed', (e) => {
this.handleAudioInputDeviceChange(e.detail)
})
this.devices.addEventListener('audio-output-device-changed', (e) => {
this.handleAudioOutputDeviceChange(e.detail)
})
this.devices.addEventListener('video-input-device-changed', (e) => {
this.handleVideoInputDeviceChange(e.detail)
})
// Constraints
this.constraints_el = document.createElement('details')
this.constraints_el.innerHTML = `<summary>Controls</summary>`
this.details.appendChild(this.constraints_el)
this.constraints = document.createElement('eye-controls')
this.constraints_el.appendChild(this.constraints)
this.constraints.addEventListener('UPDATE FILTER', (e) => {
this.video.style.filter = e.detail
})
this.appendChild(this.details)
// Video
this.video = document.createElement('video')
this.video.onloadedmetadata = (e) =>{
this.video.play()
}
this.appendChild(this.video)
this.getUserMedia()
}
async getUserMedia(){
if(!this.audio_constraints && !this.video_constraints){
this.video.pause()
return
}
const audio = this.audio_constraints;
const video = this.video_constraints;
const stream = await navigator.mediaDevices.getUserMedia({ audio, video })
this.video.srcObject = stream
this.video.volume = 0
this.video.play()
}
handleNewConstraints(new_constraints){
}
handleAudioInputDeviceChange(new_id){
if(new_id === "false"){
this.audio_constraints = false
this.getUserMedia()
return
} else if (!this.audio_constraints){
this.audio_constraints = {}
}
this.audio_constraints.deviceId = new_id
this.getUserMedia()
}
handleAudioOutputDeviceChange(new_id){
this.getUserMedia()
}
handleVideoInputDeviceChange(new_id){
if(new_id === "false"){
this.video_constraints = false
this.getUserMedia()
return
} else if (!this.video_constraints){
this.video_constraints = {
facingMode: "environment"
}
}
this.video_constraints.deviceId = new_id
this.getUserMedia()
}
}
customElements.define('e-y-e', EYE)
class EyeDevices extends HTMLElement {
connectedCallback(){
this.showConnectedDevices()
}
async showConnectedDevices(){
const connected_devices = [...await navigator.mediaDevices.enumerateDevices()]
let video_options = connected_devices
.filter((device) => device.kind === 'videoinput')
let audio_input_options = connected_devices.filter((device) => device.kind === 'audioinput')
let audio_output_options = connected_devices.filter((device) => device.kind === 'audiooutput')
if(video_options.length){
const video_input_label = document.createElement('label')
video_input_label.innerHTML = `Video Input`
const video_selector = document.createElement('select')
video_selector.innerHTML = video_options.map((device) => {return `<option value="${device.deviceId}">${device.label}</option>`}).join("") + '<option value="false">none</option>'
video_input_label.appendChild(video_selector)
this.appendChild(video_input_label)
video_selector.addEventListener('change', (e) => {
this.setAttribute('video-input-device', e.target.value)
})
this.setAttribute('video-input-device', video_options[0].deviceId)
}
if(audio_input_options.length){
const audio_input_label = document.createElement('label')
audio_input_label.innerHTML = `Audio Input`
const audio_input_selector = document.createElement('select')
audio_input_selector.innerHTML = audio_input_options.map((device) => {return `<option value="${device.deviceId}">${device.label}</option>`}).join("")+ '<option value="false">none</option>'
audio_input_label.appendChild(audio_input_selector)
this.appendChild(audio_input_label)
audio_input_selector.addEventListener('change', (e) => {
this.setAttribute('audio-input-device', e.target.value)
})
this.setAttribute('audio-input-device', audio_input_options[0].deviceId)
}
// if(audio_output_options.length){
// const audio_output_label = document.createElement('label')
// audio_output_label.innerHTML = 'Audio Output'
// const audio_output_selector = document.createElement('select')
// audio_output_selector.innerHTML = audio_output_options.map((device) => {return `<option value="${device.deviceId}">${device.label}</option>`}).join("") + '<option value="false">none</option>'
// audio_output_label.appendChild(audio_output_selector)
// this.appendChild(audio_output_label)
// audio_output_selector.addEventListener('change', (e) => {
// this.setAttribute('audio-output-device', e.target.value)
// })
// this.setAttribute('audio-output-device', audio_output_options[0].deviceId)
// }
}
static get observedAttributes() {
return ['audio-output-device', 'audio-input-device', 'video-input-device', 'video-output-device'];
}
attributeChangedCallback(name, old_value, new_value){
switch(name){
case "audio-input-device":
dispatch('audio-input-device-changed', new_value, this)
break
case "audio-output-device":
dispatch('audio-output-device-changed', new_value, this)
break
case "video-input-device":
dispatch('video-input-device-changed', new_value, this)
break
default:
}
}
}
customElements.define('eye-devices', EyeDevices)
class EyeControls extends HTMLElement {
connectedCallback(){
this.form = document.createElement('form')
this.form.innerHTML = `
<label>
brightness
<input type="range" min="0" max="400" name="brightness">
</label>
<label>
Contrast
<input type="range" min="0" max="200" name="contrast">
</label>
<label>
Hue
<input type="range" min="0" max="360" name="hue">
</label>
<label>
Saturation
<input type="range" min="0" max="360" name="saturation">
</label>
<label>
Flip
<input type="checkbox" name="flip">
</label>
<label>
Invert
<input type="checkbox" name="invert">
</label>
`
this.appendChild(this.form)
this.flip = document.createElement('form')
this.flip.innerHTML = `
`
let mousedown = false
this.form.addEventListener('mousedown', (e) => {
mousedown = true
})
document.body.addEventListener('mouseup', (e) => {
mousedown = false
})
this.form.addEventListener('mousemove', (e) => {
if(mousedown){
this.handleSettings()
}
})
this.form.addEventListener('change', (e) => {
this.handleSettings(e)
})
}
handleSettings(){
let settings = {};
[...this.form.querySelectorAll('input')].forEach(input => {
settings[input.name] = input.value
})
let filter_text = `brightness(${(settings.brightness / 100)}) contrast(${(settings.contrast / 100)}) hue-rotate(${settings.hue}deg) saturate(${settings.saturation / 100}) invert(${settings.invert === 'checked' ? 1 : 0})
`
dispatch('UPDATE FILTER', filter_text, this)
dispatch('UPDATE FLIPPED', settings.flip, this)
}
static get observedAttributes() {
return [];
}
attributeChangedCallback(name, old_value, new_value){
switch(name){
default:
}
}
}
customElements.define('eye-controls', EyeControls)
|
/*
* Copyright 2019 MediaMath
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mediamath.bid_valuator;
import com.google.common.base.Strings;
import com.google.openrtb.OpenRtb;
import com.mediamath.bid_valuator.WURFL.*;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
class HelperTest {
private static class DynamicWURFLTest<T extends WURFLValue> {
Class<T> valueClass;
String left, right, rightPropertyName;
DynamicWURFLTest(Class<T> valueClass, String left, String right, String rightPropertyName) {
this.valueClass = valueClass;
this.left = left;
this.right = right;
this.rightPropertyName = rightPropertyName;
}
@Override
public String toString() {
return "DynamicWURFLTest{" +
"valueClass=" + valueClass.getName() +
", left='" + left + '\'' +
", right='" + right + '\'' +
", rightPropertyName='" + rightPropertyName + '\'' +
'}';
}
}
static Stream<DynamicWURFLTest> wurflTests() {
return Stream.of(
// WURFLValue subclass, wurflText, left, right, right method name
new DynamicWURFLTest<>(Browser.class, "br_firefox", "ve_46.1.2", "version"),
new DynamicWURFLTest<>(Browser.class, "br_firefox", "ve_46.1.2", "version"),
new DynamicWURFLTest<>(Browser.class, "br_firefox", "", ""),
new DynamicWURFLTest<>(Device.class, "ma_samsung", "mo_sm-g360p", "model"),
new DynamicWURFLTest<>(Device.class, "ma_samsung", "", "model"),
new DynamicWURFLTest<>(DeviceFormFactor.class, "fo_smartphone", "unused", ""),
new DynamicWURFLTest<>(DeviceFormFactor.class, "fo_smartphone", "", ""),
new DynamicWURFLTest<>(OS.class, "os_windows", "ve_10.0.0", "version"),
new DynamicWURFLTest<>(OS.class, "os_windows", "", "version")
);
}
@ParameterizedTest
@NullAndEmptySource
void testEmptyWURFLText(String wurflText) {
Throwable thrown = catchThrowableOfType(() -> new WURFLValue(wurflText, true),
IllegalArgumentException.class);
assertThat(thrown).hasMessageContaining("null or empty Helper value");
}
@ParameterizedTest
@MethodSource("wurflTests")
<T extends WURFLValue> void testValueParse(DynamicWURFLTest<T> t) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<T> ctor = t.valueClass.getConstructor(String.class, boolean.class);
T value = ctor.newInstance(t.left + ":" + t.right, true);
assertThat(value)
.extracting(T::getLeft)
.first()
.isEqualTo(t.left);
if(!Strings.isNullOrEmpty(t.right)) {
assertThat(value.getRight())
.isEqualTo(t.right);
assertThat(value)
.extracting(T::isTwoPart)
.first()
.isEqualTo(true);
if(!Strings.isNullOrEmpty(t.rightPropertyName)) {
assertThat(BeanUtils.getSimpleProperty(value, t.rightPropertyName))
.isEqualTo(t.right);
}
} else {
assertThat(value.getRight())
.isNullOrEmpty();
}
}
@Test
void testBrowserDataExtraction() throws IOException {
OpenRtb.BidRequest bidRequest = com.mediamath.bid_valuator.Helper.allWURFLBidRequest();
List<Browser> browserResults = com.mediamath.bid_valuator.WURFL.Helper.getWURFLData(bidRequest.getExt().getMmExt().getSelectedEntities(0).getCompanionData(), Browser.class);
assertThat(browserResults)
.isNotEmpty()
.containsExactlyInAnyOrder(new Browser("br_firefox", true), new Browser("br_firefox:ve_46.1.2", false));
assertThat(com.mediamath.bid_valuator.WURFL.Helper.getBrowserData(bidRequest.getExt().getMmExt().getSelectedEntities(0)))
.hasSameElementsAs(browserResults);
}
@Test
void testOSDataExtraction() throws IOException {
OpenRtb.BidRequest bidRequest = com.mediamath.bid_valuator.Helper.allWURFLBidRequest();
List<OS> osResults = com.mediamath.bid_valuator.WURFL.Helper.getWURFLData(bidRequest.getExt().getMmExt().getSelectedEntities(0).getCompanionData(), OS.class);
assertThat(osResults)
.isNotEmpty()
.containsExactlyInAnyOrder(new OS("os_iOS", true), new OS("os_iOS:ve_12.1.0", false));
assertThat(com.mediamath.bid_valuator.WURFL.Helper.getOSData(bidRequest.getExt().getMmExt().getSelectedEntities(0)))
.hasSameElementsAs(osResults);
}
@Test
void testDeviceDataExtraction() throws IOException {
OpenRtb.BidRequest bidRequest = com.mediamath.bid_valuator.Helper.allWURFLBidRequest();
List<Device> deviceResults = com.mediamath.bid_valuator.WURFL.Helper.getWURFLData(bidRequest.getExt().getMmExt().getSelectedEntities(0).getCompanionData(), Device.class);
assertThat(deviceResults)
.isNotEmpty()
.containsExactlyInAnyOrder(new Device("ma_Apple:mo_iPhone", true));
assertThat(com.mediamath.bid_valuator.WURFL.Helper.getDeviceData(bidRequest.getExt().getMmExt().getSelectedEntities(0)))
.hasSameElementsAs(deviceResults);
}
@Test
void testDeviceFormFactorDataExtraction() throws IOException {
OpenRtb.BidRequest bidRequest = com.mediamath.bid_valuator.Helper.allWURFLBidRequest();
List<DeviceFormFactor> dffResults = com.mediamath.bid_valuator.WURFL.Helper.getWURFLData(bidRequest.getExt().getMmExt().getSelectedEntities(0).getCompanionData(), DeviceFormFactor.class);
assertThat(dffResults)
.isNotEmpty()
.containsExactlyInAnyOrder(new DeviceFormFactor("fo_Smartphone", true));
assertThat(com.mediamath.bid_valuator.WURFL.Helper.getDeviceFormFactorData(bidRequest.getExt().getMmExt().getSelectedEntities(0)))
.hasSameElementsAs(dffResults);
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ic_directions_car_twotone = void 0;
var ic_directions_car_twotone = {
"viewBox": "0 0 24 24",
"children": [{
"name": "path",
"attribs": {
"d": "M0 0h24v24H0V0z",
"fill": "none"
},
"children": []
}, {
"name": "path",
"attribs": {
"d": "M5 17h14v-5H5v5zm11.5-4c.83 0 1.5.67 1.5 1.5s-.67 1.5-1.5 1.5-1.5-.67-1.5-1.5.67-1.5 1.5-1.5zm-9 0c.83 0 1.5.67 1.5 1.5S8.33 16 7.5 16 6 15.33 6 14.5 6.67 13 7.5 13z",
"opacity": ".3"
},
"children": []
}, {
"name": "path",
"attribs": {
"d": "M18.92 6.01C18.72 5.42 18.16 5 17.5 5h-11c-.66 0-1.21.42-1.42 1.01L3 12v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.85 7h10.29l1.08 3.11H5.77L6.85 7zM19 17H5v-5h14v5z"
},
"children": []
}, {
"name": "circle",
"attribs": {
"cx": "7.5",
"cy": "14.5",
"r": "1.5"
},
"children": []
}, {
"name": "circle",
"attribs": {
"cx": "16.5",
"cy": "14.5",
"r": "1.5"
},
"children": []
}]
};
exports.ic_directions_car_twotone = ic_directions_car_twotone;
|
#! /bin/bash
#SBATCH -o /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2016_01_03_scalability_rexi_fd_high_res_run3/run_rexi_fd_par_m0512_t001_n0128_r3640_a1.txt
###SBATCH -e /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2016_01_03_scalability_rexi_fd_high_res_run3/run_rexi_fd_par_m0512_t001_n0128_r3640_a1.err
#SBATCH -J rexi_fd_par_m0512_t001_n0128_r3640_a1
#SBATCH --get-user-env
#SBATCH --clusters=mpp2
#SBATCH --ntasks=3640
#SBATCH --cpus-per-task=1
#SBATCH --exclusive
#SBATCH --export=NONE
#SBATCH --time=03:00:00
#declare -x NUMA_BLOCK_ALLOC_VERBOSITY=1
declare -x KMP_AFFINITY="granularity=thread,compact,1,0"
declare -x OMP_NUM_THREADS=1
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/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2016_01_03_scalability_rexi_fd_high_res_run3
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 1 -envall -ppn 28 -n 3640 ./build/rexi_fd_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 0 --rexi-h 0.8 --timestepping-mode 1 --staggering 0 --rexi-m=512 -C -5.0
|
from sklearn.svm import SVC
clf = SVC(kernel='linear')
clf.fit(x, y)
|
<gh_stars>1-10
import {Context} from 'makit';
import {extname} from 'path';
import {include} from './utils/filter';
import {parse} from './parse';
import {normalize as normalizeOptions, AmdNormalizeOptions} from './options';
export {aliasConf} from './options';
export function normalize(options: AmdNormalizeOptions) {
const normalizedOptions = normalizeOptions(options);
const {baseUrl, exclude} = normalizedOptions;
return (ctx: Context) => {
function done(result: string) {
ctx.writeTargetSync(result);
}
const filePath = ctx.dependencyPath();
let contents = ctx.readDependencySync();
if (extname(filePath) !== '.js') {
return done(contents);
}
if (include(filePath, exclude, baseUrl)) {
return done(contents);
}
try {
contents = parse(contents.toString(), {
...normalizedOptions,
filePath
});
}
catch (e) {
ctx.logger.warning('AMD', `${filePath} compile error \n |__${e.message}`);
}
done(contents);
};
};
|
<gh_stars>10-100
package org.quifft;
import org.quifft.output.FFTFrame;
import org.quifft.output.FFTResult;
import org.quifft.output.FrequencyBin;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestUtils {
/**
* Retrieves audio file from /test/resources directory
* @param fileName name of file in test resources directory
* @return audio file specified by fileName parameter
*/
static File getAudioFile(String fileName) {
Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "src", "test", "resources", fileName);
return filePath.toFile();
}
static double findMaxFrequencyBin(FFTFrame fftFrame) {
double maxAmplitude = -100;
double maxFrequencyBin = 0;
for(FrequencyBin bin : fftFrame.bins) {
if(bin.amplitude > maxAmplitude) {
maxAmplitude = bin.amplitude;
maxFrequencyBin = bin.frequency;
}
}
return maxFrequencyBin;
}
}
|
//Copyright (c) 2013-2016 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
//
//DISCLAIMERS
// No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND,
// EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT
// THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY
// THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED,
// WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN
// ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS,
// HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT
// SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING
// THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS."
//
// Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES
// GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF
// RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES
// OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING
// FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE
// UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT,
// TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE
// IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.
// X-Plane Connect Client
//
// DESCRIPTION
// Communicates with the XPC plugin to facilitate controling and gathering data from X-Plane.
//
// INSTRUCTIONS
// See Readme.md in the root of this repository or the wiki hosted on GitHub at
// https://github.com/nasa/XPlaneConnect/wiki for requirements, installation instructions,
// and detailed documentation.
//
// CONTACT
// For questions email <NAME> (<EMAIL>)
//
// CONTRIBUTORS
// CT: <NAME> (<EMAIL>)
// JW: <NAME> (<EMAIL>)
#include "xplaneConnect.h"
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#ifdef _WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif
int sendUDP(XPCSocket sock, char buffer[], int len);
int readUDP(XPCSocket sock, char buffer[], int len);
int sendDREFRequest(XPCSocket sock, const char* drefs[], unsigned char count);
int getDREFResponse(XPCSocket sock, float* values[], unsigned char count, int sizes[]);
void printError(char *functionName, char *format, ...)
{
va_list args;
va_start(args, format);
printf("[%s] ERROR: ", functionName);
vprintf(format, args);
printf("\n");
va_end(args);
}
/*****************************************************************************/
/**** Low Level UDP functions ****/
/*****************************************************************************/
XPCSocket openUDP(const char *xpIP)
{
return aopenUDP(xpIP, 49009, 0);
}
XPCSocket aopenUDP(const char *xpIP, unsigned short xpPort, unsigned short port)
{
XPCSocket sock;
// Setup Port
struct sockaddr_in recvaddr;
recvaddr.sin_family = AF_INET;
recvaddr.sin_addr.s_addr = INADDR_ANY;
recvaddr.sin_port = htons(port);
// Set X-Plane Port and IP
if (strcmp(xpIP, "localhost") == 0)
{
xpIP = "127.0.0.1";
}
strncpy(sock.xpIP, xpIP, 16);
sock.xpPort = xpPort == 0 ? 49009 : xpPort;
#ifdef _WIN32
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
printError("OpenUDP", "WSAStartup failed");
exit(EXIT_FAILURE);
}
#endif
if ((sock.sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
printError("OpenUDP", "Socket creation failed");
exit(EXIT_FAILURE);
}
if (bind(sock.sock, (struct sockaddr*)&recvaddr, sizeof(recvaddr)) == -1)
{
printError("OpenUDP", "Socket bind failed");
exit(EXIT_FAILURE);
}
// Set timeout to 100ms
#ifdef _WIN32
DWORD timeout = 100;
#else
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 250000;
#endif
if (setsockopt(sock.sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) < 0)
{
printError("OpenUDP", "Failed to set timeout");
}
return sock;
}
void closeUDP(XPCSocket sock)
{
#ifdef _WIN32
int result = closesocket(sock.sock);
#else
int result = close(sock.sock);
#endif
if (result < 0)
{
printError("closeUDP", "Failed to close socket");
exit(EXIT_FAILURE);
}
}
/// Sends the given data to the X-Plane plugin.
///
/// \param sock The socket to use to send the data.
/// \param buffer A pointer to the data to send.
/// \param len The number of bytes to send.
/// \returns If an error occurs, a negative number. Otehrwise, the number of bytes sent.
int sendUDP(XPCSocket sock, char buffer[], int len)
{
// Preconditions
if (len <= 0)
{
printError("sendUDP", "Message length must be positive.");
return -1;
}
// Set up destination address
struct sockaddr_in dst;
dst.sin_family = AF_INET;
dst.sin_port = htons(sock.xpPort);
inet_pton(AF_INET, sock.xpIP, &dst.sin_addr.s_addr);
int result = sendto(sock.sock, buffer, len, 0, (const struct sockaddr*)&dst, sizeof(dst));
if (result < 0)
{
printError("sendUDP", "Send operation failed.");
return -2;
}
if (result < len)
{
printError("sendUDP", "Unexpected number of bytes sent.");
}
return result;
}
/// Reads a datagram from the specified socket.
///
/// \param sock The socket to read from.
/// \param buffer A pointer to the location to store the data.
/// \param len The number of bytes to read.
/// \returns If an error occurs, a negative number. Otehrwise, the number of bytes read.
int readUDP(XPCSocket sock, char buffer[], int len)
{
#ifdef _WIN32
// Windows readUDP needs the select command- minimum timeout is 1ms.
// Without this playback becomes choppy
// Definitions
FD_SET stReadFDS;
FD_SET stExceptFDS;
// Setup for Select
FD_ZERO(&stReadFDS);
FD_SET(sock.sock, &stReadFDS);
FD_ZERO(&stExceptFDS);
FD_SET(sock.sock, &stExceptFDS);
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100000;
// Select Command
int status = select(-1, &stReadFDS, (FD_SET*)0, &stExceptFDS, &tv);
if (status < 0)
{
printError("readUDP", "Select command error");
return -1;
}
if (status == 0)
{
// No data
return 0;
}
status = recv(sock.sock, buffer, len, 0);
#else
// For apple or linux-just read - will timeout in 0.5 ms
int status = (int)recv(sock.sock, buffer, len, 0);
#endif
if (status < 0)
{
printError("readUDP", "Error reading socket");
}
return status;
}
/*****************************************************************************/
/**** End Low Level UDP functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** Configuration functions ****/
/*****************************************************************************/
int setCONN(XPCSocket* sock, unsigned short port)
{
// Set up command
char buffer[32] = "CONN";
memcpy(&buffer[5], &port, 2);
// Send command
if (sendUDP(*sock, buffer, 7) < 0)
{
printError("setCONN", "Failed to send command");
return -1;
}
// Switch socket
closeUDP(*sock);
*sock = aopenUDP(sock->xpIP, sock->xpPort, port);
// Read response
int result = readUDP(*sock, buffer, 32);
if (result <= 0)
{
printError("setCONN", "Failed to read response");
return -2;
}
if (strncmp(buffer, "CONF", 4) == 0)
{
// Response received succesfully.
return 0;
}
// Response incorrect
return -3;
}
int pauseSim(XPCSocket sock, char pause)
{
// Validte input
if (pause < 0 || pause > 2)
{
printError("pauseSim", "Invalid argument: %i", pause);
return -2;
}
// Setup command
char buffer[6] = "SIMU";
buffer[5] = pause;
// Send command
if (sendUDP(sock, buffer, 6) < 0)
{
printError("pauseSim", "Failed to send command");
return -1;
}
return 0;
}
/*****************************************************************************/
/**** End Configuration functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** X-Plane UDP Data functions ****/
/*****************************************************************************/
int sendDATA(XPCSocket sock, float data[][9], int rows)
{
// Preconditions
// There are only 134 DATA rows in X-Plane. Realistically, clients probably
// shouldn't be trying to set nearly this much data at once anyway.
if (rows > 134)
{
printError("sendDATA", "Too many rows.");
return -1;
}
// Setup command
// 5 byte header + 134 rows * 9 values * 4 bytes per value => 4829 byte max length.
char buffer[4829] = "DATA";
int len = 5 + rows * 9 * sizeof(float);
unsigned short step = 9 * sizeof(float);
int i; // iterator
for (i = 0; i < rows; i++)
{
buffer[5 + i * step] = (char)data[i][0];
memcpy(&buffer[9 + i*step], &data[i][1], 8 * sizeof(float));
}
// Send command
if (sendUDP(sock, buffer, len ) < 0)
{
printError("sendDATA", "Failed to send command");
return -2;
}
return 0;
}
int readDATA(XPCSocket sock, float data[][9], int rows)
{
// Preconditions
// There are only 134 DATA rows in X-Plane. Realistically, clients probably
// shouldn't be trying to read nearly this much data at once anyway.
if (rows > 134)
{
printError("readDATA", "Too many rows.");
// Read as much as we can anyway
rows = 134;
}
// Read data
char buffer[4829] = { 0 };
int result = readUDP(sock, buffer, 4829);
if (result <= 0)
{
printError("readDATA", "Failed to read from socket.");
return -1;
}
// Validate data
int readRows = (result - 5) / 36;
if (readRows > rows)
{
printError("readDATA", "Read more rows than will fit in dataRef.");
}
else if (readRows < rows)
{
printError("readDATA", "Read fewer rows than expected.");
// Copy as much data as we read anyway
rows = readRows;
}
// Parse data
int i; // iterator
for (i = 0; i < rows; ++i)
{
data[i][0] = buffer[5 + i * 36];
memcpy(&data[i][1], &buffer[9 + i * 36], 8 * sizeof(float));
}
return rows;
}
/*****************************************************************************/
/**** End X-Plane UDP Data functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** DREF functions ****/
/*****************************************************************************/
int sendDREF(XPCSocket sock, const char* dref, float value[], int size)
{
return sendDREFs(sock, &dref, &value, &size, 1);
}
int sendDREFs(XPCSocket sock, const char* drefs[], float* values[], int sizes[], int count)
{
// Setup command
// Max size is technically unlimited.
unsigned char buffer[65536] = "DREF";
int pos = 5;
int i; // Iterator
for (i = 0; i < count; ++i)
{
int drefLen = strnlen(drefs[i], 256);
if (pos + drefLen + sizes[i] * 4 + 2 > 65536)
{
printError("sendDREF", "About to overrun the send buffer!");
return -4;
}
if (drefLen > 255)
{
printError("sendDREF", "dref %d is too long. Must be less than 256 characters.", i);
return -1;
}
if (sizes[i] > 255)
{
printError("sendDREF", "size %d is too big. Must be less than 256.", i);
return -2;
}
// Copy dref to buffer
buffer[pos++] = (unsigned char)drefLen;
memcpy(buffer + pos, drefs[i], drefLen);
pos += drefLen;
// Copy values to buffer
buffer[pos++] = (unsigned char)sizes[i];
memcpy(buffer + pos, values[i], sizes[i] * sizeof(float));
pos += sizes[i] * sizeof(float);
}
// Send command
if (sendUDP(sock, buffer, pos) < 0)
{
printError("setDREF", "Failed to send command");
return -3;
}
return 0;
}
int sendDREFRequest(XPCSocket sock, const char* drefs[], unsigned char count)
{
// Setup command
// 6 byte header + potentially 255 drefs, each 256 chars long.
// Easiest to just round to an even 2^16.
unsigned char buffer[65536] = "GETD";
buffer[5] = count;
int len = 6;
int i; // iterator
for (i = 0; i < count; ++i)
{
size_t drefLen = strnlen(drefs[i], 256);
if (drefLen > 255)
{
printError("getDREFs", "dref %d is too long.", i);
return -1;
}
buffer[len++] = (unsigned char)drefLen;
strncpy(buffer + len, drefs[i], drefLen);
len += drefLen;
}
// Send Command
if (sendUDP(sock, buffer, len) < 0)
{
printError("getDREFs", "Failed to send command");
return -2;
}
return 0;
}
int getDREFResponse(XPCSocket sock, float* values[], unsigned char count, int sizes[])
{
unsigned char buffer[65536];
int result = readUDP(sock, buffer, 65536);
if (result < 0)
{
#ifdef _WIN32
printError("getDREFs", "Read operation failed. (%d)", WSAGetLastError());
#else
printError("getDREFs", "Read operation failed.");
#endif
return -1;
}
if (result < 6)
{
printError("getDREFs", "Response was too short. Expected at least 6 bytes, but only got %d.", result);
return -2;
}
if (buffer[5] != count)
{
printError("getDREFs", "Unexpected response size. Expected %d rows, got %d instead.", count, buffer[5]);
return -3;
}
int cur = 6;
int i; // Iterator
for (i = 0; i < count; ++i)
{
int l = buffer[cur++];
if (l > sizes[i])
{
printError("getDREFs", "values is too small. Row had %d values, only room for %d.", l, sizes[i]);
// Copy as many values as we can anyway
memcpy(values[i], buffer + cur, sizes[i] * sizeof(float));
}
else
{
memcpy(values[i], buffer + cur, l * sizeof(float));
sizes[i] = l;
}
cur += l * sizeof(float);
}
return 0;
}
int getDREF(XPCSocket sock, const char* dref, float values[], int* size)
{
return getDREFs(sock, &dref, &values, 1, size);
}
int getDREFs(XPCSocket sock, const char* drefs[], float* values[], unsigned char count, int sizes[])
{
// Send Command
int result = sendDREFRequest(sock, drefs, count);
if (result < 0)
{
// A error ocurred while sending.
// sendDREFRequest will print an error message, so just return.
return -1;
}
// Read Response
if (getDREFResponse(sock, values, count, sizes) < 0)
{
// A error ocurred while reading the response.
// getDREFResponse will print an error message, so just return.
return -2;
}
return 0;
}
/*****************************************************************************/
/**** End DREF functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** POSI functions ****/
/*****************************************************************************/
int getPOSI(XPCSocket sock, float values[7], char ac)
{
// Setup send command
unsigned char buffer[6] = "GETP";
buffer[5] = ac;
// Send command
if (sendUDP(sock, buffer, 6) < 0)
{
printError("getPOSI", "Failed to send command.");
return -1;
}
// Get response
unsigned char readBuffer[34];
int readResult = readUDP(sock, readBuffer, 34);
if (readResult < 0)
{
printError("getPOSI", "Failed to read response.");
return -2;
}
if (readResult != 34)
{
printError("getPOSI", "Unexpected response length.");
return -3;
}
// Copy response into values
memcpy(values, readBuffer + 6, 7 * sizeof(float));
return 0;
}
int sendPOSI(XPCSocket sock, float values[], int size, char ac)
{
// Validate input
if (ac < 0 || ac > 20)
{
printError("sendPOSI", "aircraft should be a value between 0 and 20.");
return -1;
}
if (size < 1 || size > 7)
{
printError("sendPOSI", "size should be a value between 1 and 7.");
return -2;
}
// Setup command
// 5 byte header + up to 7 values * 5 bytes each
unsigned char buffer[40] = "POSI";
buffer[5] = ac;
int i; // iterator
for (i = 0; i < 7; i++)
{
float val = -998;
if (i < size)
{
val = values[i];
}
*((float*)(buffer + 6 + i * 4)) = val;
}
// Send Command
if (sendUDP(sock, buffer, 40) < 0)
{
printError("sendPOSI", "Failed to send command");
return -3;
}
return 0;
}
/*****************************************************************************/
/**** End POSI functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** CTRL functions ****/
/*****************************************************************************/
int getCTRL(XPCSocket sock, float values[7], char ac)
{
// Setup send command
unsigned char buffer[6] = "GETC";
buffer[5] = ac;
// Send command
if (sendUDP(sock, buffer, 6) < 0)
{
printError("getCTRL", "Failed to send command.");
return -1;
}
// Get response
unsigned char readBuffer[31];
int readResult = readUDP(sock, readBuffer, 31);
if (readResult < 0)
{
printError("getCTRL", "Failed to read response.");
return -2;
}
if (readResult != 31)
{
printError("getCTRL", "Unexpected response length.");
return -3;
}
// Copy response into values
memcpy(values, readBuffer + 5, 4 * sizeof(float));
values[4] = readBuffer[21];
values[5] = *((float*)(readBuffer + 22));
values[6] = *((float*)(readBuffer + 27));
return 0;
}
int sendCTRL(XPCSocket sock, float values[], int size, char ac)
{
// Validate input
if (ac < 0 || ac > 20)
{
printError("sendCTRL", "aircraft should be a value between 0 and 20.");
return -1;
}
if (size < 1 || size > 7)
{
printError("sendCTRL", "size should be a value between 1 and 7.");
return -2;
}
// Setup Command
// 5 byte header + 5 float values * 4 + 2 byte values
unsigned char buffer[31] = "CTRL";
int cur = 5;
int i; // iterator
for (i = 0; i < 6; i++)
{
float val = -998;
if (i < size)
{
val = values[i];
}
if (i == 4)
{
buffer[cur++] = val == -998 ? -1 : (unsigned char)val;
}
else
{
*((float*)(buffer + cur)) = val;
cur += sizeof(float);
}
}
buffer[26] = ac;
*((float*)(buffer + 27)) = size == 7 ? values[6]: -998;
// Send Command
if (sendUDP(sock, buffer, 31) < 0)
{
printError("sendCTRL", "Failed to send command");
return -3;
}
return 0;
}
/*****************************************************************************/
/**** End CTRL functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** Drawing functions ****/
/*****************************************************************************/
int sendTEXT(XPCSocket sock, char* msg, int x, int y)
{
if (msg == NULL)
{
msg = "";
}
size_t msgLen = strnlen(msg, 255);
// Input Validation
if (x < -1)
{
printError("sendTEXT", "x should be positive (or -1 for default).");
// Technically, this should work, and may print something to the screen.
}
if (y < -1)
{
printError("sendTEXT", "y should be positive (or -1 for default).");
// Negative y will never result in text being displayed.
return -1;
}
if (msgLen > 255)
{
printError("sendTEXT", "msg must be less than 255 bytes.");
return -2;
}
// Setup command
// 5 byte header + 8 byte position + up to 256 byte message
char buffer[269] = "TEXT";
size_t len = 14 + msgLen;
memcpy(buffer + 5, &x, sizeof(int));
memcpy(buffer + 9, &y, sizeof(int));
buffer[13] = msgLen;
strncpy(buffer + 14, msg, msgLen);
// Send Command
if (sendUDP(sock, buffer, len) < 0)
{
printError("sendTEXT", "Failed to send command");
return -3;
}
return 0;
}
int sendWYPT(XPCSocket sock, WYPT_OP op, float points[], int count)
{
// Input Validation
if (op < XPC_WYPT_ADD || op > XPC_WYPT_CLR)
{
printError("sendWYPT", "Unrecognized operation.");
return -1;
}
if (count > 255)
{
printError("sendWYPT", "Too many points. Must be less than 256.");
return -2;
}
// Setup Command
// 7 byte header + 12 bytes * count
char buffer[3067] = "WYPT";
buffer[5] = (unsigned char)op;
buffer[6] = (unsigned char)count;
size_t ptLen = sizeof(float) * 3 * count;
memcpy(buffer + 7, points, ptLen);
// Send Command
if (sendUDP(sock, buffer, 7 + 12 * count) < 0)
{
printError("sendWYPT", "Failed to send command");
return -2;
}
return 0;
}
/*****************************************************************************/
/**** End Drawing functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** View functions ****/
/*****************************************************************************/
int sendVIEW(XPCSocket sock, VIEW_TYPE view)
{
// Validate Input
if (view < XPC_VIEW_FORWARDS || view > XPC_VIEW_FULLSCREENNOHUD)
{
printError("sendVIEW", "Unrecognized view");
return -1;
}
// Setup Command
char buffer[9] = "VIEW";
*((int*)(buffer + 5)) = view;
// Send Command
if (sendUDP(sock, buffer, 9) < 0)
{
printError("sendVIEW", "Failed to send command");
return -2;
}
return 0;
}
/*****************************************************************************/
/**** End View functions ****/
/*****************************************************************************/
/*****************************************************************************/
/**** Comm functions ****/
/*****************************************************************************/
int sendCOMM(XPCSocket sock, const char* comm) {
// Setup command
// Max size is technically unlimited.
unsigned char buffer[65536] = "COMM";
int pos = 5;
int commLen = strnlen(comm, 256);
if (pos + commLen + 2 > 65536)
{
printError("sendCOMM", "About to overrun the send buffer!");
return -4;
}
if (commLen > 255)
{
printError("sendCOMM", "comm is too long. Must be less than 256 characters.");
return -1;
}
// Copy comm to buffer
buffer[pos++] = (unsigned char)commLen;
memcpy(buffer + pos, comm, commLen);
pos += commLen;
// Send command
if (sendUDP(sock, buffer, pos) < 0)
{
printError("setDREF", "Failed to send command");
return -3;
}
return 0;
}
|
/*
* Copyright(c) Archway Inc. All rights reserved.
*/
;(function (global, $, undef) {
"use strict";
var ddlmenu = App.define("App.ui.ddlmenu", {
setting: {},
isShowed: false,
context: {},
settings: function (title, setting) {
ddlmenu.settingsObj = {
title: title,
setting: setting
};
},
settingsObj: {},
setup: function (role, container, baseUrl) {
var base = baseUrl.replace(/\/$/, "");
ddlmenu.setting = ddlmenu.settingsObj || { setting: [], title: "" };
role = App.ifUndefOrNull(role, "");
var root = createTopElement(ddlmenu.setting.setting || [], 1001, role, base);
$(container).append(root);
}
});
var isVisibleRole = function (item, role) {
var visible = false,
i;
if (!item.visible) {
return true;
}
// visible が "*" 以外の文字列で指定されていて、 role と一致しない場合は表示しない
if (App.isStr(item.visible) && item.visible !== "*" && item.visible !== role) {
return visible;
}
// visible が 配列で role とどれも一致しない場合は表示しない
else if (App.isArray(item.visible)) {
for (i = 0; i < item.visible.length; i++) {
if (item.visible[i] === role) {
visible = true;
break;
}
}
return visible;
}
// visible が 関数で戻り値が false の場合は表示しない
else if (App.isFunc(item.visible)) {
return item.visible(role);
}
return true;
};
var createTopElement = function (items, zIndex, role, baseUrl) {
var ul = $('<ul class="nav navbar-nav"></ul>'),
li,
i,
item;
for (i = 0; i < items.length; i++) {
item = items[i];
//if (!isVisibleRole(item, role)) {
// continue;
//}
li = $("<li></li>");
if (item.items && item.items.length) {
li.append("<a class='dropdown-toggle' data-toggle='dropdown' href='" + (item.url ? baseUrl + item.url : "#") + "'>" + item.display + "<b class='caret'></b></a>");
var ddl = $('<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu"></ul>');
createItemsElement(ddl, item.items, zIndex, role, baseUrl);
li.append(ddl);
li.addClass("dropdown");
}
else if (item.url) {
li.append("<a href='" + baseUrl + item.url + "'>" + item.display + "</a>");
}
ul.append(li);
}
return ul;
};
var createItemsElement = function (ul, items, zIndex, role, baseUrl) {
var li,
i, len,
item;
for (i = 0, len = items.length; i < len; i++) {
item = items[i];
//if (!isVisibleRole(item, role)) {
// continue;
//}
li = $("<li role='presentation'></li>");
ul.append(li);
if (item.items && item.items.length) {
li.addClass("dropdown-header");
li.text(item.display);
createItemsElement(ul, item.items, zIndex, role, baseUrl);
ul.append("<li role='presentation' class='divider'></li>");
}
else if (item.url) {
li.append("<a href='" + baseUrl + item.url + "'>" + item.display + "</a>");
}
}
return ul;
};
})(this, jQuery);
|
#!/bin/bash -e
IMG_FILE="${STAGE_WORK_DIR}/${IMG_FILENAME}${IMG_SUFFIX}.img"
NOOBS_DIR="${STAGE_WORK_DIR}/${IMG_DATE}-${IMG_NAME}${IMG_SUFFIX}"
unmount_image "${IMG_FILE}"
mkdir -p "${STAGE_WORK_DIR}"
cp "${WORK_DIR}/export-image/${IMG_FILENAME}${IMG_SUFFIX}.img" "${STAGE_WORK_DIR}/"
rm -rf "${NOOBS_DIR}"
PARTED_OUT=$(parted -sm "${IMG_FILE}" unit b print)
BOOT_OFFSET=$(echo "$PARTED_OUT" | grep -e '^1:' | cut -d':' -f 2 | tr -d B)
BOOT_LENGTH=$(echo "$PARTED_OUT" | grep -e '^1:' | cut -d':' -f 4 | tr -d B)
ROOT_OFFSET=$(echo "$PARTED_OUT" | grep -e '^2:' | cut -d':' -f 2 | tr -d B)
ROOT_LENGTH=$(echo "$PARTED_OUT" | grep -e '^2:' | cut -d':' -f 4 | tr -d B)
sleep 5
BOOT_DEV=$(losetup --show -f -o "${BOOT_OFFSET}" --sizelimit "${BOOT_LENGTH}" "${IMG_FILE}")
sleep 5
ROOT_DEV=$(losetup --show -f -o "${ROOT_OFFSET}" --sizelimit "${ROOT_LENGTH}" "${IMG_FILE}")
echo "/boot: offset $BOOT_OFFSET, length $BOOT_LENGTH"
echo "/: offset $ROOT_OFFSET, length $ROOT_LENGTH"
mkdir -p "${STAGE_WORK_DIR}/rootfs"
mkdir -p "${NOOBS_DIR}"
mount "$ROOT_DEV" "${STAGE_WORK_DIR}/rootfs"
mount "$BOOT_DEV" "${STAGE_WORK_DIR}/rootfs/boot"
ln -sv "/lib/systemd/system/apply_noobs_os_config.service" "$ROOTFS_DIR/etc/systemd/system/multi-user.target.wants/apply_noobs_os_config.service"
bsdtar --numeric-owner --format gnutar -C "${STAGE_WORK_DIR}/rootfs/boot" -cpf - . | xz -T0 > "${NOOBS_DIR}/boot.tar.xz"
umount "${STAGE_WORK_DIR}/rootfs/boot"
bsdtar --numeric-owner --format gnutar -C "${STAGE_WORK_DIR}/rootfs" --one-file-system -cpf - . | xz -T0 > "${NOOBS_DIR}/root.tar.xz"
unmount_image "${IMG_FILE}"
|
import { $ } from './Class/$'
import { Dict } from './types/Dict'
export function envolve(
interf: Dict<(...args: any[]) => any>,
__: string[]
): $ {
return new (class Class extends $ {
_ = __
constructor() {
super()
for (const name in interf) {
const method = interf[name]
this[name] = method
}
}
})()
}
|
<gh_stars>0
package com.quasar.javatostring.json;
public class SimpleObject {
private final String aString;
private final Integer anInteger;
private final Boolean aBoolean;
private final Object aNull;
public SimpleObject() {
aString = SimpleProperties.DEFAULT_STRING;
anInteger = SimpleProperties.DEFAULT_INTEGER;
aBoolean = SimpleProperties.DEFAULT_BOOLEAN;
aNull = null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
sb.append("\"aString\": \"").append(aString).append('\"');
sb.append(", \"anInteger\": ").append(anInteger);
sb.append(", \"aBoolean\": ").append(aBoolean);
sb.append(", \"aNull\": ").append(aNull);
sb.append("}");
return sb.toString();
}
}
|
<reponame>ES-UFABC/UFABCplanner
import { forwardRef, useImperativeHandle, useState } from 'react';
import { FiX } from 'react-icons/fi';
import { IconButton } from '../IconButton';
import styles from './Modal.module.scss';
interface Props {
children: React.ReactNode;
title: string;
onClose?: () => void;
width?: string;
}
export interface ModalRef {
handleOpenModal: () => void;
handleCloseModal: () => void;
}
const Modal = forwardRef<ModalRef, Props>(({ children, title, onClose, width = '400px' }, ref) => {
const [open, setOpen] = useState(false);
useImperativeHandle(ref, () => ({
handleOpenModal: () => setOpen(true),
handleCloseModal: () => setOpen(false),
}), []);
if (!open) return <></>;
return (
<div className={styles.modal_container}>
<div className={styles.modal} style={{ width }}>
<div className={styles.modal_header}>
<b className={styles.modal_title}>{title}</b>
<IconButton onClick={() => { setOpen(false); if (onClose) onClose(); }} icon={FiX}/>
</div>
{children}
</div>
</div>
);
});
export default Modal;
|
package com.mcserver;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
public class MCServerInstaller {
private MCServerActivity mContext;
final private String BaseDirectory = "basedir";
final private String PluginDirectory = "Plugins";
final public String SHARED_PREFS_NAME = "MCSERVER_PREFS";
final public String PREF_IS_INSTALLED = "IS_INSTALLED";
final public String PREF_LAST_VERSION = "LAST_VERSION";
private SharedPreferences mSettings = null;
int thisVersion;
MCServerInstaller( MCServerActivity activity )
{
mContext = activity;
mSettings = mContext.getSharedPreferences( SHARED_PREFS_NAME, 0);
try {
this.thisVersion = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
} catch (NameNotFoundException e) {
Log.e("MCServer", "Could not read version code from manifest!");
e.printStackTrace();
this.thisVersion = -1;
}
}
public boolean IsInstalled()
{
return mSettings.getBoolean(PREF_IS_INSTALLED, false);
}
public boolean NeedsUpdate()
{
Log.i("MCServer", "thisVersion: " + this.thisVersion + " pref: " + mSettings.getInt(PREF_LAST_VERSION, 0));
return mSettings.getInt(PREF_LAST_VERSION, 0) != this.thisVersion;
}
public ArrayList<String> FindFoldersInPath(String path)
{
ArrayList<String> allFolders = new ArrayList<String>();
AssetManager am = mContext.getAssets();
try {
String[] allPlugins = am.list(path);
for(String pluginName : allPlugins)
{
InputStream istr = null;
try
{
istr = am.open(path + "/" + pluginName);
} catch( java.io.FileNotFoundException e ) {
// It seems to be a folder :D
allFolders.add(pluginName);
continue;
}
istr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return allFolders;
}
public void ExpandAssets( String path )
{
AssetManager am = mContext.getAssets();
try {
String[] getAssets = am.list(path);
for(String assetName : getAssets)
{
//Log.e("MCServer", path + "/" + imgName);
InputStream istr = null;
try
{
istr = am.open(path + "/" + assetName);
} catch( java.io.FileNotFoundException e ) {
//Log.e("MCServer", "Could not open" + path + "/" + imgName );
ExpandAssets(path + "/" + assetName);
continue;
}
String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/" + path + "/" + assetName;
//Log.e("MCServer", "outPath: " + outPath );
File f = new File( outPath );
f.getParentFile().mkdirs();
f.createNewFile();
OutputStream ostr = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length;
while ((length = istr.read(buffer))>0)
{
ostr.write(buffer, 0, length);
}
ostr.flush();
ostr.close();
istr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
void ShowFirstRunDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//builder.setTitle("blaa");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setMessage("It seems this is the first time you are running MCServer on your Android device or it has been updated! This app comes with a couple of pre-packaged plugins, please take a moment to select the plugins you would like to install.");
builder.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
dialog.setOnDismissListener( new DialogInterface.OnDismissListener(){
public void onDismiss(DialogInterface dialog) {
ShowPluginInstallDialog(false);
}
});
}
public void ShowPluginInstallDialog(boolean bCancelable)
{
final ArrayList<String> allPlugins = FindFoldersInPath( BaseDirectory + "/" + PluginDirectory );
final CharSequence[] items = allPlugins.toArray(new CharSequence[allPlugins.size()]);
final boolean[] selected = new boolean[items.length];
for( int i = 0; i < items.length; ++i )
{
if( items[i].toString().contains("Core") )
{ // Select the core plugin by default
selected[i] = true;
items[i] = items[i] + " (Recommended)";
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Plugins to install");
builder.setCancelable(bCancelable);
builder.setMultiChoiceItems(items, selected, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
selected[which] = isChecked;
}
});
builder.setPositiveButton("Install", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ArrayList<String> toInstall = new ArrayList<String>();
for( int i = 0; i < selected.length; ++i )
{
if( selected[i] )
{
toInstall.add(allPlugins.get(i));
}
}
InstallPlugins(toInstall);
}
});
AlertDialog dialog2 = builder.create();
dialog2.show();
}
void InstallPlugins( final ArrayList<String> plugins )
{
new AsyncTask<Void, Integer, Boolean>()
{
ProgressDialog progressDialog;
@Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(mContext, "", "Installing...");
}
@Override
protected Boolean doInBackground(Void... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
for( int i = 0; i < plugins.size(); ++i )
{
this.publishProgress((int)(i / (float)plugins.size() * 100), i);
InstallSinglePlugin(PluginDirectory + "/" + plugins.get(i));
}
this.publishProgress( 100, -1 );
InstallExampleSettings();
this.publishProgress( 100, -2 );
InstallWebAdmin();
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
protected void onProgressUpdate(Integer... progress)
{
progressDialog.setProgress(progress[0]);
if( progress[1] > -1 )
{
progressDialog.setMessage("Installing " + plugins.get(progress[1]) + "..." );
}
else if( progress[1] == -1 )
{
progressDialog.setMessage("Installing default settings...");
}
else if( progress[1] == -2 )
{
progressDialog.setMessage("Installing WebAdmin...");
}
}
@Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(mContext);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Install succeeded");
SharedPreferences.Editor editor = mSettings.edit();
editor.putBoolean(PREF_IS_INSTALLED, true);
editor.putInt(PREF_LAST_VERSION, thisVersion);
editor.commit();
}
else
{
b.setMessage("Install failed");
}
b.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
b.create().show();
}
}.execute();
}
void InstallExampleSettings()
{
AssetManager am = mContext.getAssets();
try {
String[] allFiles = am.list(BaseDirectory);
for(String fileName : allFiles)
{
InputStream istr = null;
try
{
istr = am.open(BaseDirectory + "/" + fileName);
} catch( java.io.FileNotFoundException e ) {
// Must be a folder :D
continue;
}
String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/" + fileName;
Log.i("MCServer", "outPath: " + outPath );
File f = new File( outPath );
f.getParentFile().mkdirs();
f.createNewFile();
OutputStream ostr = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length;
while ((length = istr.read(buffer))>0)
{
ostr.write(buffer, 0, length);
}
ostr.flush();
ostr.close();
istr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
void InstallWebAdmin()
{
AssetManager am = mContext.getAssets();
try {
String[] allFiles = am.list(BaseDirectory + "/webadmin");
for(String fileName : allFiles)
{
InputStream istr = null;
try
{
istr = am.open(BaseDirectory + "/webadmin/" + fileName);
} catch( java.io.FileNotFoundException e ) {
// Must be a folder :D
continue;
}
String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/webadmin/" + fileName;
Log.i("MCServer", "outPath: " + outPath );
File f = new File( outPath );
f.getParentFile().mkdirs();
f.createNewFile();
OutputStream ostr = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length;
while ((length = istr.read(buffer))>0)
{
ostr.write(buffer, 0, length);
}
ostr.flush();
ostr.close();
istr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
void InstallSinglePlugin( String path )
{
AssetManager am = mContext.getAssets();
try {
String[] getImages = am.list(BaseDirectory + "/" + path);
for(String imgName : getImages)
{
Log.i("MCServer", path + "/" + imgName);
InputStream istr = null;
try
{
istr = am.open(BaseDirectory + "/" + path + "/" + imgName);
} catch( java.io.FileNotFoundException e ) {
Log.i("MCServer", "Could not open" + path + "/" + imgName );
InstallSinglePlugin(path + "/" + imgName);
continue;
}
String outPath = Environment.getExternalStorageDirectory().getPath() + "/mcserver/" + path + "/" + imgName;
Log.i("MCServer", "outPath: " + outPath );
File f = new File( outPath );
f.getParentFile().mkdirs();
f.createNewFile();
OutputStream ostr = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int length;
while ((length = istr.read(buffer))>0)
{
ostr.write(buffer, 0, length);
}
ostr.flush();
ostr.close();
istr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
<reponame>kavehjamshidi/url-shortener
module.exports = (req, res) => {
return res.status(200).render('about');
};
|
#!/bin/bash
# Enable Fake KMS driver
# ----------------------
# Author: Henrik Noerfjand Stengaard
# Date: 2022-01-13
#
# Bash script to enable fake kms driver.
# Enabled use of DispmanX, but considered legacy
# install
install=0
# parse arguments
for i in "$@"
do
case $i in
-i|--install)
install=1
shift
;;
-id=*|--installdir=*)
installdir="${i#*=}"
shift
;;
-kd=*|--kickstartsdir=*)
kickstartsdir="${i#*=}"
shift
;;
*)
# unknown argument
;;
esac
done
# show dialog
dialog --clear --stdout \
--title "Enable Fake KMS video driver" \
--yesno "Fake KMS video driver is considered legacy, but required by UAE4ARM Amiga emulator as it uses DispmanX. Without fake KMS video driver, UAE4ARM will show a black screen. Both Amiberry and UAE4ARM Amiga emulators work with fake KMS video driver enabled.\n\nEnabling fake KMS video driver will first take effect when Raspberry Pi is rebooted.\n\nDo you want to enable fake KMS video driver?" 0 0
# exit, if no is selected
if [ $? -ne 0 ]; then
exit
fi
# create backup of config.txt, if it doesn't exist
if [ ! -f /boot/config.txt.bak ]; then
sudo cp /boot/config.txt /boot/config.txt.bak
fi
# update config.txt
sudo sed -e "s/^\(dtoverlay=\)/#\1/gi" /boot/config.txt >>/tmp/config.txt
echo "dtoverlay=vc4-fkms-v3d" >>/tmp/config.txt
sudo cp /tmp/config.txt /boot/config.txt
rm /tmp/config.txt
# show reboot dialog, not install
if [ $install == 0 ]; then
# show reboot dialog
dialog --clear --stdout \
--title "Reboot" \
--yesno "Enabling fake KMS video driver will first take effect when Raspberry Pi is rebooted.\n\nDo you want to reboot now?" 0 0
# reboot, if yes is selected
if [ $? -eq 0 ]; then
sudo reboot
fi
fi
|
#!/bin/bash
set -euxo pipefail
RELEASE_VERSION="$1"
BRANCH="$2"
REPOSITORY="$3"
ACCESS_TOKEN="$4"
generate_post_data()
{
cat <<EOF
{
"tag_name": "$RELEASE_VERSION",
"target_commitish": "$BRANCH",
"name": "$RELEASE_VERSION",
"body": "",
"draft": false,
"prerelease": false
}
EOF
}
echo "Creating github release '$RELEASE_VERSION' for Repo '$REPOSITORY' and Branch: '$BRANCH'"
curl -H "Authorization: token $ACCESS_TOKEN" --data "$(generate_post_data)" "https://api.github.com/repos/$REPOSITORY/releases"
echo "Github Release Created Successfully"
|
cd ..
rm -rf ./Tamagotchi/bin/
rm -rf ./Tamagotchi/obj/
rm -rf ./Tamagotchi.Tests/bin/
rm -rf ./Tamagotchi.Tests/obj/
./Commands/fresh.sh
|
Common properties of high-level programming languages include: object-oriented features such as abstraction and polymorphism, support for database access, built-in string manipulation capabilities, an extensive set of standard library functions, widespread availability of interpreters and compilers, support for multiple-threaded execution and dynamic memory allocation, and a generally easier to learn syntax than lower-level languages.
|
package math;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author minchoba
* 백준 1940번: 주몽
*
* @see https://www.acmicpc.net/problem/1940/
*
*/
public class Boj1940 {
public static void main(String[] args) throws Exception{
// 버퍼를 통한 값 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int M = Integer.parseInt(br.readLine());
int[] nums = new int[N]; // 갑옷 재료를 나타내는 숫자를 담을 배열
boolean[] isVisited = new boolean[N]; // 해당 재료가 이미 쓰인 재료인지 확인
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < N; i++){
nums[i] = Integer.parseInt(st.nextToken());
}
int res = 0;
for(int i = 0; i < N; i++){
if(isVisited[i]) continue; // 이미 사용된 재료라면 다음 재료로 넘어감
for(int j = i + 1; j < N; j++){
if(M - nums[i] == nums[j]){ // (제작할 갑옷의 재료합 - 임의의 재료 값) == (임의의 재료를 제외한 나머지 중 하나) 일 경우
isVisited[i] = true; // 제작한 재료로 표시 한 후
res++; // 제작 갑옷 +1
break; // 다음 i번째 재료로 바로 넘어감
}
}
}
System.out.println(res); // 총 제작된 갑옷의 수를 출력
}
}
|
//
// Created by ooooo on 2020/1/8.
//
#ifndef CPP_0234_SOLUTION2_H
#define CPP_0234_SOLUTION2_H
#include "ListNode.h"
class Solution {
public:
bool isPalindrome(ListNode *head) {
if (!head || !head->next) return true;
ListNode *low = head, *fast = head, *prev = nullptr, *temp = nullptr;
while (fast->next && fast->next->next) {
fast = fast->next->next;
temp = low->next;
low->next = prev;
prev = low;
low = temp;
}
ListNode *left = nullptr;
ListNode *right = low->next;
if (!fast->next) {
left = prev;
} else {
low->next = prev;
left = low;
}
bool match = true;
while (match && left && right) {
if (left->val != right->val) {
match = false;
break;
}
left = left->next;
right = right->next;
}
return match;
}
};
#endif //CPP_0234_SOLUTION2_H
|
class MessagePublisher:
def __init__(self, hermes_settings):
self.hermes_settings = hermes_settings
def publish_message(self, topic, message):
if topic == 'TOPICS_ALL':
topics = list(self.hermes_settings.PUBLISHING_TOPICS.keys())
else:
topics = [topic]
for topic in topics:
try:
print('Sending message to {}'.format(topic))
self.publish(topic, {'result': message})
except HermesPublishException as e:
print(str(e), file=sys.stderr)
else:
print('Message was sent successfully to {}!'.format(topic))
def publish(self, topic, message):
# Placeholder for the actual message publishing logic
pass
# Usage example
hermes_settings = ... # Initialize hermes_settings with appropriate values
publisher = MessagePublisher(hermes_settings)
publisher.publish_message('topic1', 'Hello, topic 1!')
publisher.publish_message('TOPICS_ALL', 'Hello, all topics!')
|
import requests
def generate_number():
url = 'https://www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
response = requests.get(url)
if response.status_code == 200:
return int(response.text)
else:
return None
|
import * as numjs from 'numjs';
import { IVehicle } from './ElementInterface';
import { ICanvasState } from '../components/Canvas/CanvasInterfaces';
import { magnitude, normalize, getCoordinateAfterRotation, limit, mapping, findNormalPoint } from '../utils/math';
import FlowField from './FlowField';
import Path from './Path';
export default class Vehicle implements IVehicle {
mass: number;
size: number;
location: nj.NdArray;
velocity: nj.NdArray = numjs.array([0, 0]);
maxVelocity: number;
maxSteeringForce: number;
isDebugging: boolean = false;
private angle: number = mapping(Math.random(), 0, 1, 0, Math.PI * 2);
private targetDistanceThreshold: number = 0;
private predictDistance: number = 0;
private predictRadius: number = 0;
private nextWanderLocation: nj.NdArray = numjs.array([0, 0]);
private futurePosition: nj.NdArray = numjs.array([0, 0]);
private normalPointOnPath: nj.NdArray = numjs.array([0, 0]);
private isWandering: boolean = false;
private isFollowingPath: boolean = false;
protected acceleration: nj.NdArray = numjs.array([0, 0]);
protected mainColor: string = '#ffcf00';
protected subColor: string = '#0f0b19';
constructor(mass: number, location: nj.NdArray, maxVelocity: number, maxSteeringForce: number, mainColor?: string, subColor?: string, isDebugging?: boolean) {
this.mass = mass;
this.size = mass;
this.predictDistance = mass * 6;
this.predictRadius = mass * 2;
this.targetDistanceThreshold = mass * 5;
this.maxVelocity = maxVelocity;
this.maxSteeringForce = maxSteeringForce;
this.location = location;
this.mainColor = mainColor ? mainColor : this.mainColor;
this.subColor = subColor ? subColor : this.subColor;
this.isDebugging = isDebugging || this.isDebugging;
}
applyForce(force: nj.NdArray) {
this.acceleration = this.acceleration.add(force);
}
run(state: ICanvasState): void {
this.step(state);
this.display(state);
this.isWandering = false;
this.isFollowingPath = false;
}
step(state: ICanvasState): void {
this.velocity = limit(this.velocity.add(this.acceleration), this.maxVelocity);
this.location = this.location.add(this.velocity);
if (magnitude(this.velocity) > 0) {
this.angle = Math.atan2(this.velocity.get(1), this.velocity.get(0));
}
this.checkEdges(state.worldWidth, state.worldHeight);
this.acceleration = this.acceleration.multiply(0);
}
display(state: ICanvasState): void {
const x = this.location.get(0);
const y = this.location.get(1);
const [newX, newY] = getCoordinateAfterRotation(x, y, this.angle);
if (state.ctx) {
state.ctx.beginPath();
state.ctx.rotate(this.angle);
state.ctx.moveTo(newX + this.size / 2, newY);
state.ctx.lineTo(newX - this.size / 2, newY - this.size / 2);
state.ctx.lineTo(newX - this.size / 4, newY);
state.ctx.lineTo(newX - this.size / 2, newY + this.size / 2);
state.ctx.lineTo(newX + this.size / 2, newY);
state.ctx.fillStyle = this.mainColor;
state.ctx.lineWidth = 2;
state.ctx.strokeStyle = this.subColor;
state.ctx.fill();
state.ctx.stroke();
state.ctx.lineWidth = 1;
state.ctx.strokeStyle = '#000000';
state.ctx.fillStyle = '#ffffff';
if (this.isDebugging) {
if (this.isWandering) {
const [futureX, futureY] = getCoordinateAfterRotation(this.futurePosition.get(0), this.futurePosition.get(1), this.angle);
const [wanderX, wanderY] = getCoordinateAfterRotation(this.nextWanderLocation.get(0), this.nextWanderLocation.get(1), this.angle);
state.ctx.beginPath();
state.ctx.moveTo(newX + this.size / 2, newY);
state.ctx.lineTo(futureX, futureY);
state.ctx.stroke();
state.ctx.beginPath();
state.ctx.arc(futureX, futureY, this.predictRadius, 0, Math.PI * 2);
state.ctx.stroke();
state.ctx.beginPath();
state.ctx.moveTo(futureX, futureY);
state.ctx.lineTo(wanderX, wanderY);
state.ctx.stroke();
}
if (this.isFollowingPath) {
const [futureX, futureY] = getCoordinateAfterRotation(this.futurePosition.get(0), this.futurePosition.get(1), this.angle);
const [normalX, normalY] = getCoordinateAfterRotation(this.normalPointOnPath.get(0), this.normalPointOnPath.get(1), this.angle);
state.ctx.beginPath();
state.ctx.moveTo(newX + this.size / 2, newY);
state.ctx.lineTo(futureX, futureY);
state.ctx.stroke();
state.ctx.beginPath();
state.ctx.moveTo(futureX, futureY);
state.ctx.lineTo(normalX, normalY);
state.ctx.stroke();
}
}
state.ctx.resetTransform();
}
}
seek(target: nj.NdArray): nj.NdArray {
const desiredVector = target.subtract(this.location);
const distance = magnitude(desiredVector);
let desiredVelocity = normalize(desiredVector).multiply(this.maxVelocity);
if (distance < this.targetDistanceThreshold) {
const velocity = mapping(distance, 0, this.targetDistanceThreshold, 0, this.maxVelocity);
desiredVelocity = normalize(desiredVector).multiply(velocity)
}
const steer = desiredVelocity.subtract(this.velocity);
const steeringForce = limit(steer, this.maxSteeringForce);
return steeringForce;
}
wander(): void {
const futureX = this.location.get(0) + this.predictDistance * Math.cos(this.angle);
const futureY = this.location.get(1) + this.predictDistance * Math.sin(this.angle);
this.futurePosition = numjs.array([futureX, futureY]);
const newSubAngle = mapping(Math.random(), 0, 1, 0, 2 * Math.PI);
const xOffset = this.predictRadius * Math.cos(newSubAngle);
const yOffset = this.predictRadius * Math.sin(newSubAngle);
this.nextWanderLocation = numjs.array([futureX + xOffset, futureY + yOffset]);
const seekForce = this.seek(this.nextWanderLocation);
this.applyForce(seekForce);
this.isWandering = true;
}
follow(flowField: FlowField): void {
const force = flowField.getField(this.location);
const desiredVelocity = normalize(force).multiply(this.maxVelocity);
const steer = desiredVelocity.subtract(this.velocity);
const steeringForce = limit(steer, this.maxSteeringForce);
this.applyForce(steeringForce);
}
private getClosestNormalFromPath(path: Path): nj.NdArray[] {
const predictDistance = this.mass * 2;
const futureX = this.location.get(0) + predictDistance * Math.cos(this.angle);
const futureY = this.location.get(1) + predictDistance * Math.sin(this.angle);
const threshold = Math.min(this.size * 2, 10);
let result: nj.NdArray[] = [numjs.array([Infinity, Infinity])];
let minResult: nj.NdArray[] = [numjs.array([Infinity, Infinity])];
let normalFound: boolean = false;
this.futurePosition = numjs.array([futureX, futureY]);
for (let i = 0; i < path.points.length - 1; i++) {
const start = path.points[i];
const end = path.points[i + 1];
if (magnitude(this.futurePosition.subtract(end)) < threshold) {
continue;
}
let normalPoint = findNormalPoint(start, end, this.futurePosition);
const isNormalInPath = normalPoint.get(0) >= Math.min(start.get(0), end.get(0)) && normalPoint.get(0) <= Math.max(start.get(0), end.get(0));
const currentDistance = magnitude(normalPoint.subtract(this.futurePosition));
const minResultDistance = magnitude(minResult[0].subtract(this.futurePosition));
if (currentDistance <= minResultDistance) {
minResult = [normalPoint, start, end];
}
if (isNormalInPath) {
normalFound = true;
const resultDistance = magnitude(result[0].subtract(this.futurePosition));
if (currentDistance <= resultDistance) {
result = [normalPoint, start, end];
}
}
}
if (!normalFound) {
result = minResult;
}
return result;
}
getClosestNormalFromPathV1(path: Path): nj.NdArray[] {
const predictDistance = this.mass * 2;
const futureX = this.location.get(0) + predictDistance * Math.cos(this.angle);
const futureY = this.location.get(1) + predictDistance * Math.sin(this.angle);
let result: nj.NdArray[] = [numjs.array([Infinity, Infinity])];
this.futurePosition = numjs.array([futureX, futureY]);
for (let i = 0; i < path.points.length - 1; i++) {
const start = path.points[i];
const end = path.points[i + 1];
let normalPoint = findNormalPoint(start, end, this.futurePosition);
const isNormalInPath = normalPoint.get(0) >= Math.min(start.get(0), end.get(0)) && normalPoint.get(0) <= Math.max(start.get(0), end.get(0));
if (!isNormalInPath) {
normalPoint = end;
}
const resultDistance = magnitude(result[0].subtract(this.futurePosition));
const currentDistance = magnitude(normalPoint.subtract(this.futurePosition));
if (currentDistance <= resultDistance) {
result = [normalPoint, start, end];
}
}
return result;
}
followPath(path: Path): void {
this.isFollowingPath = true;
const [normalPoint, start, end] = this.getClosestNormalFromPathV1(path);
// const [normalPoint, start, end] = this.getClosestNormalFromPath(path);
this.normalPointOnPath = normalPoint;
const targetDistanceFromNormal = 25;
const distance = magnitude(this.normalPointOnPath.subtract(this.location));
const target = normalize(end.subtract(start)).multiply(targetDistanceFromNormal).add(normalPoint);
if (distance > path.radius || magnitude(this.velocity) === 0) {
const seekForce = this.seek(target);
this.applyForce(seekForce);
}
}
seperate(others: Vehicle[]): nj.NdArray {
let count: number = 0;
let sum: nj.NdArray = numjs.array([0, 0]);
let result: nj.NdArray = numjs.array([0, 0]);
const separation = 50;
for (let i = 0; i < others.length; i++) {
const otherNode = others[i];
const force = this.location.subtract(otherNode.location);
const distance = magnitude(force);
if (distance > 0 && distance < separation) {
sum = sum.add(normalize(force));
count++;
}
}
if (count > 0) {
sum = sum.divide(count);
const desiredVelocity = sum.multiply(this.maxVelocity);
const steer = desiredVelocity.subtract(this.velocity);
result = limit(steer, this.maxSteeringForce);
}
return result;
}
applyBehaviors(others: Vehicle[], target: nj.NdArray, seekMag: number, seperateMag: number): void {
const seekForce = this.seek(target);
const seperateForce = this.seperate(others);
this.applyForce(seekForce.multiply(seekMag));
this.applyForce(seperateForce.multiply(seperateMag));
}
align(others: Vehicle[]): nj.NdArray {
let count: number = 0;
let sum: nj.NdArray = numjs.array([0, 0]);
let result: nj.NdArray = numjs.array([0, 0]);
const radius = 50;
for (let i = 0; i < others.length; i++) {
const otherNode = others[i];
const force = this.location.subtract(otherNode.location);
const distance = magnitude(force);
if (distance > 0 && distance < radius) {
sum = sum.add(others[i].velocity);
count++;
}
}
if (count > 0) {
sum = normalize(sum.divide(count));
const desiredVelocity = sum.multiply(this.maxVelocity);
const steer = desiredVelocity.subtract(this.velocity);
result = limit(steer, this.maxSteeringForce);
}
return result;
}
cohesion(others: Vehicle[]): nj.NdArray {
let count: number = 0;
let sum: nj.NdArray = numjs.array([0, 0]);
let result: nj.NdArray = numjs.array([0, 0]);
const radius = 50;
for (let i = 0; i < others.length; i++) {
const otherNode = others[i];
const force = this.location.subtract(otherNode.location);
const distance = magnitude(force);
if (distance > 0 && distance < radius) {
sum = sum.add(otherNode.location);
count++;
}
}
if (count > 0) {
sum = sum.divide(count);
result = this.seek(sum);
}
return result;
}
flock(others: Vehicle[], seperateMag: number, alignMag: number, cohesionMag: number): void {
const seperateForce = this.seperate(others);
const alignForce = this.align(others);
const cohesionForce = this.cohesion(others);
this.applyForce(seperateForce.multiply(seperateMag));
this.applyForce(alignForce.multiply(alignMag));
this.applyForce(cohesionForce.multiply(cohesionMag));
}
checkEdges(worldWidth: number, worldHeight: number): void {
const x = this.location.get(0);
const y = this.location.get(1);
let newX: number = x;
let newY: number = y;
if (x > worldWidth) {
newX = 0;
}
if (x < 0) {
newX = worldWidth;
}
if (y > worldHeight) {
newY = 0;
}
if (y < 0) {
newY = worldHeight;
}
this.location = numjs.array([newX, newY]);
}
}
|
'use strict';
Connector.artistSelector = '.mainPanel .artist';
Connector.albumSelector = '.mainPanel .album';
Connector.trackSelector = '.mainPanel .song';
Connector.playButtonSelector = '#mp3_play .musicPlay';
Connector.currentTimeSelector = '#mp3_position';
Connector.durationSelector = '#mp3_duration';
Connector.trackArtSelector = '.mainPanel .artwork > img';
new MutationObserver(Connector.onStateChanged).observe(document, {
childList: true, subtree: true,
attributes: true, characterData: true,
});
|
<gh_stars>1-10
package de.core23.dicewars.controller;
public class SettingsException extends Exception {
private static final long serialVersionUID = 6394702369131537160L;
public SettingsException(String message) {
super(message);
}
}
|
#!/bin/bash
script_dir=$(cd $(dirname ${BASH_SOURCE:-$0}); pwd)
VOC_DIR=$script_dir/../../
# Directory that contains all wav files
# **CHANGE** this to your database path
db_root=~/data/LJSpeech-1.1/wavs/
spk="lj"
dumpdir=dump
# train/dev/eval split
dev_size=10
eval_size=10
# Maximum size of train/dev/eval data (in hours).
# set small value (e.g. 0.2) for testing
limit=1000000
# waveform global gain normalization scale
global_gain_scale=0.55
stage=0
stop_stage=0
# Hyper parameters (.json)
# **CHANGE** here to your own hparams
hparams=conf/mulaw256_wavenet_demo.json
# Batch size at inference time.
inference_batch_size=32
# Leave empty to use latest checkpoint
eval_checkpoint=
# Max number of utts. for evaluation( for debugging)
eval_max_num_utt=1000000
# exp tag
tag="" # tag for managing experiments.
. $VOC_DIR/utils/parse_options.sh || exit 1;
# Set bash to 'debug' mode, it will exit on :
# -e 'error', -u 'undefined variable', -o ... 'error in pipeline', -x 'print commands',
set -e
set -u
set -o pipefail
train_set="train_no_dev"
dev_set="dev"
eval_set="eval"
datasets=($train_set $dev_set $eval_set)
# exp name
if [ -z ${tag} ]; then
expname=${spk}_${train_set}_$(basename ${hparams%.*})
else
expname=${spk}_${train_set}_${tag}
fi
expdir=exp/$expname
feat_typ="logmelspectrogram"
# Output directories
data_root=data/$spk # train/dev/eval splitted data
dump_org_dir=$dumpdir/$spk/$feat_typ/org # extracted features (pair of <wave, feats>)
dump_norm_dir=$dumpdir/$spk/$feat_typ/norm # extracted features (pair of <wave, feats>)
if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then
echo "stage 0: train/dev/eval split"
if [ -z $db_root ]; then
echo "ERROR: DB ROOT must be specified for train/dev/eval splitting."
echo " Use option --db-root \${path_contains_wav_files}"
exit 1
fi
python $VOC_DIR/mksubset.py $db_root $data_root \
--train-dev-test-split --dev-size $dev_size --test-size $eval_size \
--limit=$limit
fi
if [ ${stage} -le 1 ] && [ ${stop_stage} -ge 1 ]; then
echo "stage 1: Feature Generation"
for s in ${datasets[@]};
do
python $VOC_DIR/preprocess.py wavallin $data_root/$s ${dump_org_dir}/$s \
--hparams="global_gain_scale=${global_gain_scale}" --preset=$hparams
done
# Compute mean-var normalization stats
find $dump_org_dir/$train_set -type f -name "*feats.npy" > train_list.txt
python $VOC_DIR/compute-meanvar-stats.py train_list.txt $dump_org_dir/meanvar.joblib
rm -f train_list.txt
# Apply normalization
for s in ${datasets[@]};
do
python $VOC_DIR/preprocess_normalize.py ${dump_org_dir}/$s $dump_norm_dir/$s \
$dump_org_dir/meanvar.joblib
done
cp -f $dump_org_dir/meanvar.joblib ${dump_norm_dir}/meanvar.joblib
fi
if [ ${stage} -le 2 ] && [ ${stop_stage} -ge 2 ]; then
echo "stage 2: WaveNet training"
python $VOC_DIR/train.py --dump-root $dump_norm_dir --preset $hparams \
--checkpoint-dir=$expdir \
--log-event-path=tensorboard/${expname}
fi
if [ ${stage} -le 3 ] && [ ${stop_stage} -ge 3 ]; then
echo "stage 3: Synthesis waveform from WaveNet"
if [ -z $eval_checkpoint ]; then
eval_checkpoint=$expdir/checkpoint_latest.pth
fi
name=$(basename $eval_checkpoint)
name=${name/.pth/}
for s in $dev_set $eval_set;
do
dst_dir=$expdir/generated/$name/$s
python $VOC_DIR/evaluate.py $dump_norm_dir/$s $eval_checkpoint $dst_dir \
--preset $hparams --hparams="batch_size=$inference_batch_size" \
--num-utterances=$eval_max_num_utt
done
fi
|
#!./test/libs/bats/bin/bats
load 'libs/bats-support/load'
load 'libs/bats-assert/load'
load 'helpers'
setup() {
setupNotesEnv
}
teardown() {
teardownNotesEnv
}
export EDITOR=touch
notes="./notes"
@test "Configuration should override QUICKNOTE_FORMAT" {
mkdir -p $HOME/.config/notes
echo "QUICKNOTE_FORMAT=test" > $HOME/.config/notes/config
run $notes new
assert_success
assert_exists "$NOTES_DIRECTORY/test.md"
}
@test "Configuration should override EDITOR" {
mkdir -p $HOME/.config/notes
echo "EDITOR=echo" > $HOME/.config/notes/config
run $notes new test
assert_success
assert_line "$NOTES_DIRECTORY/test.md"
}
@test "Configuration should override file extension" {
mkdir -p $HOME/.config/notes
echo "NOTES_EXT=txt" > $HOME/.config/notes/config
run $notes new test
assert_success
assert_exists "$NOTES_DIRECTORY/test.txt"
}
@test "Configuration should be accepted if NOTES_DIR doesn't exist" {
mkdir -p $HOME/.config/notes
echo "NOTES_DIRECTORY=$NOTES_DIRECTORY/notesdir" > $HOME/.config/notes/config
run $notes new test
assert_success
}
@test "Configuration should be rejected if NOTES_DIR is a existing file" {
mkdir -p $HOME/.config/notes
touch $NOTES_DIRECTORY/testfile
echo "NOTES_DIRECTORY=$NOTES_DIRECTORY/testfile" > $HOME/.config/notes/config
run $notes new test
assert_failure
assert_line "Could not create directory $NOTES_DIRECTORY/testfile, please update your \$NOTES_DIRECTORY"
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.fhwa.c2cri.testprocedures;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import tmddv3verification.utilities.TMDDDatabase;
/**
*
* @author TransCore ITS
*/
public class TMDDSubPubMapping {
private static TMDDSubPubMapping thisMapping;
private static HashMap<Integer, ArrayList<SubPubMatch>> subPubMap = new HashMap();
public static TMDDSubPubMapping getInstance() {
if (thisMapping == null) {
thisMapping = new TMDDSubPubMapping();
}
return thisMapping;
}
private TMDDSubPubMapping() {
TMDDDatabase theDatabase = new TMDDDatabase();
try {
theDatabase.connectToDatabase();
ResultSet subPubRS = theDatabase.queryReturnRS("SELECT * FROM TMDDv303SubPubLookupQuery");
try {
while (subPubRS.next()) {
SubPubMatch thisMatch = new SubPubMatch();
thisMatch.setSubscription(subPubRS.getString("SubDialog"));
thisMatch.setPublication(subPubRS.getString("PubDialog"));
thisMatch.setRelatedMessageRequirement(subPubRS.getString("ValueReqID"));
Integer needNumber = subPubRS.getInt("NeedNumber");
if (subPubMap.containsKey(needNumber)){
subPubMap.get(needNumber).add(thisMatch);
} else {
ArrayList<SubPubMatch> newList = new ArrayList();
newList.add(thisMatch);
subPubMap.put(needNumber, newList);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
subPubRS.close();
System.out.println("TMDDSubPubMapping: Initialized!!");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
theDatabase.disconnectFromDatabase();
}
}
public String getPublicationDialog(String subDialog, int needNumber) throws Exception{
if (subPubMap.containsKey(needNumber)){
for (SubPubMatch thisMatch : subPubMap.get(needNumber)){
if (thisMatch.getSubscription().equals(subDialog)){
return thisMatch.getPublication();
}
}
}
throw new Exception("No Publication Match Found for "+subDialog);
}
public String getSubscriptionDialog(String pubDialog, int needNumber) throws Exception {
System.out.println("The needNumber is "+needNumber);
if (subPubMap.containsKey(needNumber)){
for (SubPubMatch thisMatch : subPubMap.get(needNumber)){
if (thisMatch.getPublication().equals(pubDialog)){
return thisMatch.getSubscription();
}
}
}
throw new Exception("No Subscription Match Found for "+pubDialog);
}
public String getRelatedMessageRequirement(String pubDialog, int needNumber) throws Exception {
if (subPubMap.containsKey(needNumber)){
for (SubPubMatch thisMatch : subPubMap.get(needNumber)){
if (thisMatch.getPublication().equals(pubDialog)){
return thisMatch.getRelatedMessageRequirement();
}
}
}
throw new Exception("No Publication Match Found for "+pubDialog);
}
class SubPubMatch {
private String subscription;
private String relatedMessageRequirement;
private String publication;
public String getSubscription() {
return subscription;
}
public void setSubscription(String subscription) {
this.subscription = subscription;
}
public String getPublication() {
return publication;
}
public void setPublication(String publication) {
this.publication = publication;
}
public String getRelatedMessageRequirement() {
return relatedMessageRequirement;
}
public void setRelatedMessageRequirement(String relatedMessageRequirement) {
this.relatedMessageRequirement = relatedMessageRequirement;
}
}
}
|
<filename>src/idtype/SelectionUtils.ts
/* *****************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
**************************************************************************** */
/**
* Created by <NAME> on 04.08.2014.
*/
import {ParseRangeUtils, Range, Range1D, RangeLike} from '../range';
export enum SelectOperation {
SET, ADD, REMOVE
}
export class SelectionUtils {
public static defaultSelectionType = 'selected';
public static hoverSelectionType = 'hovered';
/**
* converts the given mouse event to a select operation
* @param event the mouse event to examine
*/
static toSelectOperation(event: MouseEvent): SelectOperation;
/**
* converts the given key modifiers to select operation
* @param ctryKey
* @param altKey
* @param shiftKey
* @param metaKey
*/
static toSelectOperation(ctryKey: boolean, altKey: boolean, shiftKey: boolean, metaKey: boolean): SelectOperation;
static toSelectOperation(event: any) {
let ctryKeyDown, shiftDown, altDown, metaDown;
if (typeof event === 'boolean') {
ctryKeyDown = event;
altDown = arguments[1] || false;
shiftDown = arguments[2] || false;
metaDown = arguments[3] || false;
} else {
ctryKeyDown = event.ctrlKey || false;
altDown = event.altKey || false;
shiftDown = event.shiftKey || false;
metaDown = event.metaKey || false;
}
if (ctryKeyDown || shiftDown) {
return SelectOperation.ADD;
} else if (altDown || metaDown) {
return SelectOperation.REMOVE;
}
return SelectOperation.SET;
}
static asSelectOperation(v: any) {
if (!v) {
return SelectOperation.SET;
}
if (typeof v === 'string') {
switch (v.toLowerCase()) {
case 'add' :
return SelectOperation.ADD;
case 'remove' :
return SelectOperation.REMOVE;
default :
return SelectOperation.SET;
}
}
return +v;
}
static fillWithNone(r: Range, ndim: number) {
while (r.ndim < ndim) {
r.dims[r.ndim] = Range1D.none();
}
return r;
}
static integrateSelection(current: Range, additional: RangeLike, operation: SelectOperation = SelectOperation.SET) {
const next = ParseRangeUtils.parseRangeLike(additional);
switch (operation) {
case SelectOperation.ADD:
return current.union(next);
case SelectOperation.REMOVE:
return current.without(next);
default:
return next;
}
}
}
|
def sort_strings(array):
# Index of the string with the lowest alphabetical order
min_index = 0
for i in range(1, len(array)):
if array[i] < array[min_index]:
min_index = i
# Swap the elements
array[i], array[min_index] = array[min_index], array[i]
sort_strings(["dog", "cat", "apple", "banana"])
# Output: ['apple', 'banana', 'cat', 'dog']
|
<gh_stars>10-100
//
// Created by ooooo on 2020/3/19.
//
#ifndef CPP_030__SOLUTION1_H_
#define CPP_030__SOLUTION1_H_
#include <iostream>
using namespace std;
class MinStack {
private:
struct Node {
Node *next;
int val;
Node(Node *next, int val) : next(next), val(val) {}
Node(int val) : val(val), next(nullptr) {}
};
Node *dummyHead;
int size;
public:
/** initialize your data structure here. */
MinStack() {
dummyHead = new Node(0);
size = 0;
}
void push(int x) {
dummyHead->next = new Node(dummyHead->next, x);
size += 1;
}
void pop() {
if (size == 0) return;
dummyHead->next = dummyHead->next->next;
size--;
}
int top() {
if (size == 0) return -1;
return dummyHead->next->val;
}
int min() {
Node *cur = dummyHead->next;
int min_value = INT_MAX;
while (cur) {
min_value = std::min(min_value, cur->val);
cur = cur->next;
}
return min_value;
}
};
#endif //CPP_030__SOLUTION1_H_
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Constants
F1 = 1.0 # High-pass filter corner
F2 = 6.0 # Low-pass filter corner
# Read seismic data from file
seismic_data = pd.read_csv("ShakeNetwork2020.csv")
# Apply high-pass filter
filtered_data_high_pass = np.fft.fft(seismic_data["Seismic Data"])
frequencies = np.fft.fftfreq(len(filtered_data_high_pass))
filtered_data_high_pass[frequencies < F1] = 0
filtered_data_high_pass = np.fft.ifft(filtered_data_high_pass)
# Apply low-pass filter
filtered_data_low_pass = np.fft.fft(seismic_data["Seismic Data"])
filtered_data_low_pass[frequencies > F2] = 0
filtered_data_low_pass = np.fft.ifft(filtered_data_low_pass)
# Display the filtered seismic data
plt.figure(figsize=(12, 6))
plt.plot(seismic_data["Seismic Data"], label="Original Data", color='b')
plt.plot(filtered_data_high_pass, label="High-pass Filtered Data", color='g')
plt.plot(filtered_data_low_pass, label="Low-pass Filtered Data", color='r')
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.title('Seismic Data with High-pass and Low-pass Filters')
plt.legend()
plt.show()
|
def fibonacci(n):
a = 0
b = 1
if n < 0:
print("Incorrect input")
elif n == 0:
return a
elif n == 1:
return b
else:
for i in range(2, n):
c = a + b
a = b
b = c
return b
result = fibonacci(5)
print(result)
|
<reponame>stardot/ncc
/*
* options.h -- compiler configuration options set at compile time
* Copyright (C) Acorn Computers Ltd. 1988
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _options_LOADED
#define _options_LOADED
/*
* The following conditional settings allow the produced compiler (TARGET)
* to depend on the HOST (COMPILING_ON) environment.
* Note that we choose to treat this independently of the target-machine /
* host-machine issue.
*/
#define CPLUSPLUS 1
#define USE_PP
#define NO_LISTING_OUTPUT 1
#define NO_CONFIG 1
#define NO_OBJECT_OUTPUT 1
#define NO_DEBUGGER 1
#define NO_ASSEMBLER_OUTPUT 1
#define TARGET_VTAB_ELTSIZE 4
/* for indirect VTABLEs optimised for single inheritance */
#include "toolver.h"
#define NON_RELEASE_VSN TOOLVER_ARMCPP
/* Expire this version at 00:00:01 on Saturday 01 Oct 94 */
/*#define UNIX_TIME_LIMIT 780969601 */
#define TARGET_ENDIANNESS_CONFIGURABLE 1
/* #define TARGET_DEFAULT_BIGENDIAN 0 */ /* 1 => bigendian default */
/* 0 => littleendian default */
/* unset => defaults to host */
#define DISABLE_ERRORS 1 /* -- to enable -Exyz... error suppression */
#define EXTENSION_SYSV 1 /* -- to allow #ident ... */
# define TARGET_SYSTEM "C Interpreter"
# define HOST_WANTS_NO_BANNER 1
# ifndef DRIVER_OPTIONS
/* -D__arm done by TARGET_PREDEFINES */
# define DRIVER_OPTIONS {NULL}
# endif
# define C_INC_VAR "ARMINC"
# define C_LIB_VAR "ARMLIB"
#ifndef RELEASE_VSN
# define ENABLE_ALL 1 /* -- to enable all debugging options */
#endif
/* mac-specific options - find a better home for these sometime! */
#ifdef macintosh
/* The origin of time is 0th Jan 1904... */
# ifdef UNIX_TIME_LIMIT
# define TIME_LIMIT (UNIX_TIME_LIMIT+(66*365+16)*24*3600)
# endif
# define NO_STATIC_BANNER 1
pascal void SpinCursor(short increment); /* copied from CursorCtl.h */
# define ExecuteOnSourceBufferFill() SpinCursor(1)
#ifdef TARGET_IS_NEWTON
# define HOST_OBJECT_INCLUDES_SOURCE_EXTN 1 /* .c -> .c.o */
# define EXTENSION_COUNTED_STRINGS 1 /* to enable Pascal-style strings */
# define EXTENSION_UNSIGNED_STRINGS 1 /* and they are unsigned */
# define ALLOW_KEYWORDS_IN_HASHIF 1 /* to allow keywords in #if expns */
# define ALLOW_WHITESPACE_IN_FILENAMES 1 /* to allow as it says... */
# define ONLY_WARN_ON_NONPRINTING_CHAR 1 /* to do as it says... */
# define HOST_DOES_NOT_FORCE_TRAILING_NL 1
# define HOST_WANTS_NO_BANNER 1 /* no routine banner output */
# define DISABLE_ERRORS 1
# define TARGET_WANTS_LINKER_TO_RESOLVE_FUNCTION_REFERENCES 1
# define HOST_CANNOT_INVOKE_ASSEMBLER 1
# define HOST_CANNOT_INVOKE_LINKER 1
# define PUT_FILE_NAME_IN_AREA_NAME 1
# define CHAR_NL '\n'
# define CHAR_CR '\r'
# define CFRONT_MODE_WARN_LACKS_STORAGE_TYPE 0
# define HOST_DOESNT_WANT_FP_OFFSET_TABLES 1
#endif
#else /* NOT macintosh */
# ifdef UNIX_TIME_LIMIT
# define TIME_LIMIT UNIX_TIME_LIMIT
# endif
#endif
#ifdef TIME_LIMIT
# define VENDOR_NAME "Advanced RISC Machines Limited"
#endif
#ifdef CPLUSPLUS
# ifndef CFRONT_MODE_WARN_LACKS_STORAGE_TYPE
# define CFRONT_MODE_WARN_LACKS_STORAGE_TYPE 1
# endif
#endif
#define MSG_TOOL_NAME "armcc" /* used to load correct NLS message file */
#endif
/* end of cpparm/options.h */
|
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
/* This file has been modified by Open Source Strategies, Inc. */
package org.ofbiz.minilang.method;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.w3c.dom.*;
import org.ofbiz.minilang.*;
/**
* A single operation, does the specified operation on the given field
*/
public abstract class MethodOperation {
public interface Factory<M extends MethodOperation> {
M createMethodOperation(Element element, SimpleMethod simpleMethod);
String getName();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DeprecatedOperation {
String value();
}
protected SimpleMethod simpleMethod;
public MethodOperation(Element element, SimpleMethod simpleMethod) {
this.simpleMethod = simpleMethod;
}
public SimpleMethod getSimpleMethod() {
return this.simpleMethod;
}
/** Execute the operation; if false is returned then no further operations will be executed */
public abstract boolean exec(MethodContext methodContext);
/** Create a raw string representation of the operation, would be similar to original XML */
public abstract String rawString();
/** Create an expanded string representation of the operation, is for the current context */
public abstract String expandedString(MethodContext methodContext);
}
|
ACCOUNT_NUMBER=<YOUR_ACCOUNT_NUMBER>
REGION=<YOUR_ACCOUNT_REGION>
SOURCE_S3_BUCKET="eks-stepfunction-dev-source-bucket"
TARGET_S3_BUCKET="eks-stepfunction-dev-target-bucket"
ECR_REPO_NAME="eks-stepfunction-repo"
aws ecr batch-delete-image --repository-name $ECR_REPO_NAME --image-ids imageTag=latest
aws ecr batch-delete-image --repository-name $ECR_REPO_NAME --image-ids imageTag=untagged
aws s3 rm s3://$SOURCE_S3_BUCKET-$ACCOUNT_NUMBER --recursive
aws s3 rm s3://$TARGET_S3_BUCKET-$ACCOUNT_NUMBER --recursive
cd templates
terraform destroy --auto-approve
cd ..
cd samples
rm Product*.txt
cd ..
$SHELL
|
/**
* Copyright (c) 2020-present, <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.
*/
import { TEST_ID } from '../../src/const';
import { EDITOR_LANGUAGE } from '../../src/stores/EditorConfig';
import { getConfigUrls } from './E2ETestUtil';
import { editor as MonacoEditorAPI } from 'monaco-editor';
import { Clazz, guaranteeType } from '@finos/legend-studio-shared';
import { EndToEndTester } from './EndToEndTester';
import { ElementHelperExtension } from './ElementHelperExtension';
export class ElementEditorTester extends EndToEndTester {
// TODO make this an array
helperExtension?: ElementHelperExtension;
public static create(
configFile = 'element-editor.json',
): ElementEditorTester {
const elementEditorTest = new ElementEditorTester();
cy.fixture(configFile).then((demoJSON) => {
elementEditorTest._projectName = demoJSON.PROJECT_NAME;
elementEditorTest._projectId = demoJSON.PROJECT_ID;
elementEditorTest._workspace = demoJSON.WORKSPACE;
getConfigUrls().then((response) => {
elementEditorTest._sdlcServer = response[0];
elementEditorTest._engineServer = response[1];
cy.server();
elementEditorTest.loadRoutes();
});
});
return elementEditorTest;
}
withHelperExtension(
helperExtension: ElementHelperExtension,
): ElementEditorTester {
this.helperExtension = helperExtension;
return this;
}
getHelperExtension<T extends ElementHelperExtension>(clazz: Clazz<T>): T {
return guaranteeType(
this.helperExtension,
clazz,
`No helper extension found`,
);
}
buildGraphWithText = (
graphText: string,
editorLanguage = EDITOR_LANGUAGE.PURE,
): void => {
let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[];
cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT)
.get(`[title="${this._domTitles.TOGGLE_TEXT_MODE}"]`)
.click()
.get(`[data-mode-id="${editorLanguage}"]`)
.window()
.then((win) => {
editorModels = (win as any).monaco.editor.getModels();
})
.then(() => {
expect(editorModels.length).to.equal(1);
editorModels[0].setValue(graphText);
})
.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT)
.get(`[title="${this._domTitles.TOGGLE_TEXT_MODE}"]`)
.click();
cy.contains('Open or Search for an Element');
};
getMonacoText = (idx?: number): Cypress.Chainable<string> => {
let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[];
return cy
.window()
.then((win) => {
editorModels = (win as any).monaco.editor.getModels();
})
.then(() => {
if (!idx) {
expect(editorModels.length).to.equal(1);
const model = editorModels[0];
return model.getValue();
}
return editorModels[idx].getValue();
});
};
addToGraphText = (appendText: string): void => {
let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[];
cy.window()
.then((win) => {
editorModels = (win as any).monaco.editor.getModels();
})
.then(() => {
expect(editorModels.length).to.equal(1);
const model = editorModels[0];
editorModels[0].setValue(model.getValue() + appendText);
});
};
setTextToGraphText = (text: string, child: number = 0): void => {
let editorModels: MonacoEditorAPI.IStandaloneCodeEditor[];
cy.window()
.then((win) => {
editorModels = (win as any).monaco.editor.getModels();
})
.then(() => {
editorModels[child].setValue(text);
});
};
setDevTools = (): void => {
cy.get(`[title="Settings..."]`).click();
cy.contains('Show Developer Tool').click();
cy.contains('Payload compression').parent().children().eq(1).click();
cy.get('[title="Toggle auxiliary panel (Ctrl + `)"]').click();
};
compile = (): void => {
cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT)
.get('[title="Compile (F9)"]')
.click();
cy.wait('@compile').its('status').should('eq', 200);
cy.contains('Compiled sucessfully');
};
createReview = (title: string): void => {
cy.get('[placeholder="Title"]').focus().clear().type(title);
cy.get('[title="Create review"]').click();
cy.wait('@postReview').its('status').should('eq', 200);
};
toggleOnHackerMode = (): void => {
cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT)
.get('[title="Toggle text mode (F8)"]')
.click();
cy.wait('@postTransformJsonToGrammar');
};
toggleOffHackerMode = (): void => {
cy.getByTestID(TEST_ID.EDITOR__STATUS_BAR__RIGHT)
.get('[title="Toggle text mode (F8)"]')
.click();
cy.wait('@postTransformGrammarToJson');
};
setUpRoutes = (): void => {
cy.route({
method: 'GET',
url: `${this.sdlcServer}/projects/${this.projectId}/workspaces`,
}).as('getWorkspaces');
cy.route({
method: 'GET',
url: `${this.sdlcServer}/projects/${this.projectId}/conflictResolution`,
}).as('getConflictResolution');
cy.route({
method: 'POST',
url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}`,
}).as('postWorkspace');
//same as above but with different alias
cy.route({
method: 'GET',
url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/entities`,
}).as('getEntities');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/schemaGeneration/avro`,
}).as('avroGeneration');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/schemaGeneration/protobuf`,
}).as('protobufGeneration');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/compilation/compile`,
}).as('compile');
cy.route({
method: 'POST',
url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/entityChanges`,
}).as('syncChanges');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/execution/execute`,
}).as('postExecute');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/execution/generatePlan`,
}).as('postGeneratePlan');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/grammar/transformGrammarToJson`,
}).as('transformGrammarToJson');
cy.route({
method: 'POST',
url: `${this.sdlcServer}/projects/${this.projectId}/reviews`,
}).as('postReview');
cy.route({
method: 'POST',
url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/entityChanges`,
}).as('postEntityChanges');
cy.route({
method: 'GET',
url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}/inConflictResolutionMode`,
}).as('getInConflictResolutionMode');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/grammar/transformJsonToGrammar`,
}).as('postTransformJsonToGrammar');
cy.route({
method: 'POST',
url: `${this.engineServer}/api/pure/v1/grammar/transformGrammarToJson`,
}).as('postTransformGrammarToJson');
cy.route({
method: 'GET',
url: `${this.sdlcServer}/projects/${this.projectId}`,
}).as('getProjectDetails');
cy.route({
method: 'GET',
url: `${this.sdlcServer}/projects/${this.projectId}/workspaces/${this.workspace}`,
}).as('getWorkspace');
};
}
|
<filename>data/init.sql
DROP TABLE IF EXISTS `cdr`;
CREATE TABLE `cdr` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`calldate` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
`clid` VARCHAR(80) NOT NULL DEFAULT '',
`src` VARCHAR(80) NOT NULL DEFAULT '',
`dst` VARCHAR(80) NOT NULL DEFAULT '',
`dcontext` VARCHAR(80) NOT NULL DEFAULT '',
`channel` VARCHAR(80) NOT NULL DEFAULT '',
`dstchannel` VARCHAR(50) NOT NULL DEFAULT '',
`lastapp` VARCHAR(80) NOT NULL DEFAULT '',
`lastdata` VARCHAR(200) NOT NULL DEFAULT '',
`duration` INTEGER(11) NOT NULL DEFAULT '0',
`billsec` INTEGER(11) NOT NULL DEFAULT '0',
`disposition` VARCHAR(45) NOT NULL DEFAULT '',
`amaflags` VARCHAR(50) NULL DEFAULT NULL,
`accountcode` VARCHAR(20) NULL DEFAULT NULL,
`uniqueid` VARCHAR(32) NOT NULL DEFAULT '',
`userfield` varchar(255) NOT NULL DEFAULT '',
`peeraccount` VARCHAR(20) NOT NULL DEFAULT '',
`linkedid` VARCHAR(32) NOT NULL DEFAULT '',
`sequence` INT(11) NOT NULL DEFAULT '0',
`record` VARCHAR(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
INDEX `calldate` (`calldate`),
INDEX `dst` (`dst`),
INDEX `src` (`src`),
INDEX `dcontext` (`dcontext`),
INDEX `clid` (`clid`)
)
COLLATE='utf8_bin'
ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
#/bin/bash
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
source $(dirname "$0")/test_base_functions.sh
# Set up Java to be used by the openliberty test
echo_setup
cd ${TEST_HOME}
cd dev
set -e
#Build all projects and create the open-liberty image
./gradlew -q cnf:initialize
./gradlew -q releaseNeeded
set +e
echo "Build projects and create images done"
#Following are not enabled tests, may need to enable later
#com.ibm.ws.microprofile.reactive.streams.operators_fat_tck
#com.ibm.ws.concurrent.mp_fat_tck
#com.ibm.ws.microprofile.config_git_fat_tck
#com.ibm.ws.security.mp.jwt_fat_tck
#com.ibm.ws.microprofile.faulttolerance_git_fat_tck
#Exclude Metrics TCK
#Start MicroProfile Metrics TCK
./gradlew -q com.ibm.ws.microprofile.metrics_fat_tck:clean
./gradlew -q com.ibm.ws.microprofile.metrics_fat_tck:buildandrun
#Start MicroProfile Config TCK
./gradlew -q com.ibm.ws.microprofile.config.1.4_fat_tck:clean
./gradlew -q com.ibm.ws.microprofile.config.1.4_fat_tck:buildandrun
#Start MicroProfile FaultTolerance TCK
./gradlew -q com.ibm.ws.microprofile.faulttolerance_fat_tck:clean
./gradlew -q com.ibm.ws.microprofile.faulttolerance_fat_tck:buildandrun
#Start MicroProfile Rest Client TCK
./gradlew -q com.ibm.ws.microprofile.rest.client_fat_tck:clean
./gradlew -q com.ibm.ws.microprofile.rest.client_fat_tck:buildandrun
#Start MicroProfile OpenAPI TCK
./gradlew -q com.ibm.ws.microprofile.openapi_fat_tck:clean
./gradlew -q com.ibm.ws.microprofile.openapi_fat_tck:buildandrun
test_exit_code=$?
find ./ -type d -name 'surefire-reports' -exec cp -r "{}" /testResults \;
exit $test_exit_code
|
<reponame>penguincoder/uncomplicated_mutex<filename>uncomplicated_mutex.gemspec
Gem::Specification.new do |s|
s.name = 'uncomplicated_mutex'
s.version = '1.2.2'
s.date = '2017-04-06'
s.summary = 'Redis. Lua. Mutex.'
s.description = 'A mutex that uses Redis that is also not complicated.'
s.authors = [ '<NAME>' ]
s.email = '<EMAIL>'
s.files = [ 'lib/uncomplicated_mutex.rb' ]
s.homepage = 'https://github.com/penguincoder/uncomplicated_mutex'
s.license = 'MIT'
s.add_runtime_dependency 'redis', '~> 3.0'
s.add_development_dependency 'minitest', '~> 5.0'
end
|
import requests
import re
def crawl(url):
# make request to target url
response = requests.get(url)
# get the html from the response
html = response.text
# extract the links from the html
links = re.findall(r'<a\shref="(.*?)"', html)
# return the extracted links
return links
# crawl the website
crawled_links = crawl('https://www.example.org')
print(crawled_links)
|
class Server:
@staticmethod
def web_server(context):
# Simulate the setup of a web server using the provided context
print(f"Setting up web server with context: {context}")
@staticmethod
def gunicorn(context):
# Simulate the configuration of Gunicorn using the provided context
print(f"Configuring Gunicorn with context: {context}")
@staticmethod
def supervisor(context):
# Simulate the setup of Supervisor using the provided context
print(f"Setting up Supervisor with context: {context}")
@staticmethod
def fix_permissions(context):
# Simulate fixing the permissions of the server files based on the provided context
print(f"Fixing permissions with context: {context}")
@staticmethod
def letsencrypt(context):
# Simulate obtaining and setting up Let's Encrypt SSL certificates for the server
print(f"Obtaining and setting up Let's Encrypt SSL certificates with context: {context}")
# Example usage
server = Server()
server.web_server("example_context")
server.gunicorn("example_context")
server.supervisor("example_context")
server.fix_permissions("example_context")
server.letsencrypt("example_context")
|
<filename>cypress/excluded/checkout_credit_card.spec.js<gh_stars>0
import { second } from '../fixtures/example.json';
describe('Checkout Credit Card Payments', () => {
beforeEach(() => {
// cy.useGateway(second);
cy.clientLogin();
});
it('should be able to complete payment using checkout credit card', () => {
cy.visit('/client/invoices');
cy.get('#unpaid-checkbox').click();
cy.get('[data-cy=pay-now')
.first()
.click();
cy.location('pathname').should('eq', '/client/invoices/payment');
cy.get('[data-cy=payment-methods-dropdown').click();
cy.get('[data-cy=payment-method')
.first()
.click();
cy.wait(8000);
cy.get('.cko-pay-now.show')
.first()
.click();
cy.wait(3000);
cy.getWithinIframe('[data-checkout="card-number"]').type(
'4242424242424242'
);
cy.getWithinIframe('[data-checkout="expiry-month"]').type('12');
cy.getWithinIframe('[data-checkout="expiry-year"]').type('30');
cy.getWithinIframe('[data-checkout="cvv"]').type('100');
cy.getWithinIframe('.form-submit')
.first()
.click();
cy.wait(5000);
cy.url().should('contain', '/client/payments');
});
});
|
<reponame>wetherbeei/gopar
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
)
var verbose = flag.Bool("verbose", false, "Print verbose compiler output")
var leaveSource = flag.Bool("source", false, "Don't delete the transformed source")
func main() {
flag.Parse()
compilecmd := flag.Arg(0) // run|build|install
compilepkg := flag.Arg(1)
if compilepkg == "" {
panic(fmt.Errorf("Empty compile package"))
}
fmt.Println("GoPar Compiler")
dir, err := ioutil.TempDir(os.TempDir(), "gopar_")
if err != nil {
panic(err)
}
if *verbose {
fmt.Println(dir)
}
if !*leaveSource {
defer os.RemoveAll(dir)
}
project := NewProject(compilepkg)
var importGraph func(string) ([]string, error)
importGraph = func(pkgPath string) (result []string, err error) {
if exists := project.get(pkgPath); exists != nil {
return
}
err = project.load(pkgPath)
if err != nil {
return
}
if *verbose {
fmt.Println(pkgPath)
}
var packageImports []string
pkg := project.get(pkgPath)
if pkg == nil {
return
}
if *verbose {
fmt.Println("->", pkg.Imports())
}
for _, i := range pkg.Imports() {
packageImports, err = importGraph(i)
if err != nil {
return
}
result = append(result, packageImports...)
}
result = append(result, pkgPath)
return
}
// Generate an import dependency graph of all used packages
var importOrder []string
importOrder, err = importGraph(compilepkg)
if err != nil {
panic(err)
}
fmt.Println(importOrder)
mainPkg := project.get(compilepkg)
if mainPkg.name != "main" {
panic(fmt.Errorf("%s is not a main package", compilepkg))
}
AddAnalysisPasses := func(compiler *Compiler) {
compiler.AddPass(NewDefinedTypesPass())
compiler.AddPass(NewBasicBlockPass())
//compiler.AddPass(NewInvalidConstructPass())
compiler.AddPass(NewCallGraphPass())
// analysis starts
compiler.AddPass(NewAccessPass())
compiler.AddPass(NewAccessPassPropogate())
compiler.AddPass(NewAccessPassFuncPropogate())
compiler.AddPass(NewDependencyPass())
}
AddParallelizePasses := func(compiler *Compiler) {
compiler.AddPass(NewParallelizePass())
// modification starts
compiler.AddPass(NewInsertBlocksPass())
compiler.AddPass(NewWriteKernelsPass())
}
// analyze all of the used packages
var analyzed map[string]bool = make(map[string]bool)
compiler := NewCompiler(project)
AddAnalysisPasses(compiler)
for _, pkgPath := range importOrder {
if analyzed[pkgPath] {
continue
}
//showGraph(project, pkgPath)
pkg := project.get(pkgPath)
err = compiler.Run(pkg)
if err != nil {
panic(err)
}
analyzed[pkgPath] = true
}
// modify the main package
AddParallelizePasses(compiler)
if err = compiler.Run(mainPkg); err != nil {
panic(err)
}
if err = project.write(dir, mainPkg); err != nil {
panic(err)
}
goparPath, _ := exec.LookPath(os.Args[0])
goparRoot, _ := filepath.Abs(path.Clean(path.Dir(goparPath) + "/../"))
cmd := exec.Command("go", compilecmd, compilepkg)
env := os.Environ()
for i, _ := range env {
if strings.HasPrefix(env[i], "GOPATH=") {
env[i] = os.ExpandEnv(fmt.Sprintf("GOPATH=%s:%s:${GOPATH}", dir, goparRoot))
if *verbose {
fmt.Println(env[i])
}
}
}
cmd.Env = env
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
}
|
package detector
import "talisman/git_repo"
type Details struct {
Category string `json:"type"`
Message string `json:"message"`
Commits []string `json:"commits"`
}
type ResultsDetails struct {
Filename git_repo.FilePath `json:"filename"`
FailureList []Details `json:"failure_list"`
WarningList []Details `json:"warning_list"`
}
type FailureTypes struct {
Filecontent int `json:"filecontent"`
Filesize int `json:"filesize"`
Filename int `json:"filename"`
}
type ResultsSummary struct {
Types FailureTypes `json:"types"`
}
type JsonDetectionResults struct {
Summary ResultsSummary `json:"summary"`
Results []ResultsDetails `json:"results"`
}
func (result JsonDetectionResults) getResultObjectForFileName(filename git_repo.FilePath) ResultsDetails {
for _, resultDetails := range result.Results {
if resultDetails.Filename == filename {
return resultDetails
}
}
return ResultsDetails{"", make([]Details, 0), make([]Details, 0)}
}
func GetJsonSchema(r *DetectionResults) JsonDetectionResults {
jsonResults := JsonDetectionResults{}
failures := r.Failures
for path, data := range failures {
resultDetails := ResultsDetails{}
resultDetails.Filename = path
for message, commits := range data.FailuresInCommits {
failureDetails := Details{}
failureDetails.Message = message
failureDetails.Commits = commits
resultDetails.FailureList = append(resultDetails.FailureList, failureDetails)
}
jsonResults.Results = append(jsonResults.Results, resultDetails)
}
warnings := r.warnings
for path, data := range warnings {
resultDetails := jsonResults.getResultObjectForFileName(path)
resultDetails.Filename = path
for message, commits := range data.FailuresInCommits {
failureDetails := Details{}
failureDetails.Message = message
failureDetails.Commits = commits
resultDetails.WarningList = append(resultDetails.WarningList, failureDetails)
}
}
return jsonResults
}
|
def binary_search_recursive(array, target, start, end):
if start > end:
return -1
mid = (start + end) // 2
mid_element = array[mid]
if mid_element == target:
return mid
elif target < mid_element:
return binary_search_recursive(array, target, start, mid - 1)
else:
return binary_search_recursive(array, target, mid + 1, end)
|
package io.opensphere.hud.util;
import io.opensphere.core.hud.framework.Component;
import io.opensphere.core.hud.framework.Frame;
import io.opensphere.core.hud.framework.layout.GridLayout;
import io.opensphere.core.hud.framework.layout.GridLayoutConstraints;
import io.opensphere.core.model.ScreenBoundingBox;
import io.opensphere.core.model.ScreenPosition;
import io.opensphere.core.viewer.impl.MapContext;
import io.opensphere.core.viewer.impl.ScreenViewer;
import io.opensphere.core.viewer.impl.SimpleMapContext;
import io.opensphere.core.viewer.impl.Viewer3D;
/** A frame which uses a 3d projection. */
public class Frame3D extends Frame<GridLayoutConstraints, GridLayout>
{
/**
* Child component which will either be renderable or contain the renderable
* components.
*/
private Component myChild;
/** The viewers for the sub-frame. */
private MapContext<Viewer3D> myMapContext;
/**
* Construct me.
*
* @param parent parent component. components.
*/
public Frame3D(Component parent)
{
super(parent);
}
@Override
public MapContext<Viewer3D> createMapContext()
{
ScreenBoundingBox frameBox = getAbsoluteLocation();
myMapContext = new SimpleMapContext<>(new ScreenViewer(), new Viewer3D(new Viewer3D.Builder(), false));
myMapContext.reshape((int)frameBox.getWidth(), (int)frameBox.getHeight());
myMapContext.getStandardViewer().setViewOffset(frameBox.getUpperLeft());
return myMapContext;
}
/**
* Get the child.
*
* @return the child
*/
public Component getChild()
{
return myChild;
}
/**
* Get the mapContext.
*
* @return the mapContext
*/
public MapContext<Viewer3D> getMapContext()
{
return myMapContext;
}
@Override
public void handleWindowMoved()
{
ScreenBoundingBox frameBox = getAbsoluteLocation();
myMapContext.getStandardViewer().setViewOffset(frameBox.getUpperLeft());
}
@Override
public void init()
{
initBorder();
// set the layout
setLayout(new GridLayout(1, 1, this));
GridLayoutConstraints constr = new GridLayoutConstraints(
new ScreenBoundingBox(new ScreenPosition(0, 0), new ScreenPosition(0, 0)));
add(myChild, constr);
getLayout().complete();
// setup the mapmanager
setupRenderToTexture();
}
/**
* Set the child.
*
* @param child the child to set
*/
public void setChild(Component child)
{
myChild = child;
}
}
|
import time
import curses
def play_game(time_limit, tolerance):
stdscr = curses.initscr()
curses.noecho()
stdscr.clear()
stdscr.addstr(0, 0, "Press spacebar when the timer reaches zero.")
stdscr.refresh()
for t in range(time_limit, -1, -1):
stdscr.addstr(1, 0, "Time left: {} seconds".format(t))
stdscr.refresh()
time.sleep(1)
stdscr.addstr(2, 0, "Press spacebar now!")
stdscr.refresh()
start_time = time.time()
while True:
key = stdscr.getch()
if key == ord(' '):
break
elapsed_time = time.time() - start_time
curses.endwin()
if abs(elapsed_time - time_limit) <= tolerance:
return True
else:
return False
if __name__ == "__main__":
time_limit = 5
tolerance = 0.5
result = play_game(time_limit, tolerance)
if result:
print("Congratulations! You won the game.")
else:
print("Sorry, you lost the game.")
|
# File: F (Python 2.4)
import random
import math
from panda3d.core import CullBinManager
from pandac.PandaModules import NodePath, CardMaker, Point3, LineSegs, Vec3, Vec4, Vec2, GraphicsStateGuardian
from direct.interval.IntervalGlobal import Sequence, Parallel, Wait, Func
from direct.interval.MetaInterval import Parallel
from direct.interval.LerpInterval import LerpPosInterval
from direct.interval.ProjectileInterval import ProjectileInterval
from direct.showbase import DirectObject
from direct.actor.Actor import Actor
from direct.task import Task
from otp.otpgui import OTPDialog
from direct.gui.DirectGui import DirectWaitBar, DGG
from direct.gui.DirectGui import DirectButton, DirectFrame
from direct.interval.IntervalGlobal import *
from pirates.uberdog.UberDogGlobals import InventoryType
from pirates.audio import SoundGlobals
from pirates.audio.SoundGlobals import loadSfx
from pirates.inventory import ItemGlobals
from pirates.reputation import ReputationGlobals
from pirates.piratesbase import PLocalizer
from pirates.piratesbase import PiratesGlobals
from pirates.piratesgui import PiratesGuiGlobals
from pirates.piratesbase import TODGlobals
import FishingGlobals
from FishingGameFSM import FishingGameFSM
from FishManager import FishManager
from FishingGameGUI import FishingGameGUI
from LegendaryFishingGameGUI import LegendaryFishingGameGUI
from FishLure import FishLure
from FishingTutorialManager import FishingTutorialManager
from LegendaryFishingGameFSM import LegendaryFishingGameFSM
from pirates.effects.SeaBottomBubbleEffect import SeaBottomBubbleEffect
from pirates.effects.LureHittingWaterBubbleEffect import LureHittingWaterBubbleEffect
from pirates.effects.PooledEffect import PooledEffect
from pirates.effects.LightRay import LightRay
from pandac.PandaModules import MouseButton
from pirates.minigame.LegendaryTellGUI import LegendaryTellGUI
from pirates.world.LocationConstants import LocationIds
from direct.fsm.FSM import RequestDenied
from pirates.seapatch.Water import Water
class FishingGame(DirectObject.DirectObject):
def __init__(self, distributedFishingSpot = None):
base.fishingGame = self
self.accept('onCodeReload', self.codeReload)
self.lureAngle = 0
self.lureForceTarget = 0
self.lureCurrForce = 0
self.wantLeg = False
self.forceTarget = Vec2(-0.10000000000000001, 0.10000000000000001)
self.currForce = Vec2(0, 0)
self.boundaryTarget = Vec2(0, 0)
self.currBoundary = Vec2(0, 0)
self.cbm = CullBinManager.getGlobalPtr()
self.distributedFishingSpot = distributedFishingSpot
self.fishingSpot = NodePath('fishingSpot')
self.gui = FishingGameGUI(self)
self.lfgGui = LegendaryFishingGameGUI(self)
self.setupScene()
self.fishManager = FishManager(self)
base.loadingScreen.beginStep('rest', 3, 20)
self.tutorialManager = FishingTutorialManager()
PooledEffect.poolLimit = 50
self.currentFishingLevel = self.getPlayerFishingLevel()
self.setupCamera()
base.loadingScreen.tick()
base.localAvatar.bindAnim('fsh_smallCast')
base.localAvatar.bindAnim('fsh_bigCast')
base.localAvatar.bindAnim('fsh_idle')
base.localAvatar.bindAnim('fsh_smallSuccess')
base.localAvatar.bindAnim('fsh_bigSuccess')
if self.distributedFishingSpot.onABoat:
waterOffset = FishingGlobals.waterLevelOffset['boat']
else:
waterOffset = FishingGlobals.waterLevelOffset['land']
self.boatFishingCameraOffset = Point3(0.0, 0.0, 0.0)
if self.distributedFishingSpot.onABoat:
if self.distributedFishingSpot.index == 0:
self.distributedFishingSpot.oceanOffset = 13.300000000000001
self.boatFishingCameraOffset = FishingGlobals.boatSpotIndexToCameraOffset[self.distributedFishingSpot.index]
if self.distributedFishingSpot.index == 1:
self.distributedFishingSpot.oceanOffset = 13.300000000000001
self.boatFishingCameraOffset = FishingGlobals.boatSpotIndexToCameraOffset[self.distributedFishingSpot.index]
if self.distributedFishingSpot.index == 2:
self.distributedFishingSpot.oceanOffset = 13.300000000000001
self.boatFishingCameraOffset = FishingGlobals.boatSpotIndexToCameraOffset[self.distributedFishingSpot.index]
if self.distributedFishingSpot.index == 3:
self.distributedFishingSpot.oceanOffset = 13.300000000000001
self.boatFishingCameraOffset = FishingGlobals.boatSpotIndexToCameraOffset[self.distributedFishingSpot.index]
if self.distributedFishingSpot.index == 4:
self.distributedFishingSpot.oceanOffset = 13.300000000000001
self.boatFishingCameraOffset = FishingGlobals.boatSpotIndexToCameraOffset[self.distributedFishingSpot.index]
if self.distributedFishingSpot.index == 5:
self.distributedFishingSpot.oceanOffset = 13.300000000000001
self.boatFishingCameraOffset = FishingGlobals.boatSpotIndexToCameraOffset[self.distributedFishingSpot.index]
self.waterLevel = waterOffset - self.distributedFishingSpot.oceanOffset
self.castDistance = 0.0
self.stateToNextStateWhenLureIsDone = {
'Reeling': 'PlayerIdle',
'QuickReel': 'PlayerIdle',
'Fishing': 'PlayerIdle',
'ReelingFish': 'Reward',
'FishOnHook': 'Reward',
'Lose': 'PlayerIdle' }
base.loadingScreen.tick()
self.levelAtCastStart = None
self.lineHealth = FishingGlobals.maxLineHealth
self.resetSceneParallel = None
self.castSeq = None
self.rewardSequence = None
self.hookedIt = False
self.reelVelocityMultiplier = 1.0
self.attractionCollisionVisualsVisible = False
self.avoidanceCollisionVisualsVisible = False
self.scareFish = False
self.oceanEye = False
self.restoreFish = False
self.prevClickingTime = 0.0
self.initClicking = False
self.halfwayAround = False
self.lastRodRotationValue = 0.0
self.dragHandleMode = False
self.initDrag = False
self.elapsedReelingTime = 0.0
self.legendaryFishShowSequence = Sequence()
self.lfgFishingHandleGrabSequence = Sequence()
self.enterReelingFishStateSequence = Sequence()
self.lfgReelingFishInterval = None
self.lightRays = []
self.lureStallTime = 0
self.fsm = FishingGameFSM(self)
self.lfgFsm = LegendaryFishingGameFSM(self)
self.fsm.request('Offscreen')
base.loadingScreen.endStep('rest')
self.accept('open_main_window', self.windowChanged)
self.accept('inventoryQuantity-%s-%s' % (localAvatar.getInventoryId(), InventoryType.RegularLure), self.gui.updateLureQuantities)
self.accept('inventoryQuantity-%s-%s' % (localAvatar.getInventoryId(), InventoryType.LegendaryLure), self.gui.updateLureQuantities)
def shaderTickUpdate(self, task):
dt = globalClock.getDt()
time = globalClock.getFrameTime()
tick = time % 10
render.setShaderInput('timeInfo', Vec4(dt, time, tick, 0.0))
return task.cont
def handleSpinningSpeedBaseOnFishStamina(self, dt):
return FishingGlobals.handleSpinningSpeed * self.fishManager.activeFish.myData['speed'] * self.fishManager.activeFish.staminaPercentage() * dt * 20.0
def getFishStruggleForceBaseOnStamina(self, dt):
return FishingGlobals.fishingRodInclineDegree * self.fishManager.activeFish.myData['strength'] * (1 + self.fishManager.activeFish.staminaPercentage() * 0.59999999999999998) * dt * 20.0
def fishingRodPullbyHumanDegree(self):
return FishingGlobals.humanPulledfishingRodBackDegree * 0.40000000000000002
def getSwimSpeedBaseOnFishStamina(self, currentState, dt):
return FishingGlobals.lureVelocities[currentState] * dt * (self.fishManager.activeFish.staminaPercentage() * 0.5 + 0.5)
def setAsOceanEyeMode(self):
if self.oceanEye:
return None
self.toggleOceanEye()
def swapFSM(self, a, b):
return (b, a)
def changeCameraPosHpr(self):
base.cam.setPos(FishingGlobals.cameraPosLegendaryFinal)
base.cam.setHpr(FishingGlobals.cameraHprLegendaryFinal)
def cleanLegendaryFishingGameFlags(self):
self.dragHandleMode = False
self.elapsedReelingTime = 0.0
def cleanLegendaryFishingGameGUI(self):
if self.lfgGui is None:
return None
self.lfgGui.hideAllGUI()
base.localAvatar.guiMgr.combatTray.skillTray.show()
def setLegendaryRodDangerSound(self, playSound):
if playSound:
if self.sfx['legendaryRed'].status() != 2:
self.sfx['legendaryRed'].setLoop(True)
self.sfx['legendaryRed'].play()
a = FishingGlobals.loseFishingRodAngle
b = FishingGlobals.struggleDangerThreshold
c = self.lfgGui.fishingRod.getR()
if c == a:
return None
percentToFail = (c - b) / float(a - b)
base.musicMgr.requestChangeVolume(SoundGlobals.SFX_MINIGAME_FISHING_LEGENDARY_MUSIC, 0.10000000000000001, percentToFail * 0.20000000000000001 + 0.59999999999999998)
self.sfx['legendaryRed'].setVolume(percentToFail * 4)
elif self.sfx['legendaryRed'].status() is 1:
return None
self.sfx['legendaryRed'].stop()
base.musicMgr.requestChangeVolume(SoundGlobals.SFX_MINIGAME_FISHING_LEGENDARY_MUSIC, 0.10000000000000001, 0.59999999999999998)
def testForLegendaryFish(self, task = None):
if self.distributedFishingSpot.onABoat and self.fsm.state == 'Fishing':
if ((self.wantLeg or self.fishManager.caughtFish > 0) and self.lure.currentLureType is not None or self.lure.currentLureType is 'legendary') and self.lure.getX() > FishingGlobals.lurePositionRangesForLegendaryFishingGame['xRange'][0] and self.lure.getX() < FishingGlobals.lurePositionRangesForLegendaryFishingGame['xRange'][1] and self.lure.getZ() < FishingGlobals.lurePositionRangesForLegendaryFishingGame['zRange'][0] and self.lure.getZ() > FishingGlobals.lurePositionRangesForLegendaryFishingGame['zRange'][1]:
if self.wantLeg or random.random() < FishingGlobals.legendaryFishShowChance:
self.startLegendaryFishingGame(self.wantLeg)
taskMgr.remove('testLegendaryFishingGameLaterTask')
return None
taskMgr.doMethodLater(FishingGlobals.timeBetweenLegendaryFishTests, self.testForLegendaryFish, self.distributedFishingSpot.uniqueName('testLegendaryFishingGameLaterTask'))
def startLegendaryFishingGame(self, whichFish = None):
if self.fsm.getCurrentOrNextState() == 'LegendaryFish' or self.fishManager.activeFish is not None:
return None
self.gui.hideGui()
base.localAvatar.guiMgr.combatTray.skillTray.hide()
self.fsm.request('LegendaryFish')
self.lfgFsm.request('LegdFishShow', whichFish)
taskMgr.remove('testLegendaryFishingGameLaterTask')
def pauseLegendaryFishingGame(self):
self.lfgGui.hideAllGUI()
(self.fsm, self.oldFSM) = self.swapFSM(self.fsm, self.oldFSM)
oldState = self.oldFSM.getCurrentOrNextState()
self.oldFSM.request('Pause')
self.fsm.request(oldState)
def resumeLegendaryFishingGame(self):
(self.fsm, self.oldFSM) = self.swapFSM(self.fsm, self.oldFSM)
self.oldFSM.request('Pause')
self.fsm.request('Fishing')
self.lfgGui.showAllGUI()
def loseLegendaryFishingGame(self):
self.fishManager.activeFish.fsm.request('Offscreen')
self.sfx['legendaryFail'].play()
self.lfgFsm.request('Offscreen')
self.fsm.request('Lose')
self.fishManager.loadFish()
self.restoreFish = True
def legendaryFishShow(self, whichFish = None):
self.fishManager.scareAwayNormalFish()
self.legendaryFishShowSequence = Sequence(Wait(FishingGlobals.legendaryMusicIntroDuration), Func(self.setAsOceanEyeMode), Wait(FishingGlobals.legendaryFishArrivalDelay), Func(self.fishManager.startLegendaryFish, whichFish), name = self.distributedFishingSpot.uniqueName('legendaryFishShowSequence'))
self.legendaryFishShowSequence.start()
def initMouseClickingFlags(self):
self.saveFishingRod = 0
self.prevClickingTime = globalClock.getFrameTime()
self.startStruggleTime = globalClock.getFrameTime()
taskMgr.doMethodLater(0.050000000000000003, self.checkStruggle, 'checkStruggle')
def checkForMouseClickRate(self):
now = globalClock.getFrameTime()
elapsedTime = now - self.prevClickingTime
self.prevClickingTime = now
if elapsedTime < FishingGlobals.clickingRateThreshold:
self.saveFishingRod += 1
def moveRodBasedOnClicks(self, task):
return Task.cont
def fishingHandleTurning(self, dt, currentState):
if not base.mouseWatcherNode.hasMouse():
return None
newR = math.degrees(math.atan2(self.lfgGui.fishingHandle.getX() - base.mouseWatcherNode.getMouseX(), self.lfgGui.fishingHandle.getZ() - base.mouseWatcherNode.getMouseY()))
self.lfgGui.fishingHandle.setR(newR)
if not self.halfwayAround:
if self.lastRodRotationValue > 120.0 and newR < 120.0:
self.halfwayAround = True
elif self.lastRodRotationValue < 0.0 and newR > 0.0 and newR < 90.0:
weight = self.fishManager.activeFish.weight
newX = max(FishingGlobals.leftLureBarrier, self.lure.getX() + (15.0 - weight) * self.reelVelocityMultiplier * FishingGlobals.lureVelocities[currentState][0] * dt)
newZ = max(-(self.castDistance), min(self.lure.getZ() + (15.0 - weight) * self.reelVelocityMultiplier * FishingGlobals.lureVelocities[currentState][2] * dt, self.waterLevel))
duration = self.elapsedReelingTime
self.elapsedReelingTime = 0.0
self.lfgReelingFishInterval = LerpPosInterval(self.lure, duration, Point3(newX, -1.0, newZ), self.lure.getPos(), blendType = 'easeInOut', name = self.distributedFishingSpot.uniqueName('lfgReelingFishInterval'))
self.lfgReelingFishInterval.start()
self.halfwayAround = False
self.lastRodRotationValue = newR
self.elapsedReelingTime += dt
def toggleAvoidanceCollisionVisuals(self):
if FishingGlobals.wantDebugCollisionVisuals:
self.avoidanceCollisionVisualsVisible = not (self.avoidanceCollisionVisualsVisible)
if self.avoidanceCollisionVisualsVisible:
self.fishManager.showAvoidanceCollisionVisuals()
else:
self.fishManager.hideAvoidanceCollisionVisuals()
def toggleAttractionCollisionVisuals(self):
if FishingGlobals.wantDebugCollisionVisuals:
self.attractionCollisionVisualsVisible = not (self.attractionCollisionVisualsVisible)
if self.attractionCollisionVisualsVisible:
self.fishManager.showAttractionCollisionVisuals()
self.lure.showCollisionVisuals()
else:
self.fishManager.hideAttractionCollisionVisuals()
self.lure.hideCollisionVisuals()
def codeReload(self):
reload(FishingGlobals)
self.fishManager.loseInterest()
if FishingGlobals.wantDebugCollisionVisuals:
self.fishManager.reloadCollisions()
self.fishManager.codeReload()
self.setupCamera()
def windowChanged(self):
base.cam.reparentTo(self.fishingSpot)
def setupCamera(self):
if self.distributedFishingSpot.onABoat:
self.fishingSpot.reparentTo(self.distributedFishingSpot)
self.fishingSpot.setPos(self.distributedFishingSpot.getPos())
else:
self.fishingSpot.reparentTo(localAvatar.getParent())
self.fishingSpot.setPos(self.distributedFishingSpot.getPos(localAvatar.getParent()))
self.fishingSpot.setHpr(self.distributedFishingSpot.getHpr(localAvatar.getParent()))
self.fishingSpot.setH(self.fishingSpot.getH() - 90.0)
def delete(self):
self.ignoreAll()
if self.backdropTransitionIval:
self.backdropTransitionIval.pause()
self.backdropTransitionIval = None
self.stopLightRays()
self.stopSeaBottomBubbles()
PooledEffect.poolLimit = 30
if self.fsm.getCurrentOrNextState() not in [
'Offscreen',
'Off']:
self.fsm.request('Offscreen')
self.gui.destroy()
self.gui = None
self.fishManager.destroy()
self.lfgGui.hideAllGUI()
self.lfgGui.destroy()
self.lfgGui = None
self.fishingSpot.removeNode()
self.backdrop.removeNode()
self.lure.destroy()
self.fishingLine.removeNode()
self.distributedFishingSpot = None
taskMgr.remove('checkStruggle')
taskMgr.remove('stopOceanEyeTask')
taskMgr.remove('stopPullTask')
taskMgr.remove('stopLureStallTask')
taskMgr.remove('stopLureSinkTask')
def setupScene(self):
base.loadingScreen.beginStep('SetupScene', 3, 20)
self.sfx = {
'biteLarge': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_BITE_LARGE),
'biteSmall': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_BITE_SMALL),
'biteAlert': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_BITE_ALERT),
'fishEscape': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_ESCAPE),
'fishFight01': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_FIGHT_01),
'fishFight02': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_FIGHT_02),
'fishOutLarge01': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_LARGE_01),
'fishOutLarge02': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_LARGE_02),
'fishOutLarge03': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_LARGE_03),
'fishOutSmall01': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_SMALL_01),
'fishOutSmall02': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_SMALL_02),
'fishOutSmall03': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_SMALL_03),
'fishOutMedium01': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_MEDIUM_01),
'fishOutMedium02': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_FISH_OUT_MEDIUM_02),
'castLarge': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_CAST_LARGE),
'castSmall': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_CAST_SMALL),
'lureEquip': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LURE_EQUIP),
'successCaught': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_SUCCESS_CAUGHT),
'usability': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_USABILITY),
'ambience': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_AMBIENCE),
'legendaryReelSpin': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LEGENDARY_REEL_SPIN),
'lineReelFast': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LINE_REEL_FAST),
'lineReelSlow': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LINE_REEL_SLOW),
'legendaryGreen': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LEGENDARY_GREEN),
'legendaryRed': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LEGENDARY_RED),
'legendarySuccess': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LEGENDARY_SUCCESS),
'legendaryFail': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LEGENDARY_FAIL),
'lureHit': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LURE_HIT),
'lureOut': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_LURE_OUT),
'reelEnd': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_REEL_END),
'rodOut': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_ROD_OUT),
'rodPutAway': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_ROD_PUT_AWAY),
'fishingSkill': loadSfx(SoundGlobals.SFX_MINIGAME_FISHING_SKILL) }
base.loadingScreen.tick()
self.backdrop = loader.loadModel('models/minigames/pir_m_gam_fsh_fishEnvironment')
self.backdrop.findAllMatches('**/lightRay*').detach()
self.backdrop.reparentTo(self.fishingSpot)
self.backdrop.setTransparency(1, 1000)
self.backdrop.setFogOff()
self.backdrop.setLightOff()
self.backdropTransitionIval = None
self.transitionBackdrop()
if self.distributedFishingSpot.onABoat:
self.backdrop.setPos(35.0, 8.0, -86.0 - self.distributedFishingSpot.oceanOffset)
else:
self.backdrop.setPos(25.0, 8.0, -86.0 - self.distributedFishingSpot.oceanOffset)
self.backdrop.setHpr(0.0, 0.0, 0.0)
self.seaBottomBubbleEffects = []
self.cbm.addBin('fishingGame', CullBinManager.BTFixed, 30)
self.backdrop.setBin('fishingGame', 0)
self.backdrop.find('**/environment').setBin('fishingGame', 1)
self.backdrop.setDepthWrite(True)
self.backdrop.setDepthTest(True)
base.loadingScreen.tick()
self.lure = FishLure(self, 'regular')
self.lure.lureModel.setBin('fishingGame', 10)
self.setupLine(Point3(0, 0, 0), Point3(0, 1, 0))
self.sandfloors = render.findAllMatches('**/sandfloor')
base.loadingScreen.endStep('SetupScene')
def startSeaBottomBubbles(self):
fishBarrierDist = FishingGlobals.rightFishBarrier - FishingGlobals.leftFishBarrier
numEmitters = 9
startX = FishingGlobals.leftFishBarrier - 1.0
zDepth = -75
spread = fishBarrierDist / numEmitters
for i in range(numEmitters):
effect = SeaBottomBubbleEffect.getEffect(unlimited = True)
if effect:
self.seaBottomBubbleEffects.append(effect)
effect.startLoop()
effect.p0.factory.setLifespanBase(30)
effect.reparentTo(self.fishingSpot)
effect.setPos(spread * i + startX, 0, zDepth)
effect.particleDummy.setBin('fishingGame', 5)
continue
numEmitters = 5
startX = FishingGlobals.leftFishBarrier + 3.5
zDepth = -50
spread = fishBarrierDist / numEmitters
for i in range(numEmitters):
effect = SeaBottomBubbleEffect.getEffect(unlimited = True)
if effect:
self.seaBottomBubbleEffects.append(effect)
effect.startLoop()
effect.p0.factory.setLifespanBase(22)
effect.reparentTo(self.fishingSpot)
effect.setPos(spread * i + startX, 0, zDepth)
effect.particleDummy.setBin('fishingGame', 5)
continue
numEmitters = 6
startX = FishingGlobals.leftFishBarrier - 5.0
zDepth = -35
spread = (fishBarrierDist + 15.0) / numEmitters
for i in range(numEmitters):
effect = SeaBottomBubbleEffect.getEffect(unlimited = True)
if effect:
self.seaBottomBubbleEffects.append(effect)
effect.startLoop()
effect.p0.factory.setLifespanBase(16)
effect.reparentTo(self.fishingSpot)
effect.setPos(spread * i + startX, 0, -35)
effect.particleDummy.setBin('fishingGame', 5)
continue
def stopSeaBottomBubbles(self):
for effect in self.seaBottomBubbleEffects:
effect.detachNode()
effect.stopLoop()
self.seaBottomBubbleEffects = []
def hideSeaBottomBubbles(self):
for effect in self.seaBottomBubbleEffects:
effect.hide()
def showSeaBottomBubbles(self):
for effect in self.seaBottomBubbleEffects:
effect.show()
def resetScene(self):
self.lure.resetLureModel()
self.lure.wrtReparentTo(self.endOfRod)
self.lure.setHpr(0.0, 0.0, 0.0)
lureResetInterval = LerpPosInterval(self.lure, FishingGlobals.resetDuration, Point3(0.0, 0.0, 0.0))
self.fishingLine.show()
self.lure.show()
self.resetSceneParallel = Parallel(lureResetInterval, name = 'resetScene')
self.resetSceneParallel.start()
def hideScene(self):
self.oceanEye = False
base.cam.reparentTo(self.fishingSpot)
if self.resetSceneParallel is not None:
self.resetSceneParallel.pause()
self.resetSceneParallel.clearToInitial()
if self.castSeq is not None:
self.castSeq.pause()
self.castSeq.clearToInitial()
if self.rewardSequence is not None:
self.rewardSequence.pause()
self.rewardSequence.clearToInitial()
self.backdrop.reparentTo(hidden)
self.lure.resetLureModel()
self.lure.reparentTo(hidden)
self.fishingLine.reparentTo(hidden)
for floor in self.sandfloors:
floor.show()
self.stopLightRays()
self.stopSeaBottomBubbles()
self.verifyWaterReflections()
self.ignore('options_reflections_change')
def showScene(self):
self.backdrop.reparentTo(self.fishingSpot)
self.endOfRod = base.localAvatar.find('**/fishingRod').find('**/end_of_rod')
self.endOfRod.wrtReparentTo(base.localAvatar.find('**/fishingRod'))
base.localAvatar.find('**/fishingRod').setHpr(0.0, 0.0, -90.0)
self.lure.reparentTo(self.endOfRod)
self.fishingLine.reparentTo(self.fishingSpot)
base.cam.setPos(FishingGlobals.stateToCameraOffsetInfo['PlayerIdle'][0] + self.boatFishingCameraOffset)
self.lure.resetLureModel()
self.lure.reparentTo(self.endOfRod)
self.lure.setScale(1, 1, 1)
self.lure.setPosHpr(0, 0, 0, 0, 0, 0)
for floor in self.sandfloors:
floor.hide()
self.startLightRays()
self.startSeaBottomBubbles()
def hideFishAndBackdrop(self):
for fish in self.fishManager.uncaughtFish:
fish.hide()
self.backdrop.hide()
self.hideLightRays()
self.hideSeaBottomBubbles()
self.verifyWaterReflections()
self.ignore('options_reflections_change')
def showFishAndBackdrop(self):
for fish in self.fishManager.uncaughtFish:
fish.show()
self.backdrop.show()
self.showLightRays()
self.showSeaBottomBubbles()
self.turnWaterReflectionsOff()
self.accept('options_reflections_change', self.turnWaterReflectionsOff)
def updateLine(self, startPoint, endPoint, color):
self.fishingLine.setPos(startPoint)
self.fishingLine.lookAt(endPoint)
self.lengthOfLine = (endPoint - startPoint).length()
self.fishingLine.setScale(1, self.lengthOfLine, 1)
self.fishingLine.setColorScale(*color)
def setupLine(self, startPoint, endPoint):
self.line = LineSegs()
self.fishingLine = None
self.line.setColor(*FishingGlobals.defaultFishingLineColor)
self.line.setThickness(FishingGlobals.fishingLineThickness)
self.line.moveTo(startPoint)
self.line.drawTo(endPoint)
self.fishingLine = self.fishingSpot.attachNewNode(self.line.create())
self.fishingLine.setTransparency(True)
self.fishingLine.setBin('fishingGame', 10)
self.fishingLine.setDepthWrite(False)
self.fishingLine.setDepthTest(False)
self.fishingLine.setLightOff()
def getLineColorBasedOnHealth(self):
return FishingGlobals.fishingLineHealthToColor[int((self.lineHealth / 100.0) * (len(FishingGlobals.fishingLineHealthToColor) - 1))]
def updateFishingGame(self, task):
dt = task.time
currentState = None
if self.fsm.state in [
'PlayerIdle',
'ChargeCast',
'Reward']:
self.lureAngle = 0
else:
lureVec = self.lure.getPos() - self.endOfRod.getPos()
lureVec.normalize()
self.lureAngle = -(180 - math.degrees(math.atan2(lureVec.getX(), lureVec.getZ())))
lureR = self.lure.lureModel.getR()
if lureR > self.lureAngle:
lureSign = 1
self.lureForceTarget -= 5
else:
lureSign = 0
self.lureForceTarget += 5
self.lureCurrForce += (self.lureForceTarget - self.lureCurrForce) * 0.5
self.lure.lureModel.setR(self.lure.lureModel.getR() + self.lureCurrForce * dt)
if (self.lure.lureModel.getR() > self.lureAngle or not lureSign or self.lure.lureModel.getR() < self.lureAngle) and lureSign:
if abs(self.lureForceTarget) > 10:
self.lureForceTarget *= 0.59999999999999998
self.lureCurrForce *= 0.59999999999999998
if self.fsm.getCurrentOrNextState() == 'LegendaryFish':
currentState = self.lfgFsm.getCurrentOrNextState()
if currentState in [
'ReelingFish']:
self.fishingHandleTurning(dt, currentState)
if int(self.lure.getX()) <= int(FishingGlobals.leftLureBarrier) and int(self.lure.getZ()) >= int(self.waterLevel):
self.lfgFsm.request('Win')
elif currentState in [
'Struggle']:
self.lfgGui.fishingRod.setR(self.lfgGui.fishingRod.getR() + self.getFishStruggleForceBaseOnStamina(dt))
currentTime = globalClock.getFrameTime()
timeLeft = int(math.ceil(FishingGlobals.maxStruggleTime - currentTime - self.startStruggleTime))
percent = (FishingGlobals.maxStruggleTime - currentTime - self.startStruggleTime) / FishingGlobals.maxStruggleTime
self.lfgGui.updateStruggleTimerText(timeLeft, percent)
if self.lfgGui.fishingRod.getR() > FishingGlobals.struggleDangerThreshold or timeLeft <= FishingGlobals.struggleTimeDangerThreshold:
self.setLegendaryRodDangerSound(True)
else:
self.setLegendaryRodDangerSound(False)
if self.lfgGui.fishingRod.getR() >= FishingGlobals.loseFishingRodAngle:
self.lfgFsm.request('Transition', 'CatchIt')
self.fishManager.activeFish.fsm.request('PullingLure')
elif currentTime - self.startStruggleTime > FishingGlobals.maxStruggleTime:
self.lfgFsm.request('Transition', 'CatchIt')
self.fishManager.activeFish.fsm.request('PullingLure')
elif currentState in [
'CatchIt']:
moveSpeed = self.getSwimSpeedBaseOnFishStamina(currentState, dt)
speed = self.fishManager.activeFish.myData['speed']
newX = max(FishingGlobals.leftLureBarrier, self.lure.getX() + speed * moveSpeed[0])
newZ = min(max(FishingGlobals.fishingLevelBoundariesBoat[len(FishingGlobals.fishingLevelBoundariesBoat) - 1], self.lure.getZ() + speed * moveSpeed[2]), self.waterLevel)
self.lure.setPos(newX, -1.0, newZ)
self.lfgGui.fishingHandle.setR(self.lfgGui.fishingHandle.getR() - self.handleSpinningSpeedBaseOnFishStamina(dt))
if self.lure.getX() >= FishingGlobals.rightFishBarrier:
self.loseLegendaryFishingGame()
else:
currentState = self.fsm.getCurrentOrNextState()
if currentState in [
'Fishing',
'Reeling',
'QuickReel',
'ReelingFish',
'Lose',
'FishOnHook']:
self.currBoundary += (self.boundaryTarget - self.currBoundary) * 0.25
self.currForce += (self.forceTarget - self.currForce) * 0.25
if (self.forceTarget - self.currForce).length() < 0.01:
self.forceTarget = Vec2(random.uniform(-0.10000000000000001, 0.10000000000000001), random.uniform(-0.10000000000000001, 0.10000000000000001))
newX = self.lure.getX() + (self.reelVelocityMultiplier * FishingGlobals.lureVelocities[currentState][0] + self.currBoundary[0] + self.currForce[0]) * dt
if newX < FishingGlobals.leftLureBarrier:
self.boundaryTarget[0] += 0.29999999999999999
elif self.boundaryTarget[0] > 0:
self.boundaryTarget[0] = max(0, self.boundaryTarget[0] - 0.40000000000000002)
newZ = min(self.lure.getZ() + (self.reelVelocityMultiplier * FishingGlobals.lureVelocities[currentState][2] + self.currBoundary[1] + self.currForce[1]) * dt, self.waterLevel)
if (newZ < -(self.castDistance) or currentState == 'Fishing') and newZ < FishingGlobals.fishingLevelBoundaries[self.getRodLevel() - 1]:
self.boundaryTarget[1] += 0.10000000000000001
elif self.boundaryTarget[1] > 0:
self.boundaryTarget[1] = max(0, self.boundaryTarget[1] - 0.29999999999999999)
self.lure.setPos(newX, -1.0, newZ)
if int(self.lure.getX()) <= int(FishingGlobals.leftLureBarrier) and int(self.lure.getZ()) >= int(self.waterLevel):
self.sfx['lureOut'].play()
self.sfx['reelEnd'].play()
self.fsm.request(self.stateToNextStateWhenLureIsDone[currentState])
elif currentState in [
'LureSink']:
newZ = max(-(self.castDistance), min(self.lure.getZ() + self.reelVelocityMultiplier * FishingGlobals.lureVelocities[currentState][2] * dt, self.waterLevel))
newZ = max(newZ, FishingGlobals.fishingLevelBoundaries[len(FishingGlobals.fishingLevelBoundaries) - 1])
self.lure.setPos(self.lure.getX(), -1.0, newZ)
elif currentState in [
'FishFighting']:
newX = self.lure.getX() + FishingGlobals.lureVelocities[currentState][0] * dt * self.fishManager.activeFish.myData['speed']
self.lure.setX(newX)
if newX > FishingGlobals.rightLureBarrier:
self.fsm.request('Lose')
return Task.again
if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
self.lineHealth = self.lineHealth - self.fishManager.activeFish.myData['strength']
self.gui.updateLineHealthMeter(self.lineHealth)
if self.lineHealth <= 0:
self.fsm.request('Lose')
return Task.again
if self.lineHealth <= FishingGlobals.maxLineHealth * 0.5:
self.tutorialManager.showTutorial(InventoryType.FishingLineHealth)
lineLength = self.lure.getDistance(self.endOfRod)
currentState = self.fsm.getCurrentOrNextState()
if currentState != 'Lose':
self.gui.lineLengthLabel.showText(str(int(lineLength)), (1, 1, 1, 1))
startPoint = self.endOfRod.getPos(self.fishingSpot)
endPoint = self.lure.lureModel.getPos(self.fishingSpot)
currentState = self.fsm.getCurrentOrNextState()
if currentState in [
'FishOnHook',
'ReelingFish',
'FishFighting',
'LegendaryFish']:
endPoint = self.lure.lureModel.getPos(self.fishingSpot)
self.updateLine(startPoint, endPoint, self.getLineColorBasedOnHealth())
else:
endPoint = self.lure.getPos(self.fishingSpot)
self.updateLine(startPoint, endPoint, Vec4(0.29999999999999999, 0.29999999999999999, 1.0, 0.5))
self.fishManager.update(dt)
if self.lfgFsm.getCurrentOrNextState() in [
'Win',
'FarewellLegendaryFish']:
return Task.again
camPos = base.cam.getPos()
cameraOffset = FishingGlobals.stateToCameraOffsetInfo[currentState][0] + self.boatFishingCameraOffset
if self.oceanEye:
goalPos = Point3(*FishingGlobals.oceanEyeCameraPosition)
camRange = (0, 1, 2)
elif FishingGlobals.stateToCameraOffsetInfo[currentState][2]:
goalPos = self.lure.getPos()
goalPos[1] = cameraOffset[1]
camRange = (0, 1, 2)
elif FishingGlobals.stateToCameraOffsetInfo[currentState][1] and self.fishManager.activeFish is not None:
goalPos = self.fishManager.activeFish.mouthJoint.getPos(self.fishingSpot)
if self.fishManager.activeFish.myData['size'] == 'large':
goalPos[1] = cameraOffset[1] - 5.0
elif self.fishManager.activeFish.myData['size'] == 'medium':
goalPos[1] = cameraOffset[1]
else:
goalPos[1] = cameraOffset[1] + 5.0
camRange = (0, 1, 2)
else:
goalPos = Point3(cameraOffset)
camRange = (0, 1, 2)
for i in camRange:
goalPos[i] = camPos[i] * (1.0 - dt * 5.0) + goalPos[i] * dt * 5.0
base.cam.setPos(goalPos)
return Task.again
def checkStruggle(self, task = None):
currentState = self.lfgFsm.getCurrentOrNextState()
if currentState != 'Struggle':
return Task.done
self.lfgGui.fishingRod.setR(self.lfgGui.fishingRod.getR() - self.fishingRodPullbyHumanDegree() * self.saveFishingRod)
self.saveFishingRod = 0
if self.lfgGui.fishingRod.getR() <= FishingGlobals.saveFishingRodAngle:
self.lfgFsm.request('Transition', 'ReelingFish')
self.fishManager.activeFish.fsm.request('Hooked')
self.sfx['legendaryGreen'].play()
return Task.done
return Task.cont
def toggleOceanEye(self):
self.oceanEye = not (self.oceanEye)
def castLure(self):
self.levelAtCastStart = self.getPlayerFishingLevel()
if self.gui.castMeterBar.getSz() * 100.0 < FishingGlobals.minimumCastDistance:
self.gui.castMeterBar.setSz(FishingGlobals.minimumCastDistance / 100)
if self.restoreFish:
self.restoreFish = False
self.fishManager.startup()
self.castDistance = self.gui.castMeterBar.getSz() * 100 * FishingGlobals.castDistanceMultiplier[localAvatar.currentWeaponId]
if self.distributedFishingSpot.onABoat:
self.castDistance += FishingGlobals.minimumCastDistanceOnABoat
else:
self.castDistance += FishingGlobals.minimumCastDistance
if self.castDistance > FishingGlobals.maxCastDistance:
self.castDistance = FishingGlobals.maxCastDistance
bestRod = self.getAvatarsBestRod()
if bestRod == -1:
notify.error('Somehow the avatar got into the fishing game without a rod in their inventory!')
castAnim = 'fsh_smallCast'
if bestRod == ItemGlobals.FISHING_ROD_3:
if self.gui.castMeterBar.getSz() * 100 > 50:
castAnim = 'fsh_bigCast'
self.castTime = FishingGlobals.lureFlightDuration[castAnim] + self.castDistance * 0.01
FishingGlobals.stateToCameraOffsetInfo['Cast'][2] = False
if self.distributedFishingSpot.onABoat:
FishingGlobals.stateToCameraOffsetInfo['Cast'][0][1] = -48.0
self.castTime += 0.5
self.castSeq = Sequence(Func(localAvatar.play, castAnim), Wait(FishingGlobals.castReleaseDelay[castAnim]), Func(self.lureTrajectory, castAnim), Parallel(Wait(self.castTime), Sequence(Wait(self.castTime - 1.0), Func(self.startHitWaterBubbleEffect))), Func(self.sfx['lureHit'].play), Func(self.fsm.request, 'Fishing'), name = 'castLure')
self.castSeq.start()
def startHitWaterBubbleEffect(self):
self.hitWaterBubbleEffect = LureHittingWaterBubbleEffect.getEffect(unlimited = True)
if self.hitWaterBubbleEffect:
self.hitWaterBubbleEffect.reparentTo(self.fishingSpot)
self.hitWaterBubbleEffect.setPos(self.castDistance - 1.5, 0.0, self.waterLevel + 1.5)
self.hitWaterBubbleEffect.particleDummy.setBin('fishingGame', 5)
self.hitWaterBubbleEffect.play()
def lureTrajectory(self, anim):
self.lure.wrtReparentTo(self.fishManager.objectsWithCaustics)
self.lure.setHpr(0.0, 0.0, 0.0)
trajectory = ProjectileInterval(self.lure, startPos = self.lure.getPos(), endPos = Point3(self.castDistance, 0.0, self.waterLevel), duration = self.castTime)
trajectory.start()
FishingGlobals.stateToCameraOffsetInfo['Cast'][2] = True
def checkForHookSuccess(self):
if self.fishManager.activeFish.fsm.getCurrentOrNextState() == 'Biting':
self.fishManager.activeFish.fishStatusIconTextNode.setText('!')
self.fishManager.activeFish.fishStatusIconTextNode.setTextColor(1.0, 0.0, 0.0, 1.0)
self.hookedIt = True
self.checkForHooked()
def checkForHooked(self):
if self.fsm.getCurrentOrNextState() == 'LegendaryFish':
self.attachFishToLure()
self.fishManager.activeFish.fishStaminaConsume()
self.fishManager.loseInterest()
self.lfgFsm.request('Transition', 'Struggle')
elif self.fsm.getCurrentOrNextState() == 'FishBiting':
if self.hookedIt:
self.hookedIt = False
self.attachFishToLure()
if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
self.fsm.request('ReelingFish')
else:
self.fsm.request('FishOnHook')
self.fishManager.loseInterest()
elif self.fishManager.activeFish.fsm.getCurrentOrNextState() != 'Flee':
self.fishManager.activeFish.fsm.request('Flee')
self.lure.showHelpText(PLocalizer.Minigame_Fishing_Lure_Alerts['scaredOff'])
if self.fishManager.activeFish.myData['size'] != 'small':
self.fsm.request('Lose')
else:
self.fishManager.activeFish = None
if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
self.fsm.request('Reeling')
else:
self.fsm.request('Fishing')
self.fishManager.activeFish = None
elif self.fishManager.activeFish.fsm and self.fishManager.activeFish.fsm.getCurrentOrNextState() != 'Flee':
self.fishManager.activeFish.fsm.request('Flee')
self.fishManager.activeFish = None
def attachFishToLure(self):
self.fishManager.activeFish.fsm.request('Hooked')
self.lure.lureModel.hide()
self.lure.lureModel.reparentTo(self.fishManager.activeFish.mouthJoint)
self.fishManager.activeFish.reparentTo(self.lure)
self.fishManager.activeFish.setPos(self.fishManager.activeFish.mouthJoint.getPos() * -1.0)
self.fishManager.activeFish.setHpr(0.0, 0.0, 0.0)
def playRewardSequence(self):
self.lure.wrtReparentTo(self.endOfRod)
self.fishManager.activeFish.setPos(self.fishManager.activeFish.mouthJoint.getPos() * -1.0)
self.gui.showRewardDialog(self.fishManager.activeFish)
self.rewardSequence = Parallel(self.lure.hprInterval(FishingGlobals.rewardSequenceReelItInDuration, Point3(*FishingGlobals.fishToLureHprOffset)), self.lure.posInterval(FishingGlobals.rewardSequenceReelItInDuration, Point3(0.0, 0.0, 0.0)), name = 'FishingGameRewardSequence')
self.rewardSequence.start()
def useAbility(self, skillId):
self.lure.enableLureGlow(skillId)
self.sfx['fishingSkill'].play()
if skillId == InventoryType.FishingRodStall:
try:
self.fsm.request('LureStall')
except RequestDenied:
raise StandardError, 'Requesting LureStall from state %s\nTime Difference between LureStall Requests: %s' % (self.fsm.getCurrentOrNextState(), globalClock.getFrameTime() - self.lureStallTime)
self.lureStallTime = globalClock.getFrameTime()
if skillId == InventoryType.FishingRodPull:
speedMult = FishingGlobals.fishingLevelToPullSpeedBoost.get(self.currentFishingLevel, 1.0)
if speedMult == 1.0 and self.currentFishingLevel > 20:
speedMult = FishingGlobals.fishingLevelToPullSpeedBoost.get(20, 1.0)
self.reelVelocityMultiplier = speedMult
taskMgr.doMethodLater(FishingGlobals.pullDuration, self.stopPullTask, 'stopPullTask')
if skillId == InventoryType.FishingRodHeal:
amountToHeal = FishingGlobals.fishingLevelToHealAmount.get(self.currentFishingLevel, 1.0)
if amountToHeal == 1.0 and self.currentFishingLevel > 20:
amountToHeal = FishingGlobals.fishingLevelToHealAmount.get(20, 1.0)
self.lineHealth += amountToHeal
if self.lineHealth > FishingGlobals.maxLineHealth:
self.lineHealth = FishingGlobals.maxLineHealth
self.gui.updateLineHealthMeter(self.lineHealth)
if skillId == InventoryType.FishingRodTug:
if self.fsm.getCurrentOrNextState() in [
'FishFighting']:
self.fishManager.activeFish.fsm.request('Hooked')
if skillId == InventoryType.FishingRodSink:
self.fsm.request('LureSink')
if skillId == InventoryType.FishingRodOceanEye:
self.toggleOceanEye()
taskMgr.doMethodLater(FishingGlobals.oceanEyeDuration, self.stopOceanEyeTask, 'stopOceanEyeTask')
def stopLureStallTask(self, task):
self.fsm.request('Fishing')
return Task.done
def stopLureSinkTask(self, task):
self.fsm.request('Fishing')
return Task.done
def stopOceanEyeTask(self, task):
self.toggleOceanEye()
return Task.done
def stopPullTask(self, task):
self.reelVelocityMultiplier = 1.0
return Task.done
def chooseLure(self, type):
if type == InventoryType.RegularLure:
self.lure.setLureType('regular')
elif type == InventoryType.LegendaryLure:
self.lure.setLureType('legendary')
self.lure.lureModel.setBin('fishingGame', 10)
def pickWeightedItem(self, itemList):
x = random.uniform(0, 100)
for (item, weight) in itemList:
if x < weight:
break
x = x - weight
return item
def canCast(self):
if self.hasLures():
if self.lure.currentLureType is not None:
self.fsm.request('ChargeCast')
else:
localAvatar.guiMgr.createWarning(PLocalizer.FishingNoLureEquipped, PiratesGuiGlobals.TextFG6)
else:
localAvatar.guiMgr.createWarning(PLocalizer.FishingNoLuresWarning, PiratesGuiGlobals.TextFG6)
def hasLures(self):
inv = localAvatar.getInventory()
regular = inv.getStackQuantity(InventoryType.RegularLure)
legendary = inv.getStackQuantity(InventoryType.LegendaryLure)
if regular + legendary <= 0:
return False
else:
return True
def getRodLevel(self):
inv = localAvatar.getInventory()
return inv.getItemQuantity(InventoryType.FishingRod)
def getAvatarsBestRod(self):
inv = localAvatar.getInventory()
rodLvl = inv.getItemQuantity(InventoryType.FishingRod)
if rodLvl == 3:
return ItemGlobals.FISHING_ROD_3
if rodLvl == 2:
return ItemGlobals.FISHING_ROD_2
if rodLvl == 1:
return ItemGlobals.FISHING_ROD_1
return -1
def getPlayerFishingLevel(self):
inv = localAvatar.getInventory()
repAmt = inv.getAccumulator(InventoryType.FishingRep)
repLvl = ReputationGlobals.getLevelFromTotalReputation(InventoryType.FishingRep, repAmt)
return repLvl[0]
def getPredictedPlayerFishingLevel(self, repIncrease):
inv = localAvatar.getInventory()
repAmt = inv.getAccumulator(InventoryType.FishingRep) + repIncrease
repLvl = ReputationGlobals.getLevelFromTotalReputation(InventoryType.FishingRep, repAmt)
return repLvl[0]
def startLightRays(self):
self.lightRays = []
xOffset = 0
if self.distributedFishingSpot.onABoat:
waterLevel = self.waterLevel + 10.0
else:
waterLevel = self.waterLevel
for i in range(16):
lightRay = LightRay.getEffect()
if lightRay:
lightRay.reparentTo(self.fishingSpot)
lightRay.setBin('fishingGame', 3)
lightRay.setPos(xOffset, random.randint(20, 32), waterLevel)
lightRay.setR(-25)
lightRay.startLoop()
self.lightRays.append(lightRay)
xOffset += random.randint(5, 10)
continue
def stopLightRays(self):
for ray in self.lightRays:
ray.stopLoop()
self.lightRays = []
def showLightRays(self):
for ray in self.lightRays:
ray.show()
def hideLightRays(self):
for ray in self.lightRays:
ray.hide()
def transitionBackdrop(self, stateId = None, stateDuration = 0.0, elapsedTime = 0.0, transitionTime = 0.0):
if self.backdropTransitionIval:
self.backdropTransitionIval.pause()
self.backdropTransitionIval = None
todMgr = base.cr.timeOfDayManager
fromState = todMgr.lastState
toState = todMgr.currentState
if base.config.GetBool('want-shaders', 1) and base.win and base.win.getGsg():
pass
usesShader = base.win.getGsg().getShaderModel() >= GraphicsStateGuardian.SM20
if usesShader and self.distributedFishingSpot.onABoat:
usesShader = 2
elif usesShader and localAvatar.getParentObj().getUniqueId() == LocationIds.DEL_FUEGO_ISLAND:
usesShader = 3
fromColor = FishingGlobals.todBackdropColor[fromState][usesShader]
toColor = FishingGlobals.todBackdropColor[toState][usesShader]
if not elapsedTime and todMgr.transitionIval:
elapsedTime = todMgr.transitionIval.getT()
if not transitionTime and todMgr.transitionIval:
transitionTime = todMgr.transitionIval.getDuration()
self.backdropTransitionIval = LerpFunctionInterval(self.backdrop.setColorScale, duration = transitionTime, toData = toColor, fromData = fromColor)
self.backdropTransitionIval.start(elapsedTime)
self.accept('timeOfDayChange', self.transitionBackdrop)
def turnWaterReflectionsOff(self, setting = 0):
Water.all_reflections_off()
def verifyWaterReflections(self):
reflectionSetting = base.options.reflection
if reflectionSetting == 0:
Water.all_reflections_off()
elif reflectionSetting == 1:
Water.all_reflections_show_through_only()
elif reflectionSetting == 2:
Water.all_reflections_on()
def bumpLure(self):
lureR = self.lure.lureModel.getR()
if lureR > self.lureAngle:
self.lureCurrForce -= 40
self.lureForceTarget -= 40
else:
self.lureCurrForce += 40
self.lureForceTarget += 40
def checkLures(self):
inv = localAvatar.getInventory()
if not inv or not inv.getStackQuantity(InventoryType.RegularLure):
self.lure.setLureType(None)
self.gui.toggleLureSelectionDialog()
def updateResultsScreen(self):
self.gui.resultsScreen.updateGoldAndXpBonus()
|
"use strict";
const fs = require('fs');
//save the original require
let originalRequire = require;
function loadModule(filename, module, require) {
const wrappedSrc =
`(function(module, exports, require) {
${fs.readFileSync(filename, 'utf8')}
})(module, module.exports, require);`;
eval(wrappedSrc);
}
// We intentionally use var in the next line to avoid "SyntaxError: Identifier 'require' has already been declared"
var require = (moduleName) => {
console.log(`Require invoked for module: ${moduleName}`);
const id = require.resolve(moduleName); //[1]
if(require.cache[id]) { //[2]
return require.cache[id].exports;
}
//module metadata
const module = { //[3]
exports: {},
id: id
};
//Update the cache
require.cache[id] = module; //[4]
//load the module
loadModule(id, module, require); //[5]
//return exported variables
return module.exports; //[6]
};
require.cache = {};
require.resolve = (moduleName) => {
//reuse the original resolving algorithm for simplicity
return originalRequire.resolve(moduleName);
};
//Load the entry point using our homemade 'require'
require(process.argv[2]);
|
<reponame>bobthered/algodaily<gh_stars>0
const lonelyNumber = arr => {
return arr.filter(
(a, _, arr) => [...arr].filter(b => a === b).length === 1,
)[0];
};
module.exports = lonelyNumber;
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-FW/13-model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-FW/13-512+0+512-rare-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_rare_words_first_half_quarter --eval_function penultimate_quarter_eval
|
function rsync_exclude_file_parameter_list {
local RSYNC_EXCLUDE_PARAMETER_LIST=""
for EXCLUDE_FILE in $(find "${DOTFILES_PATH}/data/home-backup-exclude/" ! -type d); do
RSYNC_EXCLUDE_PARAMETER_LIST="${RSYNC_EXCLUDE_PARAMETER_LIST} --exclude-from=${EXCLUDE_FILE}"
done
echo "${RSYNC_EXCLUDE_PARAMETER_LIST}"
}
|
<gh_stars>1-10
module PoolParty
module CloudDsl
def mount_ebs_volume_at(id="", loc="/data")
ebs_volume_id id
ebs_volume_mount_point loc
ebs_volume_device "/dev/#{id.sanitize}"
has_mount(:name => loc, :device => ebs_volume_device)
has_directory(:name => loc)
end
end
end
|
#!/usr/bin/env bash
ANDROID_SDK=/Users/lmy/Library/Android/sdk
ANDROID_NDK=/Users/lmy/Library/Android/android-ndk-r14b
build() {
ARCH=$1
ABI=
if [[ "$ARCH" = "armv7a" ]]; then
echo "+--------------------------+"
echo "|----webp build armv7a-----|"
echo "+--------------------------+"
ABI="armeabi-v7a"
elif [[ "$ARCH" = "arm64" ]]; then
echo "+--------------------------+"
echo "|----webp build arm64 -----|"
echo "+--------------------------+"
ABI="arm64-v8a"
elif [[ "$ARCH" = "x86" ]]; then
echo "+--------------------------+"
echo "|---- webp build x86 -----|"
echo "+--------------------------+"
ABI="x86"
else
echo "Need a arch param"
exit 1
fi
${ANDROID_SDK}/cmake/3.6.4111459/bin/cmake -G"Unix Makefiles" -DCMAKE_TOOLCHAIN_FILE=${ANDROID_NDK}/build/cmake/android.toolchain.cmake \
-DANDROID_ABI=${ABI} \
-DCMAKE_LIBRARY_OUTPUT_DIRECTORY="./product/${ABI}" \
-DCMAKE_BUILD_TYPE="Release" \
-DANDROID_PLATFORM="android-21" \
-DANDROID_TOOLCHAIN="clang" \
-DWEBP_ENABLE_SIMD="ON" \
-DWEBP_BUILD_ANIM_UTILS="OFF" \
-DWEBP_BUILD_CWEBP="OFF" \
-DWEBP_BUILD_DWEBP="OFF" \
-DWEBP_BUILD_GIF2WEBP="OFF" \
-DWEBP_BUILD_IMG2WEBP="OFF" \
-DWEBP_BUILD_VWEBP="OFF" \
-DWEBP_BUILD_WEBPINFO="OFF" \
-DWEBP_BUILD_WEBPMUX="OFF" \
-DWEBP_BUILD_EXTRAS="OFF" \
-DWEBP_BUILD_WEBP_JS="OFF" \
-DWEBP_ENABLE_SWAP_16BIT_CSP="OFF" \
-DWEBP_ENABLE_SWAP_16BIT_CSP="OFF"
make -j4
}
build $1
|
#!/bin/bash
source activate structural_edits
export CUDA_VISIBLE_DEVICES=0
export PYTHONPATH=/scratch/yao.470/CMU_project/incremental_tree_edit:$PYTHONPATH
config_file=$1
work_dir=exp_githubedits_runs/FOLDER_OF_MODEL # TODO: replace FOLDER_OF_MODEL with your model dir
echo use config file ${config_file}
echo work dir=${work_dir}
mkdir -p ${work_dir}
# TODO: uncomment the test setting
# beam search
#test_file=source_data/githubedits/githubedits.test.jsonl
#OMP_NUM_THREADS=1 python -m exp_githubedits decode_updated_data \
# --cuda \
# --beam_size=1 \
# --evaluate_ppl \
# ${work_dir}/model.bin \
# ${test_file} 2>${work_dir}/model.bin.${filename}_test.log # dev_debug, dev, test, train_debug
# test ppl
#OMP_NUM_THREADS=1 python -m exp_githubedits test_ppl \
# --cuda \
# --evaluate_ppl \
# ${work_dir}/model.bin \
# ${test_file} #2>${work_dir}/model.bin.decode_ppl.log
## csharp_fixer
#test_file=source_data/githubedits/csharp_fixers.jsonl
#scorer='default'
#OMP_NUM_THREADS=1 python -m exp_githubedits eval_csharp_fixer \
# --cuda \
# --beam_size=1 \
# --scorer=${scorer} \
# ${work_dir}/model.bin \
# ${test_file} 2>${work_dir}/model.bin.${filename}_csharp_fixer_${scorer}.log
## beam search on csharp_fixer with gold inputs
#test_file=source_data/githubedits/csharp_fixers.jsonl
#OMP_NUM_THREADS=1 python -m exp_githubedits decode_updated_data \
# --cuda \
# --beam_size=1 \
# ${work_dir}/model.bin \
# ${test_file} 2>${work_dir}/model.bin.${filename}_csharp_fixer_gold.log
# collect edit vecs
##test_file=source_data/githubedits/csharp_fixers.jsonl
#test_file=source_data/githubedits/githubedits.test.jsonl
#OMP_NUM_THREADS=1 python -m exp_githubedits collect_edit_vecs \
# --cuda \
# ${work_dir}/model.bin \
# ${test_file}
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNativeStackInspector
* @flow
*/
'use strict';
const ReactNativeComponentTree = require('ReactNativeComponentTree');
const getComponentName = require('getComponentName');
const emptyObject = require('fbjs/lib/emptyObject');
const UIManager = require('UIManager');
const invariant = require('fbjs/lib/invariant');
let getInspectorDataForViewTag;
if (__DEV__) {
var traverseOwnerTreeUp = function(hierarchy, instance) {
if (instance) {
hierarchy.unshift(instance);
traverseOwnerTreeUp(hierarchy, instance._currentElement._owner);
}
};
var getOwnerHierarchy = function(instance) {
var hierarchy = [];
traverseOwnerTreeUp(hierarchy, instance);
return hierarchy;
};
var lastNotNativeInstance = function(hierarchy) {
for (let i = hierarchy.length - 1; i > 1; i--) {
const instance = hierarchy[i];
if (!instance.viewConfig) {
return instance;
}
}
return hierarchy[0];
};
var getHostProps = function(component) {
const instance = component._instance;
if (instance) {
return instance.props || emptyObject;
}
return emptyObject;
};
var createHierarchy = function(componentHierarchy) {
return componentHierarchy.map(component => ({
name: getComponentName(component),
getInspectorData: () => ({
measure: callback =>
UIManager.measure(component.getHostNode(), callback),
props: getHostProps(component),
source: component._currentElement && component._currentElement._source,
}),
}));
};
getInspectorDataForViewTag = function(viewTag: any): Object {
const component = ReactNativeComponentTree.getClosestInstanceFromNode(
viewTag,
);
const componentHierarchy = getOwnerHierarchy(component);
const instance = lastNotNativeInstance(componentHierarchy);
const hierarchy = createHierarchy(componentHierarchy);
const props = getHostProps(instance);
const source = instance._currentElement && instance._currentElement._source;
const selection = componentHierarchy.indexOf(instance);
return {
hierarchy,
props,
selection,
source,
};
};
} else {
getInspectorDataForViewTag = () => {
invariant(
false,
'getInspectorDataForViewTag() is not available in production',
);
};
}
module.exports = {
getInspectorDataForViewTag,
};
|
<reponame>greggman/other-window-ipc<gh_stars>1-10
"use strict";
const otherWindowIPC = require('../other-window-ipc');
const log = require('./log');
process.on('uncaughtException', (err) => {
log(err);
log(err.stack);
});
const channel = otherWindowIPC.createChannel("blarg");
channel.on('connect', stream => {
stream.on('hello', data => {
log("got hello:", data);
stream.send('hello', 'got:' + data + " send it back");
});
stream.on('disconnect', () => {
log("disconnected");
});
});
|
function formatToCurrency(num) {
let stringNum = String(num);
let len = stringNum.length;
let outputStr = '';
let count = 0;
for(let i = len - 1; i >= 0; i--) {
outputStr = stringNum[i] + outputStr;
count++;
if(count % 3 == 0 && i != 0) {
outputStr = '.' + outputStr;
}
}
return outputStr;
}
let number = 7283;
let formattedNumber = formatToCurrency(number);
console.log(formattedNumber); // prints 7.283
|
import React, {Component} from 'react';
import '../../App.css';
import '../404/404Page.css';
class FourFourErrorPage extends Component {
render() {
return (
<div id= 'fourfourError'>
<h1 id= 'fourfourErrorText' className= "font-weight-bold align-middle text-center">Error 404 - Page Not Found</h1>
<p id= "transitionToHome" className= "align-middle text-center font-weight-bold"><a className= "btn btn-light" href= "#/home">Home</a></p>
</div>
);
}
}
export default FourFourErrorPage;
|
<filename>examples/ble_simpletest.py
"""
This example scans for any BLE advertisements and prints one advertisement and one scan response
from every device found.
"""
from adafruit_ble import BLERadio
ble = BLERadio()
print("scanning")
found = set()
scan_responses = set()
for advertisement in ble.start_scan():
addr = advertisement.address
if advertisement.scan_response and addr not in scan_responses:
scan_responses.add(addr)
elif not advertisement.scan_response and addr not in found:
found.add(addr)
else:
continue
print(addr, advertisement)
print("\t" + repr(advertisement))
print()
print("scan done")
|
import pigpio
#sudo pigpiod
from time import sleep
pi = pigpio.pi() #먼저 사용할 pigpio.pi를 매칭해줍니다.
while True:
pi.set_servo_pulsewidth(17, 0) #18번 채널에연결된 서보모터를 꺼줍니다.
pi.set_servo_pulsewidth(18, 0)
pi.set_servo_pulsewidth(27, 0)
sleep(1)
pi.set_servo_pulsewidth(17, 1500) # 가운데로 이동 90도
pi.set_servo_pulsewidth(18, 1500)
pi.set_servo_pulsewidth(27, 1500)
sleep(1)
|
<filename>open-sphere-base/analysis/src/main/java/io/opensphere/analysis/table/renderers/TimeSpanTableCellRenderer.java
package io.opensphere.analysis.table.renderers;
import java.awt.Component;
import java.text.SimpleDateFormat;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import io.opensphere.core.model.time.TimeSpan;
import io.opensphere.core.preferences.ListToolPreferences;
import io.opensphere.mantle.util.TimeSpanUtility;
/**
* TimeSpan table cell renderer.
*/
public class TimeSpanTableCellRenderer extends DefaultTableCellRenderer
{
/** The serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The format. */
private final SimpleDateFormat myFormat;
/**
* Constructor.
*
* @param precision the precision
*/
public TimeSpanTableCellRenderer(int precision)
{
super();
myFormat = ListToolPreferences.getSimpleDateFormatForPrecision(precision);
setVerticalAlignment(DefaultTableCellRenderer.TOP);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
int column)
{
return super.getTableCellRendererComponent(table, TimeSpanUtility.formatTimeSpan(myFormat, (TimeSpan)value), isSelected,
hasFocus, row, column);
}
}
|
package org.jaudiotagger.tag.id3;
import org.jaudiotagger.AbstractTestCase;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM;
import java.io.File;
/**
* Test POPMFrameBody
*/
public class FrameCOMMTest extends AbstractTestCase
{
/**
* Should run without throwing Runtime excception, although COMMFrame wont be loaded and will
* throwe invalid size exception
*/
public void testReadFileContainingInvalidSizeCOMMFrame() throws Exception
{
Exception e = null;
try
{
File testFile = AbstractTestCase.copyAudioToTmp("Issue77.id3", "testV1.mp3");
MP3File mp3File = new MP3File(testFile);
}
catch (Exception ie)
{
e = ie;
}
assertNull(e);
}
/**
* Should run without throwing Runtime excception, although COMMFrame wont be loaded and will
* throwe invalid datatype exception
*/
public void testReadFileContainingInvalidTextEncodingCOMMFrame() throws Exception
{
Exception e = null;
try
{
File testFile = AbstractTestCase.copyAudioToTmp("Issue80.id3", "testV1.mp3");
MP3File mp3File = new MP3File(testFile);
}
catch (Exception ie)
{
e = ie;
}
assertNull(e);
}
/**
* Can read file containing a language code that does not actually map to a code , and write it back
* In this real example the language code has been held as three space characters
*/
public void testreadFrameContainingInvalidlanguageCodeCOMMFrame() throws Exception
{
final String INVALID_LANG_CODE = " ";
Exception e = null;
try
{
File testFile = AbstractTestCase.copyAudioToTmp("Issue108.id3", "testV1.mp3");
MP3File mp3File = new MP3File(testFile);
assertTrue(mp3File.getID3v2Tag().hasFrame("COMM"));
ID3v24Frame commFrame = (ID3v24Frame) mp3File.getID3v2Tag().getFrame("COMM");
FrameBodyCOMM frameBody = (FrameBodyCOMM) commFrame.getBody();
assertEquals(INVALID_LANG_CODE, frameBody.getLanguage());
}
catch (Exception ie)
{
ie.printStackTrace();
e = ie;
}
assertNull(e);
}
/**
* Can write file containing a COMM Frame with null language code
*/
public void testsaveFileContainingNullLanguageCodeCOMMFrame() throws Exception
{
final String SAFE_LANG_CODE = " ";
final String SAFE_LONGER_LANG_CODE = "aa ";
final String SAFE_SHORTER_LANG_CODE = "aaa";
Exception e = null;
try
{
//Read tag
File testFile = AbstractTestCase.copyAudioToTmp("Issue108.id3", "testV1.mp3");
MP3File mp3File = new MP3File(testFile);
ID3v24Frame commFrame = (ID3v24Frame) mp3File.getID3v2Tag().getFrame("COMM");
FrameBodyCOMM frameBody = (FrameBodyCOMM) commFrame.getBody();
//Set language to null, this is common problem for new frames might null lang codes
frameBody.setLanguage(null);
mp3File.save();
mp3File = new MP3File(testFile);
commFrame = (ID3v24Frame) mp3File.getID3v2Tag().getFrame("COMM");
frameBody = (FrameBodyCOMM) commFrame.getBody();
assertEquals(SAFE_LANG_CODE, frameBody.getLanguage());
//Set language to too short a value
frameBody.setLanguage("aa");
mp3File.save();
mp3File = new MP3File(testFile);
commFrame = (ID3v24Frame) mp3File.getID3v2Tag().getFrame("COMM");
frameBody = (FrameBodyCOMM) commFrame.getBody();
assertEquals(SAFE_LONGER_LANG_CODE, frameBody.getLanguage());
//Set language to too long a value
frameBody.setLanguage("aaaaaaa");
mp3File.save();
mp3File = new MP3File(testFile);
commFrame = (ID3v24Frame) mp3File.getID3v2Tag().getFrame("COMM");
frameBody = (FrameBodyCOMM) commFrame.getBody();
assertEquals(SAFE_SHORTER_LANG_CODE, frameBody.getLanguage());
}
catch (Exception ie)
{
ie.printStackTrace();
e = ie;
}
assertNull(e);
}
}
|
package com.udacity.jdnd.course3.critter.controller;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.net.URI;
import java.net.URISyntaxException;
import static org.junit.jupiter.api.Assertions.fail;
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public abstract class AbstractContextTest extends AbstractTest {
@LocalServerPort
private Integer port;
@BeforeAll
public static void beforeAll() {
AbstractTest.beforeAll();
}
@AfterAll
public static void afterAll() {
AbstractTest.afterAll();
}
protected String getLocalhostUrl(String path,
String query,
String fragment) {
URI uri = null;
try {
uri = new URI("http", null, "localhost", port, path, query, fragment);
} catch (URISyntaxException e) {
e.printStackTrace();
fail();
}
return uri.toString();
}
protected String getLocalhostUrl(String path) {
return getLocalhostUrl(path, null, null);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.