text stringlengths 1 1.05M |
|---|
<filename>bin/obj/src/cli_kb4.c
/* **** Notes
Output characters in UTF-8.
Remarks:
Based on UTF-8
*/
# define CBR
# include <conio.h>
# include <stdio.h>
# include <stdlib.h>
# include <windows.h>
# include "../../../lib/incl/config.h"
signed(__cdecl main(signed(argc),signed char(**argv))) {
/* **** DATA, BSS and STACK */
auto signed char *b;
auto cli_property_t property;
auto signed i,r;
auto signed short flag;
/* **** CODE/TEXT */
system("cls");
printf("\n");
printf(" %s \n","Currently under construction");
/* Currently under construction..
r = cli_init_property(0x00,&property);
if(!r) {
printf("%s \n","<< Error at fn. cli_init_property()");
return(0x00);
}
// to monitor
if(0x01<(argc)) OR(*(CLI_BASE+(R(flag,property))),CLI_MONITOR);
// announce
cputs("Please type the <Enter> key to stop. \n\n");
AND(flag,0x00);
r = cli_vt_opt(&property);
if(!r) {
printf("%s \n","<< Error at fn. cli_vt_opt()");
flag++;
// return(0x00);
}
cputs(" \n\n");
if(!flag) {
cputs("Based on UTF-8: \n");
b = (*(CLI_BASE+(R(b,*(CLI_BASE+(R(rule,R(text,property))))))));
if(!b) return(0x00);
r = cli_coord_outs(R(align,R(text,property)),b);
cputs(" \n\n");
printf("[%d %s] \n",ct_words(*(CLI_BASE+(R(sym,R(text,property)))),b),"words");
printf("[%d %s] \n",ct_letters(b),"letters");
printf("[%d %s] \n",ct_characters(b),"characters");
printf("[%d %s] \n",r,"bytes");
}
r = cli_init_property(0x01,&property);
if(!r) {
printf("%s \n","<< Error at fn. cli_init_property()");
return(0x00);
}
// check
AND(i,0x00);
OR(i,CLI_OBJS);
while(i) if(*(CLI_BASE+(R(b,*(--i+(R(rule,R(text,property)))))))) return(0x00);
cputs(" \n");
if(!flag) printf("%s \n","Done!");
else printf("%s \n","Oops!");
//*/
return(0x00);
}
|
polybar --list-monitors
echo "Please type in the name of the monitor you want the bar to appear on:"
read monitor
touch ~/.config/polybar/monitor
echo $monitor > ~/.config/polybar/monitor |
#!/usr/bin/env bash
# fail on any command exiting non-zero
set -eo pipefail
if [[ -z $DOCKER_BUILD ]]; then
echo
echo "Note: this script is intended for use by the Dockerfile and not as a way to build the controller locally"
echo
exit 1
fi
DEBIAN_FRONTEND=noninteractive
# install required system packages
# HACK: install git so we can install bacongobbler's fork of django-fsm
# install openssh-client for temporary fleetctl wrapper
apt-get update && \
apt-get install -yq python-dev libffi-dev libpq-dev libyaml-dev git libldap2-dev libsasl2-dev
# install pip
curl -sSL https://raw.githubusercontent.com/pypa/pip/6.1.1/contrib/get-pip.py | python -
# add a deis user
useradd deis --home-dir /app --shell /bin/bash
# create a /app directory for storing application data
mkdir -p /app && chown -R deis:deis /app
# create directory for confd templates
mkdir -p /templates && chown -R deis:deis /templates
# install dependencies
pip install -r /app/requirements.txt
# cleanup. indicate that python, libpq and libyanl are required packages.
apt-mark unmarkauto python python-openssl libpq5 libpython2.7 libffi6 libyaml-0-2 && \
apt-get remove -y --purge python-dev gcc cpp libffi-dev libpq-dev libyaml-dev git && \
apt-get autoremove -y --purge && \
apt-get clean -y && \
rm -Rf /usr/share/man /usr/share/doc && \
rm -rf /tmp/* /var/tmp/* && \
rm -rf /var/lib/apt/lists/*
|
import Foundation
/// A wrapper that fires a listener when the value changes. Acts similar to the 'CurrentValueSubject' of Apple's Combine framework API.
public final class ReactiveVarBox<T> {
// MARK: Typealiases
internal typealias Listener = (T) -> Void
// MARK: Internal IVars
internal var value: T {
didSet {
self.listener?(self.value)
}
}
internal var listener: Listener?
/// Binds the given closure as the listener for value changes.
public func bind(_ listener: @escaping Listener) {
self.listener = listener
}
} |
<filename>src/script/type.ts
import { writeFileSync } from 'fs'
import { readJSONSync } from 'fs-extra'
import * as glob from 'glob'
import { PATH_SRC_SYSTEM } from '../path'
import { removeLastSegment } from '../removeLastSegment'
import { _getSpecTypeInterface } from '../spec/type'
import _specs from '../system/_specs'
const cwd = PATH_SRC_SYSTEM
let count = 0
glob
.sync(`**/**/spec.json`, {
cwd,
})
.map((path) => removeLastSegment(path))
.forEach((_) => {
const spec_file_path = `${cwd}/${_}/spec.json`
const spec = readJSONSync(spec_file_path)
const segments = _.split('/')
const l = segments.length
const tags = segments.slice(0, l - 1)
spec.metadata = spec.metadata || {}
spec.metadata.tags = tags
const { id, inputs = {}, outputs = {} } = spec
const typeInterface = _getSpecTypeInterface(spec, _specs)
for (const input_name in inputs) {
const input = inputs[input_name]
const { type } = input
if (!type) {
const _type = typeInterface['input'][input_name].value
console.log(_, 'input', input_name, _type)
spec.inputs[input_name].type = _type
count++
}
}
for (const output_name in outputs) {
const output = outputs[output_name]
const { type } = output
if (!type) {
const _type = typeInterface['output'][output_name].value
console.log(_, 'output', output_name, _type)
spec.outputs[output_name].type = _type
count++
}
}
writeFileSync(spec_file_path, JSON.stringify(spec, null, 2))
})
console.log(count)
|
<gh_stars>1-10
package com.chess.rathma;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Scaling;
import com.chess.rathma.Packets.MovePacket;
import com.chess.rathma.Packets.SurrenderPacket;
import com.chess.rathma.Screens.GameScreen;
/**
* This will be the sidebar on the sides of games. Showing every move made, it'll hold a forfeit & draw icon and piece buffers.
* Features to add -
* Timer for both sides
* Player names & connectivity icons
* Elo/rating indicator
* Piece buffer for both player 1 & 2
*/
public class Sidebar extends WidgetGroup {
private Skin skin;
public GameScreen gameScreen;
public GameRoom gameRoom;
private TextureAtlas atlas = new TextureAtlas(Gdx.files.internal("sidebar.atlas"));
/* Containers */
private Table table;
private ScrollPane movePane;
private Table moveList;
public Sidebar(final GameScreen gameScreen, Skin skin)
{
this.skin = skin;
this.gameScreen = gameScreen;
this.gameRoom = gameScreen.gameRoom;
/* Let's initialise everything */
table = new Table(skin);
moveList = new Table(skin); // Using a table so we can add images & stuff :)
movePane = new ScrollPane(moveList);
/* Set up our primary table */
table.setFillParent(true);
table.align(Align.topLeft);
table.setBackground(skin.getDrawable("default-round-large"));
/* Set up our move table */
movePane.setScrollingDisabled(true,false);
moveList.setBackground(skin.getDrawable("default-scroll"));
Label player1 = new Label(gameRoom.player1,skin);
Label player2 = new Label(gameRoom.player2,skin);
/* Let's get some icons */
Image player1Icon = new Image(atlas.findRegion("player"));
player1Icon.setColor(0,1,0,1);
Image player2Icon = new Image(atlas.findRegion("player"));
player2Icon.setColor(0,1,0,1);
/* This is too convoluted */
Image surrender = new Image(atlas.findRegion("flag"));
surrender.setSize(24,24);
surrender.addListener(new ImageListener(gameRoom.chess) {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
gameRoom.chess.network.sendTCP(new SurrenderPacket(gameRoom.gameID,gameRoom.chess.userID));
}
});
Image home = new Image(atlas.findRegion("home"));
home.setSize(24,24);
home.addListener(new ImageListener(gameScreen.chess){
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
gameScreen.menuSwitch=true;
}
});
/* Organisation of our icon group */
// table.setDebug(true);
/* Organisation of primary table */
table.add(player2Icon).align(Align.topLeft)
.maxHeight(24)
.maxWidth(24);
table.add(player2)
.align(Align.left)
.expandX();
table.row();
table.add(movePane)
.fill(true)
.expandY()
.expandX()
.colspan(2)
.prefWidth(table.getWidth())
.maxWidth(table.getWidth())
.minHeight(200)
.maxHeight(200);
table.row();
table.add(home)
.align(Align.left)
.maxHeight(24)
.maxWidth(24);
table.add(surrender)
.align(Align.left)
.maxHeight(24)
.maxWidth(24);
table.row();
table.add(player1Icon)
.align(Align.topLeft)
.maxHeight(24)
.maxWidth(24);
table.add(player1)
.align(Align.left)
.expandX();
this.addActor(table);
loadMoves();
}
/* We'll call this once the game is over so we can rearrange things */
public void gameEnd(String gameEnd)
{
table.clear();
Label player1 = new Label(gameRoom.player1,skin);
Label player2 = new Label(gameRoom.player2,skin);
/* Let's get some icons */
Image player1Icon = new Image(atlas.findRegion("player"));
player1Icon.setColor(0,1,0,1);
Image player2Icon = new Image(atlas.findRegion("player"));
player2Icon.setColor(0,1,0,1);
/* This is too convoluted */
Image surrender = new Image(atlas.findRegion("flag"));
surrender.setSize(24,24);
surrender.setColor(Color.GRAY);
Label endGameLabel = new Label(gameEnd,skin);
endGameLabel.setWrap(true);
Image home = new Image(atlas.findRegion("home"));
home.setSize(24,24);
home.addListener(new ImageListener(gameRoom.chess){
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
gameRoom.state = GameRoom.GameState.DESTROY;
}
});
/* Organisation of our icon group */
// table.setDebug(true);
/* Organisation of primary table */
table.add(player2Icon).align(Align.topLeft)
.maxHeight(24)
.maxWidth(24);
table.add(player2)
.align(Align.left)
.expandX();
table.row();
table.add(movePane)
.fill(true)
.expandY()
.expandX()
.colspan(2)
.prefWidth(table.getWidth())
.maxWidth(table.getWidth())
.minHeight(200)
.maxHeight(200);
table.row();
table.add(home)
.align(Align.left)
.maxHeight(24)
.maxWidth(24);
table.add(surrender)
.align(Align.left)
.maxHeight(24)
.maxWidth(24);
table.row();
table.add(player1Icon)
.align(Align.topLeft)
.maxHeight(24)
.maxWidth(24);
table.add(player1)
.align(Align.left)
.expandX();
table.row();
table.add(endGameLabel).colspan(2)
.align(Align.left)
.expandX();
}
public void loadMoves()
{
if(gameRoom.moves!=null) {
for (MovePacket move : gameRoom.moves) {
addMove(move);
}
}
}
public void addMove(MovePacket m)
{
/* We need to change this to chess notation */
moveList.row().expandX().spaceTop(1);
Label move = new Label(m.toString(),skin);
move.setWrap(true);
moveList.add(move)
.align(Align.topLeft)
.prefWidth(movePane.getWidth())
.spaceTop(1).spaceBottom(1);
if(movePane.isScrollY())
{
movePane.layout();
movePane.setScrollY(movePane.getMaxY());
}
}
}
|
#!/bin/bash
python train.py --experiment_name DiffAugment-biggan-cifar10-0.1 --DiffAugment translation,cutout \
--mirror_augment --use_multiepoch_sampler \
--which_best FID --num_inception_images 10000 \
--shuffle --batch_size 50 --parallel \
--num_G_accumulations 1 --num_D_accumulations 1 --num_epochs 5000 --num_samples 5000 \
--num_D_steps 4 --G_lr 2e-4 --D_lr 2e-4 \
--dataset C10 \
--G_ortho 0.0 \
--G_attn 0 --D_attn 0 \
--G_init N02 --D_init N02 \
--ema --use_ema --ema_start 1000 \
--test_every 4000 --save_every 2000 --seed 0 |
package expo.modules.image;
import android.view.View;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.annotation.NonNull;
public class ExpoImageManager extends SimpleViewManager<View> {
private static final String REACT_CLASS = "ExpoImage";
@NonNull
@Override
public String getName() {
return REACT_CLASS;
}
@NonNull
@Override
public View createViewInstance(@NonNull ThemedReactContext context) {
// TODO: Implement some actually useful functionality
AppCompatCheckBox cb = new AppCompatCheckBox(c);
cb.setChecked(true);
return cb;
}
}
|
<reponame>dwgill/initiate
import React, { PureComponent } from "react";
import styles from "./NumberField.module.scss";
import PropTypes from "prop-types";
import computeDynamicNumber from "../../../logic/computeDynamicNumber";
import AutosizeInput from "react-input-autosize";
import cls from "classnames";
import delay from "lodash/fp/delay";
import { flashDurationMilliseconds } from "../../../logic/flashDuration";
import existy from "../../../logic/existy";
class NumberField extends PureComponent {
static propTypes = {
value: PropTypes.number,
label: PropTypes.string.isRequired,
onChange: PropTypes.func,
className: PropTypes.string
};
constructor(props) {
super(props);
this.state = {
hasFocus: false,
value: "",
isFlashing: false
};
this.inputRef = React.createRef();
}
static getDerivedStateFromProps(props, state) {
const { value } = props;
if (!state.hasFocus) {
return {
value: !value && value !== 0 ? "" : String(value)
};
}
return null;
}
flash() {
this.setState({ isFlashing: true }, () => {
delay(flashDurationMilliseconds, () =>
this.setState({ isFlashing: false })
);
});
}
handleFocus = (event, shouldSelect = true) => {
if (!this.state.hasFocus) {
this.setState({ hasFocus: true });
if (this.inputRef.current) {
this.inputRef.current.focus();
if (shouldSelect) {
this.inputRef.current.select();
}
}
}
};
handleBlur = event => {
this.setState({ hasFocus: false });
const { onChange, value: propsValue } = this.props;
const { value } = this.state;
if (String(propsValue || "") === value || !onChange) {
return;
}
if (!existy(value)) {
onChange(null);
return;
}
if (value === '') {
onChange('');
return;
}
try {
const [newValue, wasDynamic] = computeDynamicNumber(propsValue, value);
onChange(newValue);
if (wasDynamic) {
this.flash();
}
} catch (e) {}
};
handleChange = event => {
if (!this.state.hasFocus) {
this.handleFocus(event, false);
}
const newValue = event.target.value;
this.setState({ value: !newValue ? "" : String(newValue) });
};
handleKeyDown = event => {
if (event.key === "Enter") {
this.handleBlur(event);
}
};
render() {
const { value, hasFocus, isFlashing } = this.state;
const { label, className } = this.props;
const placeholder = hasFocus ? "" : "N/A";
return (
<span
className={cls(styles.field, className, { [styles.flash]: isFlashing })}
onClick={this.handleFocus}
>
<label className={styles.label}>
{label}
<AutosizeInput
inputClassName={styles.fieldInput}
onBlur={this.handleBlur}
onChange={this.handleChange}
onFocus={this.handleFocus}
onKeyDown={this.handleKeyDown}
placeholder={placeholder}
ref={this.inputRef}
value={value}
/>
</label>
</span>
);
}
}
export default NumberField;
|
<reponame>JeongsooHa/ray
import logging
from ray.rllib.utils.framework import try_import_torch
torch, nn = try_import_torch()
logger = logging.getLogger(__name__)
def make_time_major(policy, seq_lens, tensor, drop_last=False):
"""Swaps batch and trajectory axis.
Arguments:
policy: Policy reference
seq_lens: Sequence lengths if recurrent or None
tensor: A tensor or list of tensors to reshape.
drop_last: A bool indicating whether to drop the last
trajectory item.
Returns:
res: A tensor with swapped axes or a list of tensors with
swapped axes.
"""
if isinstance(tensor, (list, tuple)):
return [
make_time_major(policy, seq_lens, t, drop_last) for t in tensor
]
if policy.is_recurrent():
B = seq_lens.shape[0]
T = tensor.shape[0] // B
else:
# Important: chop the tensor into batches at known episode cut
# boundaries. TODO(ekl) this is kind of a hack
T = policy.config["rollout_fragment_length"]
B = tensor.shape[0] // T
rs = torch.reshape(tensor, [B, T] + list(tensor.shape[1:]))
# Swap B and T axes.
res = torch.transpose(rs, 1, 0)
if drop_last:
return res[:-1]
return res
def choose_optimizer(policy, config):
if policy.config["opt_type"] == "adam":
return torch.optim.Adam(
params=policy.model.parameters(), lr=policy.cur_lr)
else:
return torch.optim.RMSProp(
params=policy.model.parameters(),
lr=policy.cur_lr,
weight_decay=config["decay"],
momentum=config["momentum"],
eps=config["epsilon"])
|
<gh_stars>1-10
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// CollectionsColumns holds the columns for the "collections" table.
CollectionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "lifespan_start_at", Type: field.TypeTime, Nullable: true},
{Name: "lifespan_end_at", Type: field.TypeTime, Nullable: true},
}
// CollectionsTable holds the schema information for the "collections" table.
CollectionsTable = &schema.Table{
Name: "collections",
Columns: CollectionsColumns,
PrimaryKey: []*schema.Column{CollectionsColumns[0]},
}
// DocumentsColumns holds the columns for the "documents" table.
DocumentsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "activation", Type: field.TypeEnum, Enums: []string{"ACTIVATED", "DEACTIVATED"}, Default: "ACTIVATED"},
{Name: "lifespan_start_at", Type: field.TypeTime, Nullable: true},
{Name: "lifespan_end_at", Type: field.TypeTime, Nullable: true},
{Name: "deleted_at", Type: field.TypeTime, Nullable: true},
}
// DocumentsTable holds the schema information for the "documents" table.
DocumentsTable = &schema.Table{
Name: "documents",
Columns: DocumentsColumns,
PrimaryKey: []*schema.Column{DocumentsColumns[0]},
Indexes: []*schema.Index{
{
Name: "document_deleted_at",
Unique: false,
Columns: []*schema.Column{DocumentsColumns[4]},
},
},
}
// RevisionsColumns holds the columns for the "revisions" table.
RevisionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "lifespan_start_at", Type: field.TypeTime, Nullable: true},
{Name: "lifespan_end_at", Type: field.TypeTime, Nullable: true},
}
// RevisionsTable holds the schema information for the "revisions" table.
RevisionsTable = &schema.Table{
Name: "revisions",
Columns: RevisionsColumns,
PrimaryKey: []*schema.Column{RevisionsColumns[0]},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
CollectionsTable,
DocumentsTable,
RevisionsTable,
}
)
func init() {
}
|
import math
rootDir = '/path/to/your/root/directory/' # Replace with the actual root directory path
try:
with open(rootDir + 'output/star_list/stars.csv', 'r') as fp:
for line in fp:
star_data = line.strip().split(',')
if len(star_data) == 3:
star_name, distance, apparent_magnitude = star_data
try:
distance = float(distance)
apparent_magnitude = float(apparent_magnitude)
absolute_magnitude = apparent_magnitude - 5 * math.log10(distance) + 5
print(f"The absolute magnitude of {star_name} is {absolute_magnitude:.2f}")
except ValueError:
print(f"Invalid data format for star: {star_name}")
except ZeroDivisionError:
print(f"Distance for star {star_name} cannot be zero")
else:
print(f"Invalid data format in line: {line}")
except FileNotFoundError:
print("File not found")
except IOError:
print("Error reading the file")
except Exception as e:
print(f"An error occurred: {e}") |
<filename>app/controllers/concerns/session_helpers.rb
module SessionHelpers
extend ActiveSupport::Concern
included do
def pundit_user
current_membership
end
def current_user
@current_user ||= current_membership.try(:user)
end
def current_organisation
@current_organisation ||= current_membership.organisation
end
def current_membership
@current_membership ||= session_membership || api_membership
end
def api_membership
EasyTokens::Token.find_by(value: params[:api_key], deactivated_at: nil).try(:owner)
end
def session_membership
Membership.find_by(id: env['rack.session'][:membership_id])
end
end
end
|
package com.mrh0.createaddition.blocks.charger;
/*
import java.util.List;
import com.mrh0.createaddition.CreateAddition;
import com.mrh0.createaddition.config.Config;
import com.mrh0.createaddition.energy.BaseElectricTileEntity;
import com.mrh0.createaddition.index.CABlocks;
import com.mrh0.createaddition.index.CAItems;
import com.mrh0.createaddition.item.ChargingChromaticCompound;
import com.mrh0.createaddition.util.IComparatorOverride;
import com.simibubi.create.AllItems;
import com.simibubi.create.content.contraptions.goggles.IHaveGoggleInformation;
import net.minecraft.block.BlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntityType;
import net.minecraft.util.Direction;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
public class ChargerTileEntity extends BaseElectricTileEntity implements IComparatorOverride, IHaveGoggleInformation {
private ItemStack itemStack = ItemStack.EMPTY;
private static final int MAX_IN = Config.CHARGER_MAX_INPUT.get(), CHARGE_RATE = Config.CHARGER_CHARGE_RATE.get(),
CAPACITY = Config.CHARGER_CAPACITY.get();
public ChargerTileEntity(TileEntityType<?> tileEntityTypeIn) {
super(tileEntityTypeIn, CAPACITY, MAX_IN, 0);
setLazyTickRate(20);
}
private void chargeItem(ItemStack stack) {
stack.getCapability(CapabilityEnergy.ENERGY).ifPresent(itemEnergy -> {
if (!isChargingItem(itemEnergy))
return;
int energyRemoved = itemEnergy.receiveEnergy(Math.min(energy.getEnergyStored(), CHARGE_RATE), false);
energy.internalConsumeEnergy(energyRemoved);
});
}
public boolean isChargingItem(IEnergyStorage energy) {
return energy.getEnergyStored() >= 0;
}
public float getItemCharge(IEnergyStorage energy) {
if (energy == null)
return 0f;
return (float) energy.getEnergyStored() / (float) energy.getMaxEnergyStored();
}
@Override
public boolean isEnergyInput(Direction side) {
return side != Direction.UP;
}
@Override
public boolean isEnergyOutput(Direction side) {
return false;
}
private int lastComparator = 0;
@Override
public void tick() {
super.tick();
if (level.isClientSide())
return;
if (hasChargedStack()) {
chargeItem(itemStack);
if (itemStack.getItem() == AllItems.CHROMATIC_COMPOUND.get()) {
setChargedStack(new ItemStack(CAItems.CHARGING_CHROMATIC_COMPOUND.get(), 1));
return;
}
if (itemStack.getItem() == CAItems.CHARGING_CHROMATIC_COMPOUND.get()) {
int energyRemoved = ChargingChromaticCompound.charge(itemStack,
Math.min(energy.getEnergyStored(), CHARGE_RATE));
energy.internalConsumeEnergy(energyRemoved);
if (ChargingChromaticCompound.getEnergy(itemStack) >= ChargingChromaticCompound.MAX_CHARGE) {
setChargedStack(new ItemStack(CAItems.OVERCHARGED_ALLOY.get(), 1));
}
return;
}
}
}
@Override
public void lazyTick() {
super.lazyTick();
int comp = getComparetorOverride();
if (comp != lastComparator)
level.updateNeighborsAt(worldPosition, CABlocks.CHARGER.get());
lastComparator = comp;
if (hasChargedStack())
causeBlockUpdate();
}
@Override
public void fromTag(BlockState state, CompoundNBT nbt, boolean clientPacket) {
super.fromTag(state, nbt, clientPacket);
itemStack = ItemStack.of(nbt.getCompound("item"));
if (itemStack == null)
itemStack = ItemStack.EMPTY;
}
@Override
public void write(CompoundNBT nbt, boolean clientPacket) {
super.write(nbt, clientPacket);
nbt.put("item", itemStack.save(new CompoundNBT()));
}
public void setChargedStack(ItemStack itemStack) {
if (itemStack == null)
itemStack = ItemStack.EMPTY;
this.itemStack = itemStack.copy();
this.itemStack.setCount(1);
level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), 0);
this.setChanged();
}
public ItemStack getChargedStack() {
return itemStack;
}
public boolean hasChargedStack() {
return itemStack != null && !this.itemStack.isEmpty();
}
@Override
public int getComparetorOverride() {
return (int) (getCharge() * 15f);
}
public float getCharge() {
if (!hasChargedStack())
return 0f;
if (itemStack.getCapability(CapabilityEnergy.ENERGY).isPresent())
return getItemCharge(itemStack.getCapability(CapabilityEnergy.ENERGY).orElse(null));
if (itemStack.getItem() == CAItems.CHARGING_CHROMATIC_COMPOUND.get())
return (float) ChargingChromaticCompound.getCharge(itemStack) * 90f;
if (itemStack.getItem() == CAItems.OVERCHARGED_ALLOY.get())
return 90f;
return 0f;
}
public String getChargeString() {
float c = Math.round(getCharge() * 100);
if(c >= 9000)
return "OVER9000% ";
return Math.round(getCharge() * 100) + "% ";
}
@Override
public boolean addToGoggleTooltip(List<ITextComponent> tooltip, boolean isPlayerSneaking) {
tooltip.add(new StringTextComponent(spacing).append(
new TranslationTextComponent("block.createaddition.charger.info").withStyle(TextFormatting.WHITE)));
if (hasChargedStack()) {
tooltip.add(new StringTextComponent(spacing).append(" ")
.append(new StringTextComponent(getChargeString()).withStyle(TextFormatting.AQUA))
.append(new TranslationTextComponent(CreateAddition.MODID + ".tooltip.energy.charged")
.withStyle(TextFormatting.GRAY)));
} else {
tooltip.add(new StringTextComponent(spacing).append(" ").append(
new TranslationTextComponent("block.createaddition.charger.empty").withStyle(TextFormatting.GRAY)));
}
return true;
}
}*/ |
#!/usr/bin/env bats
# Debugging
teardown() {
echo
# TODO: figure out how to deal with this (output from previous run commands showing up along with the error message)
echo "Note: ignore the lines between \"...failed\" above and here"
echo
echo "Status: ${status}"
echo "Output:"
echo "================================================================"
echo "${output}"
echo "================================================================"
}
# Checks container health status (if available)
# Relies on healchecks introduced in docksal/cli v1.3.0+, uses `sleep` as a fallback
# @param $1 container id/name
_healthcheck ()
{
local health_status
health_status=$(docker inspect --format='{{json .State.Health.Status}}' "$1" 2>/dev/null)
# Wait for 5s then exit with 0 if a container does not have a health status property
# Necessary for backward compatibility with images that do not support health checks
if [[ $? != 0 ]]; then
echo "Waiting 10s for container to start..."
sleep 10
return 0
fi
# If it does, check the status
echo ${health_status} | grep '"healthy"' >/dev/null 2>&1
}
# Waits for containers to become healthy
_healthcheck_wait ()
{
# Wait for cli to become ready by watching its health status
local container_name="${NAME}"
local delay=5
local timeout=30
local elapsed=0
until _healthcheck "$container_name"; do
echo "Waiting for $container_name to become ready..."
sleep ${delay};
# Give the container 30s to become ready
elapsed=$((elapsed + delay))
if ((elapsed > timeout)); then
echo "$container_name heathcheck failed"
exit 1
fi
done
return 0
}
# To work on a specific test:
# run `export SKIP=1` locally, then comment skip in the test you want to debug
@test "Essential binaries" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# List of binaries to check
binaries='\
cat \
convert \
curl \
dig \
g++ \
ghostscript \
git \
git-lfs \
gcc \
html2text \
jq \
less \
make \
mc \
more \
mysql \
nano \
nslookup \
ping \
psql \
pv \
rsync \
sudo \
unzip \
wget \
yq \
zip \
'
# Check all binaries in a single shot
run make exec -e CMD="type $(echo ${binaries} | xargs)"
[[ ${status} == 0 ]]
unset output
### Cleanup ###
make clean
}
@test "Bare service" {
[[ $SKIP == 1 ]] && skip
### Setup ###
docker rm -vf "$NAME" >/dev/null 2>&1 || true
docker run --name "$NAME" -d \
-v /home/docker \
-v $(pwd)/../tests/docroot:/var/www/docroot \
${IMAGE}:${BUILD_TAG}
docker cp $(pwd)/../tests/scripts "$NAME:/var/www/"
run _healthcheck_wait
unset output
### Tests ###
# Check PHP FPM and settings
# "sed -E 's/[[:space:]]{2,}/ => /g'" - makes the HTML phpinfo output easier to parse. It will transforms
# "memory_limit 256M 256M"
# into "memory_limit => 256M => 256M", which is much easier to parse
phpInfo=$(docker exec -u docker "$NAME" bash -c "/var/www/scripts/php-fpm.sh phpinfo.php | sed -E 's/[[:space:]]{2,}/ => /g'")
output=$(echo "$phpInfo" | grep "memory_limit")
echo "$output" | grep "256M => 256M"
unset output
output=$(echo "$phpInfo" | grep "sendmail_path")
echo "$output" | grep '/usr/bin/msmtp -t --host=mail --port=1025 => /usr/bin/msmtp -t --host=mail --port=1025'
unset output
run docker exec -u docker "$NAME" /var/www/scripts/php-fpm.sh nonsense.php
echo "$output" | grep "Status: 404 Not Found"
unset output
# Check PHP CLI and settings
phpInfo=$(docker exec -u docker "$NAME" php -i)
output=$(echo "$phpInfo" | grep "PHP Version")
echo "$output" | grep "${VERSION}"
unset output
# Confirm WebP support enabled for GD
output=$(echo "$phpInfo" | grep "WebP Support")
echo "$output" | grep "enabled"
unset output
output=$(echo "$phpInfo" | grep "memory_limit")
# grep expression cannot start with "-", so prepending the expression with "memory_limit" here.
# Another option is to do "grep -- '-...'".
echo "$output" | grep "memory_limit => -1 => -1"
unset output
output=$(echo "$phpInfo" | grep "sendmail_path")
echo "$output" | grep '/usr/bin/msmtp -t --host=mail --port=1025 => /usr/bin/msmtp -t --host=mail --port=1025'
unset output
# Check PHP modules
run bash -lc "docker exec -u docker '${NAME}' php -m | diff php-modules.txt -"
[[ ${status} == 0 ]]
unset output
### Cleanup ###
docker rm -vf "$NAME" >/dev/null 2>&1 || true
}
# Examples of using Makefile commands
# make start, make exec, make clean
@test "Configuration overrides" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start -e ENV='-e XDEBUG_ENABLED=1 -e XHPROF_ENABLED=1'
run _healthcheck_wait
unset output
### Tests ###
# Check PHP FPM settings overrides
run make exec -e CMD='/var/www/scripts/php-fpm.sh phpinfo.php'
echo "$output" | grep "memory_limit" | grep "512M"
unset output
# Check xdebug was enabled
run make exec -e CMD='php -m'
echo "$output" | grep -e "^xdebug$"
unset output
# Check xdebug was enabled
run make exec -e CMD='php -m'
echo "$output" | grep -e "^xhprof$"
unset output
# Check PHP CLI overrides
run make exec -e CMD='php -i'
echo "$output" | grep "memory_limit => 128M => 128M"
unset output
# Check Opcache Preload Enabled for 7.4
run make exec -e CMD='php -i'
if [[ "${VERSION}" == "7.4" ]]; then echo "$output" | grep "opcache.preload"; fi
unset output
### Cleanup ###
make clean
}
@test "Check PHP tools and versions" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# Check Composer v1 version (legacy)
run docker exec -u docker "$NAME" bash -lc 'set -x; composer1 --version | grep "^Composer version ${COMPOSER_VERSION} "'
[[ ${status} == 0 ]]
unset output
# Check Composer v2 version (default)
run docker exec -u docker "$NAME" bash -lc 'set -x; composer --version | grep "^Composer version ${COMPOSER2_VERSION} "'
[[ ${status} == 0 ]]
unset output
# Check Drush Launcher version
run docker exec -u docker "$NAME" bash -lc 'set -x; drush --version | grep "^Drush Launcher Version: ${DRUSH_LAUNCHER_VERSION}$"'
[[ ${status} == 0 ]]
unset output
# Check Drush version
run docker exec -u docker "$NAME" bash -lc 'set -x; drush --version | grep "^ Drush Version : ${DRUSH_VERSION} $"'
[[ ${status} == 0 ]]
unset output
# Check Drupal Console version
run docker exec -u docker "$NAME" bash -lc 'set -x; drupal --version | grep "^Drupal Console Launcher ${DRUPAL_CONSOLE_LAUNCHER_VERSION}$"'
[[ ${status} == 0 ]]
unset output
# Check Wordpress CLI version
run docker exec -u docker "$NAME" bash -lc 'set -x; wp --version | grep "^WP-CLI ${WPCLI_VERSION}$"'
[[ ${status} == 0 ]]
unset output
# Check Magento 2 Code Generator version
# TODO: this needs to be replaced with the actual version check
# See https://github.com/staempfli/magento2-code-generator/issues/15
#run docker exec -u docker "$NAME" bash -lc 'mg2-codegen --version | grep "^mg2-codegen ${MG_CODEGEN_VERSION}$"'
run docker exec -u docker "$NAME" bash -lc 'set -x; mg2-codegen --version | grep "^mg2-codegen @git-version@$"'
[[ ${status} == 0 ]]
unset output
# Check Terminus version
run docker exec -u docker "$NAME" bash -lc 'set -x; terminus --version | grep "^Terminus ${TERMINUS_VERSION}$"'
[[ ${status} == 0 ]]
unset output
# Check Platform CLI version
run docker exec -u docker "$NAME" bash -lc 'set -x; platform --version | grep "Platform.sh CLI ${PLATFORMSH_CLI_VERSION}"'
[[ ${status} == 0 ]]
unset output
# Check Acquia CLI version
run docker exec -u docker "$NAME" bash -lc 'set -x; acli --version | grep "^Acquia CLI ${ACQUIA_CLI_VERSION}$"'
[[ ${status} == 0 ]]
unset output
### Cleanup ###
make clean
}
@test "Check NodeJS tools and versions" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# nvm
run docker exec -u docker "$NAME" bash -lc 'nvm --version | grep "${NVM_VERSION}"'
[[ ${status} == 0 ]]
unset output
# nodejs
run docker exec -u docker "$NAME" bash -lc 'node --version | grep "${NODE_VERSION}"'
[[ ${status} == 0 ]]
unset output
# yarn
run docker exec -u docker "$NAME" bash -lc 'yarn --version | grep "${YARN_VERSION}"'
[[ ${status} == 0 ]]
unset output
### Cleanup ###
make clean
}
@test "Check Ruby tools and versions" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# rvm
run docker exec -u docker "$NAME" bash -lc 'rvm --version 2>&1 | grep "${RVM_VERSION_INSTALL}"'
[[ ${status} == 0 ]]
unset output
# ruby
run docker exec -u docker "$NAME" bash -lc 'ruby --version | grep "${RUBY_VERSION_INSTALL}"'
[[ ${status} == 0 ]]
unset output
### Cleanup ###
make clean
}
@test "Check Python tools and versions" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# pyenv
run docker exec -u docker "$NAME" bash -lc 'pyenv --version 2>&1 | grep "${PYENV_VERSION_INSTALL}"'
[[ ${status} == 0 ]]
unset output
# pyenv
run docker exec -u docker "$NAME" bash -lc 'python --version 2>&1 | grep "${PYTHON_VERSION_INSTALL}"'
[[ ${status} == 0 ]]
unset output
### Cleanup ###
make clean
}
@test "Check misc tools and versions" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# Check Blackfire CLI version
run docker exec -u docker "$NAME" bash -lc 'blackfire version | grep "^blackfire ${BLACKFIRE_VERSION} "'
[[ ${status} == 0 ]]
unset output
# Check msmtp
run docker exec -u docker "$NAME" which msmtp
echo "$output" | grep "/usr/bin/msmtp"
unset output
### Cleanup ###
make clean
}
@test "Check config templates" {
[[ $SKIP == 1 ]] && skip
# Source and allexport (set -a) variables from docksal.env
set -a; source $(pwd)/../tests/.docksal/docksal.env; set +a
# Config variables were loaded
[[ "${SECRET_SSH_PRIVATE_KEY}" != "" ]]
### Setup ###
make start -e ENV="-e SECRET_SSH_PRIVATE_KEY"
run _healthcheck_wait
unset output
### Tests ###
# Check private SSH key
run make exec -e CMD='echo ${SECRET_SSH_PRIVATE_KEY}'
[[ "${output}" != "" ]]
unset output
# TODO: figure out how to properly use 'make exec' here (escape quotes)
run docker exec -u docker "${NAME}" bash -lc 'echo "${SECRET_SSH_PRIVATE_KEY}" | base64 -d | diff ${HOME}/.ssh/id_rsa -'
[[ ${status} == 0 ]]
unset output
### Cleanup ###
make clean
}
@test "Check custom startup script" {
[[ $SKIP == 1 ]] && skip
make start
run _healthcheck_wait
unset output
run docker exec -u docker "${NAME}" cat /tmp/test-startup.txt
[[ ${status} == 0 ]]
[[ "${output}" =~ "I ran properly" ]]
### Cleanup ###
make clean
}
@test "Check Platform.sh integration" {
[[ $SKIP == 1 ]] && skip
# Confirm secret is not empty
[[ "${SECRET_PLATFORMSH_CLI_TOKEN}" != "" ]]
### Setup ###
make start -e ENV='-e SECRET_PLATFORMSH_CLI_TOKEN'
run _healthcheck_wait
unset output
### Tests ###
# Confirm token was passed to the container
run docker exec -u docker "${NAME}" bash -lc 'echo SECRET_PLATFORMSH_CLI_TOKEN: ${SECRET_PLATFORMSH_CLI_TOKEN}'
[[ "${output}" == "SECRET_PLATFORMSH_CLI_TOKEN: ${SECRET_PLATFORMSH_CLI_TOKEN}" ]]
unset output
# Confirm the SECRET_ prefix was stripped
run docker exec -u docker "${NAME}" bash -lc 'echo PLATFORMSH_CLI_TOKEN: ${SECRET_PLATFORMSH_CLI_TOKEN}'
[[ "${output}" == "PLATFORMSH_CLI_TOKEN: ${SECRET_PLATFORMSH_CLI_TOKEN}" ]]
unset output
# Confirm authentication works
run docker exec -u docker "${NAME}" bash -lc 'platform auth:info -n'
[[ ${status} == 0 ]]
[[ ! "${output}" =~ "Invalid API token" ]]
[[ "${output}" =~ "developer@docksal.io" ]]
unset output
### Cleanup ###
make clean
}
@test "Check Pantheon integration" {
[[ $SKIP == 1 ]] && skip
# Confirm secret is not empty
[[ "${SECRET_TERMINUS_TOKEN}" != "" ]]
### Setup ###
make start -e ENV='-e SECRET_TERMINUS_TOKEN'
run _healthcheck_wait
unset output
### Tests ###
# Confirm token was passed to the container
run docker exec -u docker "${NAME}" bash -lc 'echo SECRET_TERMINUS_TOKEN: ${SECRET_TERMINUS_TOKEN}'
[[ "${output}" == "SECRET_TERMINUS_TOKEN: ${SECRET_TERMINUS_TOKEN}" ]]
unset output
# Confirm the SECRET_ prefix was stripped
run docker exec -u docker "${NAME}" bash -lc 'echo TERMINUS_TOKEN: ${TERMINUS_TOKEN}'
[[ "${output}" == "TERMINUS_TOKEN: ${SECRET_TERMINUS_TOKEN}" ]]
unset output
# Confirm authentication works
run docker exec -u docker "${NAME}" bash -lc 'terminus auth:whoami'
[[ ${status} == 0 ]]
[[ ! "${output}" =~ "You are not logged in." ]]
[[ "${output}" =~ "developer@docksal.io" ]]
unset output
### Cleanup ###
make clean
}
@test "Check cron" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# Give cron 60s to invoke the scheduled test job
sleep 60
# Confirm cron has run and file contents has changed
run docker exec -u docker "$NAME" bash -lc 'tail -1 /tmp/date.txt'
[[ "${output}" =~ "The current date is " ]]
unset output
### Cleanup ###
make clean
}
@test "Git settings" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start -e ENV='-e GIT_USER_EMAIL=git@example.com -e GIT_USER_NAME="Docksal CLI"'
run _healthcheck_wait
unset output
### Tests ###
# Check git settings were applied
run docker exec -u docker "$NAME" bash -lc 'git config --get --global user.email'
[[ "${output}" == "git@example.com" ]]
unset output
run docker exec -u docker "$NAME" bash -lc 'git config --get --global user.name'
[[ "${output}" == "Docksal CLI" ]]
unset output
### Cleanup ###
make clean
}
@test "PHPCS Coding standards check" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# Check PHPCS libraries loaded
# Normalize the output from phpcs -i so it's easier to do matches
run docker exec -u docker "$NAME" bash -lc "phpcs -i | sed 's/,//g'"
# The trailing space below allows comparing all values the same way: " <value> " (needed for the last value to match).
output="${output} "
[[ "${output}" =~ " Drupal " ]]
[[ "${output}" =~ " DrupalPractice " ]]
[[ "${output}" =~ " WordPress " ]] # Includes WordPress-Core, WordPress-Docs and WordPress-Extra
[[ "${output}" =~ " PHPCompatibility " ]]
[[ "${output}" =~ " PHPCompatibilityWP " ]]
[[ "${output}" =~ " PHPCompatibilityParagonieRandomCompat " ]]
unset output
### Cleanup ###
make clean
}
@test "Check Drush Backdrop Commands" {
[[ $SKIP == 1 ]] && skip
# Skip until Drush Backdrop is compatible with PHP 7.4
[[ "$VERSION" == "7.4" ]] && skip
### Setup ###
make start
run _healthcheck_wait
unset output
### Tests ###
# Check Drush Backdrop command loaded
run docker exec -u docker "$NAME" bash -lc 'drush help backdrop-core-status'
[[ "${output}" =~ "Provides a birds-eye view of the current Backdrop installation, if any." ]]
unset output
### Cleanup ###
make clean
}
@test "VS Code Server" {
[[ $SKIP == 1 ]] && skip
### Setup ###
make start -e ENV='-e IDE_ENABLED=1'
run _healthcheck_wait
unset output
### Tests ###
run make logs
echo "$output" | grep 'HTTP server listening on http://0\.0\.0\.0:8080'
unset output
### Cleanup ###
make clean
}
|
<filename>rtptime/rtptime_test.go
package rtptime
import (
"testing"
"time"
)
func TestDuration(t *testing.T) {
a := FromDuration(time.Second, 48000)
if a != 48000 {
t.Errorf("Expected 48000, got %v", a)
}
b := FromDuration(-time.Second, 48000)
if b != -48000 {
t.Errorf("Expected -48000, got %v", b)
}
c := ToDuration(48000, 48000)
if c != time.Second {
t.Errorf("Expected %v, got %v", time.Second, c)
}
d := ToDuration(-48000, 48000)
if d != -time.Second {
t.Errorf("Expected %v, got %v", -time.Second, d)
}
}
func differs(a, b, delta uint64) bool {
if a < b {
a, b = b, a
}
return a-b >= delta
}
func TestTime(t *testing.T) {
a := Now(48000)
time.Sleep(40 * time.Millisecond)
b := Now(48000) - a
if differs(b, 40*48, 160) {
t.Errorf("Expected %v, got %v", 4*48, b)
}
c := Microseconds()
time.Sleep(4 * time.Millisecond)
d := Microseconds() - c
if differs(d, 4000, 1000) {
t.Errorf("Expected %v, got %v", 4000, d)
}
c = Jiffies()
time.Sleep(time.Second * 10000000 / JiffiesPerSec)
d = Jiffies() - c
if differs(d, 10000000, 1000000) {
t.Errorf("Expected %v, got %v", 10000000, d)
}
}
func TestNTP(t *testing.T) {
now := time.Now()
ntp := TimeToNTP(now)
now2 := NTPToTime(ntp)
ntp2 := TimeToNTP(now2)
diff1 := now2.Sub(now)
if diff1 < 0 {
diff1 = -diff1
}
if diff1 > time.Nanosecond {
t.Errorf("Expected %v, got %v (diff=%v)",
now, now2, diff1)
}
diff2 := int64(ntp2 - ntp)
if diff2 < 0 {
diff2 = -diff2
}
if diff2 > (1 << 8) {
t.Errorf("Expected %v, got %v (diff=%v)",
ntp, ntp2, float64(diff2)/float64(1<<32))
}
}
|
//
// Created by ooooo on 2020/2/26.
//
#ifndef CPP_0322__SOLUTION1_H_
#define CPP_0322__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
/**
* p = coins[j] ==> dp[i] = min(dp[i],dp[i-p] + 1)
*/
class Solution {
public:
int coinChange(vector<int> &coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; ++i) {
for (int j = 0; j < coins.size(); ++j) {
int k = i - coins[j];
if (k >= 0) {
dp[i] = min(dp[i], dp[k] + 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};
#endif //CPP_0322__SOLUTION1_H_
|
package com.roncoo.education.course.service.dao;
import java.util.List;
import com.roncoo.education.course.service.dao.impl.mapper.entity.CourseCategory;
import com.roncoo.education.course.service.dao.impl.mapper.entity.CourseCategoryExample;
import com.roncoo.education.util.base.Page;
public interface CourseCategoryDao {
int save(CourseCategory record);
int deleteById(Long id);
int updateById(CourseCategory record);
CourseCategory getById(Long id);
Page<CourseCategory> listForPage(int pageCurrent, int pageSize, CourseCategoryExample example);
/**
* 根据父类编号查找课程分类信息
*
* @param parentId
* @author WY
*/
List<CourseCategory> listByParentId(Long parentId);
/**
* 根据层级列出分类信息
*
* @param floor
* @author WY
*/
List<CourseCategory> listByFloor(Integer floor);
/**
* 根据层级、父类ID列出分类信息
*
* @param floor
* @param parentId
* @author WY
*/
List<CourseCategory> listByFloorAndCategoryId(Integer floor, Long parentId);
/**
* 根据分类类型、层级查询可用状态的课程分类集合
*
* @param categoryType
* @param floor
* @param statusId
* @author wuyun
*/
List<CourseCategory> listByCategoryTypeAndFloorAndStatusId(Integer categoryType, Integer floor, Integer statusId);
} |
function attachEvents() {
const baseUrl = 'https://baas.kinvey.com/';
const appKey = '<KEY>';
const username = 'ovardov';
const password = '<PASSWORD>';
const endpoint = 'players';
const headers = {
'Authorization': `Basic ${btoa(username + ':' + password)}`,
'Content-Type': 'application/json'
};
startGame();
$('#reload').click(reloadBullets);
$('#save').click(saveGame);
$('#addPlayer').click(addPlayer);
let selectedPlayer;
let playerId;
let allPlayers;
async function startGame() {
try {
allPlayers = await $.ajax({
method: 'GET',
url: baseUrl + 'appdata/' + appKey + '/' + endpoint,
headers
});
showPlayers(allPlayers);
$('#canvas').css('display', 'block');
$('#save').css('display', 'block');
$('#reload').css('display', 'block');
selectedPlayer = allPlayers[0];
playerId = selectedPlayer._id;
clearInterval(canvas.intervalId);
// Load game screen
loadCanvas(selectedPlayer);
} catch (error) {
alert(`Error: ${error.message}`);
}
}
function showPlayers(allPlayers) {
$('#players').empty();
for (let player of allPlayers) {
let id = player._id;
let name = player.name;
let money = +player.money;
let bullets = +player.bullets;
let div = $(`
<div class="player" data-id="${id}">
<div class="row">
<label>Name:</label>
<label class="name">${name}</label>
</div>
<div class="row">
<label>Money:</label>
<label class="money">${money}</label>
</div>
<div class="row">
<label>Bullets:</label>
<label class="bullets">${bullets}</label>
</div>
</div>
`);
let playButton = $('<button>')
.addClass('play')
.text('Play');
playButton.click(selectPlayer);
let deleteButton = $('<button>')
.addClass('delete')
.text('Delete');
deleteButton.click(deletePlayer);
div
.append(playButton)
.append(deleteButton);
$('#players').append(div);
}
}
async function addPlayer() {
let playerNameElement = $('#addName');
let playerName = playerNameElement.val();
let newPlayer = {
name: playerName,
money: 500,
bullets: 6
};
try {
await $.ajax({
method: 'POST',
url: baseUrl + 'appdata/' + appKey + '/' + endpoint,
data: JSON.stringify(newPlayer),
headers
});
playerNameElement.val('');
startGame();
} catch (error) {
alert(`Error: ${error.message}`);
}
}
function selectPlayer() {
let id = $(this)
.parent()
.attr('data-id');
selectedPlayer = allPlayers
.filter(x => x._id === id)[0];
playerId = id;
clearInterval(canvas.intervalId);
loadCanvas(selectedPlayer);
}
async function deletePlayer() {
let id = $(this)
.parent()
.attr('data-id');
try {
await $.ajax({
method: 'DELETE',
url: baseUrl + 'appdata/' + appKey + '/' + endpoint + '/' + id,
headers
});
startGame();
} catch (error) {
alert(`Error: ${error.message}`);
}
}
function reloadBullets() {
if (selectedPlayer.money >= 60) {
selectedPlayer.money -= 60;
selectedPlayer.bullets += 6;
}
}
async function saveGame() {
try {
await $.ajax({
method: 'PUT',
url: baseUrl + 'appdata/' + appKey + '/' + endpoint + '/' + playerId,
headers,
data: JSON.stringify(selectedPlayer)
});
startGame();
} catch (error) {
alert(`Error: ${error.message}`);
}
}
} |
<filename>src/main/webapp/WEB-INF/themes/root/resource/js/components/metrics_recommended_section.js
/*
* Copyright (c) 2017 Public Library of Science
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
var MetricsRecommendedSection;
(function ($) {
MetricsRecommendedSection = MetricsTabComponent.extend({
$element: $('#f1kContent'),
$loadingEl: $('#f1KSpinner'),
$headerEl: $('#f1kHeader'),
sourceOrder: ['f1000'],
loadData: function (data) {
this._super(data);
this.createTiles();
this.afterLoadData();
},
dataError: function () {
this.$element.hide();
this.$loadingEl.hide();
this.$headerEl.hide();
},
newArticleError: function () {
this.dataError();
}
});
})(jQuery); |
<filename>services/api/src/models/__tests__/user.js
const User = require('../user');
const mongoose = require('mongoose');
describe('User', () => {
describe('serialization', () => {
it('should expose id', () => {
const user = new User();
const data = JSON.parse(JSON.stringify(user));
expect(data.id).toBe(user.id);
});
it('should not expose _id or __v', () => {
const user = new User();
const data = JSON.parse(JSON.stringify(user));
expect(data._id).toBeUndefined();
expect(data.__v).toBeUndefined();
});
it('should not expose _password or hashedPassword', () => {
const user = new User({
password: '<PASSWORD>',
hashedPassword: '<PASSWORD>',
});
expect(user._password).toBe('<PASSWORD>');
expect(user.hashedPassword).toBe('<PASSWORD>');
const data = JSON.parse(JSON.stringify(user));
expect(data.password).toBeUndefined();
expect(data._password).toBeUndefined();
expect(data.hashedPassword).toBeUndefined();
});
});
describe('validation', () => {
it('should validate email field', () => {
let user;
user = new User({
firstName: 'Neo',
lastName: 'One',
email: '<EMAIL>',
});
expect(user.validateSync()).toBeUndefined();
user = new User({
firstName: 'Neo',
lastName: 'One',
email: 'bad@email',
});
expect(user.validateSync()).toBeInstanceOf(mongoose.Error.ValidationError);
user = new User({
firstName: 'Neo',
lastName: 'One',
email: null,
});
expect(user.validateSync()).toBeInstanceOf(mongoose.Error.ValidationError);
});
});
});
|
<gh_stars>0
/**
* ACTION TYPES
*/
export const SET_MODAL = 'SET_MODAL';
export const SET_CHECKOUT_MODAL = 'SET_CHECKOUT_MODAL';
/**
* INITIAL STATE
*/
const InitialState = {
showModal: false,
checkoutModal: true,
}
// /**
// * ACTION CREATORS
// */
export const modal = (bool) => ({type: SET_MODAL, showModal: bool});
export const checkoutModal = (bool) => ({type: SET_CHECKOUT_MODAL, checkoutModal: bool});
// /**
// * REDUCER
// */
export default function(state = InitialState, action) {
switch (action.type) {
case SET_MODAL:
return {
...state,
showModal: action.showModal,
checkoutModal: action.showModal,
};
case SET_CHECKOUT_MODAL:
return {
...state,
checkoutModal: action.checkoutModal
}
default:
return state
}
}
|
<gh_stars>1-10
/*
*
*/
package net.community.chest.ui.components.dialog.load.xml;
import net.community.chest.ui.helpers.combobox.EnumComboBox;
import net.community.chest.ui.helpers.combobox.TypedComboBoxActionListener;
/**
* <P>Copyright GPLv2</P>
*
* @author <NAME>.
* @since Mar 31, 2009 12:41:00 PM
*/
public abstract class XmlImportSourceChoiceListener extends
TypedComboBoxActionListener<XmlImportSource,EnumComboBox<XmlImportSource>> {
protected XmlImportSourceChoiceListener ()
{
super();
}
}
|
<filename>src/profile/entities/follower.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm';
@Entity('follower')
export class ProfileEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
followerId: number;
@Column()
followingId: number;
}
|
#include "PhotoTransistor.h"
#include "AnalogInputPin.h"
#ifndef COMMON_DECLARATION
#define COMMON_DECLARATION
static int read_dummy() {
return 0;
}
static const struct AnalogInputPin AnalogInputPin_dummy = {
read_dummy,
};
static const struct PhotoTransistor* PhotoTransistor0_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* PhotoTransistor1_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* PhotoTransistor2_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* PhotoTransistor3_constructor(const struct AnalogInputPin*);
static const struct PhotoTransistor* (*PhotoTransistorn_constructor[4])(const struct AnalogInputPin*) = {
PhotoTransistor0_constructor,
PhotoTransistor1_constructor,
PhotoTransistor2_constructor,
PhotoTransistor3_constructor,
};
const struct PhotoTransistor* createPhotoTransistor(
const struct AnalogInputPin* pin) {
static char index = 0;
return PhotoTransistorn_constructor[index++](
pin);
}
#endif /* COMMON_DECLARATION */
#if !defined(PHOTO_TRANSISTOR0_DECLARED)
#define PHOTO_TRANSISTOR0_DECLARED
#define this_(name) PhotoTransistor0_##name
#elif !defined(PHOTO_TRANSISTOR1_DECLARED)
#define PHOTO_TRANSISTOR1_DECLARED
#define this_(name) PhotoTransistor1_##name
#elif !defined(PHOTO_TRANSISTOR2_DECLARED)
#define PHOTO_TRANSISTOR2_DECLARED
#define this_(name) PhotoTransistor2_##name
#elif !defined(PHOTO_TRANSISTOR3_DECLARED)
#define PHOTO_TRANSISTOR3_DECLARED
#define this_(name) PhotoTransistor3_##name
#define EXIT_LOOP
#endif
static const struct AnalogInputPin* this_(pin);
static int this_(read)() {
return this_(pin)->read();
}
static const struct PhotoTransistor this_(instance) = {
this_(read),
};
static const struct PhotoTransistor* this_(constructor)(
const struct AnalogInputPin* pin) {
this_(pin) = &AnalogInputPin_dummy;
this_(pin) = pin;
return &this_(instance);
}
#undef this_
#if !defined(EXIT_LOOP)
#include "PhotoTransistor.c"
#endif
|
#!/usr/bin/env sh
GITHUB_REPO="lonely-lockley/ltsv-parser"
MERGE_BRANCH=master
SOURCE_BRANCH=dev
FUNCTION_NAME="merge-$SOURCE_BRANCH-to-$MERGE_BRANCH"
echo "$FUNCTION_NAME: $GITHUB_REPO"
echo "$FUNCTION_NAME: TRAVIS_BRANCH = $TRAVIS_BRANCH"
echo "$FUNCTION_NAME: TRAVIS_PULL_REQUEST = $TRAVIS_PULL_REQUEST"
if [ "$TRAVIS_BRANCH" != "$SOURCE_BRANCH" ];
then
echo "$FUNCTION_NAME: Exiting! Branch is not $SOURCE_BRANCH: ($TRAVIS_BRANCH)"
exit 0;
fi
if [ "$TRAVIS_PULL_REQUEST" != "false" ];
then
echo "$FUNCTION_NAME: Exiting! This is a Pull Request: $TRAVIS_PULL_REQUEST"
exit 0;
fi
: ${GITHUB_SECRET_TOKEN:?"GITHUB_SECRET_TOKEN needs to be set in .travis.yml!"}
: ${TRAVIS_COMMIT:?"TRAVIS_COMMIT needs to be available to merge the right commit to master!"}
TEMPORARY_REPOSITORY=$(mktemp -d)
git clone "https://github.com/$GITHUB_REPO" "$TEMPORARY_REPOSITORY"
cd $TEMPORARY_REPOSITORY
echo "Checking out $SOURCE_BRANCH"
git checkout $SOURCE_BRANCH
git checkout -b tomerge $TRAVIS_COMMIT
echo "Checking out $MERGE_BRANCH"
git checkout $MERGE_BRANCH
echo "Merging temporary branch tomerge ($TRAVIS_COMMIT) from $SOURCE_BRANCH into $MERGE_BRANCH"
git merge --ff-only "tomerge"
echo "Pushing to $GITHUB_REPO"
# Redirect to /dev/null to avoid secret leakage
git push "https://$GITHUB_SECRET_TOKEN@github.com/$GITHUB_REPO" $MERGE_BRANCH > /dev/null 2>&1
|
<filename>App/src/main/java/com/honyum/elevatorMan/net/GetMaintListByEleRequest.java
package com.honyum.elevatorMan.net;
import com.honyum.elevatorMan.net.base.RequestBean;
import com.honyum.elevatorMan.net.base.RequestBody;
/**
* Created by Star on 2017/6/15.
*/
public class GetMaintListByEleRequest extends RequestBean {
public GetMaintListByEleBody getBody() {
return body;
}
public void setBody(GetMaintListByEleBody body) {
this.body = body;
}
private GetMaintListByEleBody body;
public class GetMaintListByEleBody extends RequestBody {
public String getElevatorId() {
return elevatorId;
}
public GetMaintListByEleBody setElevatorId(String elevatorId) {
this.elevatorId = elevatorId;
return this;
}
private String elevatorId;
}
}
|
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
class DisplayManager(QObject):
# Existing code remains the same
def display_text(self, text):
# Display the given text on the screen
self.display.setText(text)
def showFullScreen(self):
# Show the display in full screen
self.display.showFullScreen()
# Example usage
app = QApplication([])
display = QLabel()
image_label = QLabel()
manager = DisplayManager(display, image_label)
manager.display("path_to_image.jpg", "Example text")
app.exec_() |
/*********************************************************************
Blosc - Blocked Shuffling and Compression Library
Copyright (C) 2021 The Blosc Developers <<EMAIL>>
https://blosc.org
License: BSD 3-Clause (see LICENSE.txt)
See LICENSE.txt for details about copyright and rights to use.
**********************************************************************/
#include <stdbool.h>
#include <stdio.h>
#include "stune.h"
/* Whether a codec is meant for High Compression Ratios
Includes LZ4 + BITSHUFFLE here, but not BloscLZ + BITSHUFFLE because,
for some reason, the latter does not work too well */
static bool is_HCR(blosc2_context * context) {
switch (context->compcode) {
case BLOSC_BLOSCLZ :
return false;
case BLOSC_LZ4 :
return (context->filter_flags & BLOSC_DOBITSHUFFLE) ? true : false;
case BLOSC_LZ4HC :
return true;
case BLOSC_ZLIB :
return true;
case BLOSC_ZSTD :
return true;
default :
return false;
}
}
void blosc_stune_init(void * config, blosc2_context* cctx, blosc2_context* dctx) {
}
// Set the automatic blocksize 0 to its real value
void blosc_stune_next_blocksize(blosc2_context *context) {
int32_t clevel = context->clevel;
int32_t typesize = context->typesize;
int32_t nbytes = context->sourcesize;
int32_t user_blocksize = context->blocksize;
int32_t blocksize = nbytes;
// Protection against very small buffers
if (nbytes < typesize) {
context->blocksize = 1;
return;
}
if (user_blocksize) {
blocksize = user_blocksize;
goto last;
}
if (nbytes >= L1) {
blocksize = L1;
/* For HCR codecs, increase the block sizes by a factor of 2 because they
are meant for compressing large blocks (i.e. they show a big overhead
when compressing small ones). */
if (is_HCR(context)) {
blocksize *= 2;
}
// Choose a different blocksize depending on the compression level
switch (clevel) {
case 0:
// Case of plain copy
blocksize /= 4;
break;
case 1:
blocksize /= 2;
break;
case 2:
blocksize *= 1;
break;
case 3:
blocksize *= 2;
break;
case 4:
case 5:
blocksize *= 4;
break;
case 6:
case 7:
case 8:
blocksize *= 8;
break;
case 9:
// Do not exceed 256 KB for non HCR codecs
blocksize *= 8;
if (is_HCR(context)) {
blocksize *= 2;
}
break;
default:
break;
}
}
/* Now the blocksize for splittable codecs */
if (clevel > 0 && split_block(context, typesize, blocksize, true)) {
// For performance reasons, do not exceed 256 KB (it must fit in L2 cache)
switch (clevel) {
case 1:
case 2:
case 3:
blocksize = 32 * 1024;
break;
case 4:
case 5:
case 6:
case 7:
case 8:
blocksize = 256 * 1024;
break;
case 9:
default:
blocksize = 512 * 1024;
break;
}
// Multiply by typesize to get proper split sizes
blocksize *= typesize;
// But do not exceed 4 MB per thread (having this capacity in L3 is normal in modern CPUs)
if (blocksize > 4 * 1024 * 1024) {
blocksize = 4 * 1024 * 1024;
}
if (blocksize < 32 * 1024) {
/* Do not use a too small blocksize (< 32 KB) when typesize is small */
blocksize = 32 * 1024;
}
}
last:
/* Check that blocksize is not too large */
if (blocksize > nbytes) {
blocksize = nbytes;
}
// blocksize *must absolutely* be a multiple of the typesize
if (blocksize > typesize) {
blocksize = blocksize / typesize * typesize;
}
context->blocksize = blocksize;
}
void blosc_stune_next_cparams(blosc2_context * context) {
BLOSC_UNUSED_PARAM(context);
}
void blosc_stune_update(blosc2_context * context, double ctime) {
BLOSC_UNUSED_PARAM(context);
BLOSC_UNUSED_PARAM(ctime);
}
void blosc_stune_free(blosc2_context * context) {
BLOSC_UNUSED_PARAM(context);
}
|
const config = require("../package.json");
const puppeteer = require("puppeteer");
const status = require("./status");
const steamStatusURL = "https://steamstat.us";
/**
* The core class to manage the scraping.
*/
class iSteamAlive {
constructor(cache) {
this.cache = cache;
}
getHome = async (_req, res) => {
res.send(
"<pre>Visit <b>iSteamAlive API</b> (v" +
config.version +
") on <a href='https://github.com/flechajm/iSteamAliveAPI'>GitHub</a>.</pre>"
);
};
/**
* Gets the status of the Steam Services.
* @param {*} _req Request.
* @param {*} res Response.
*/
getStatus = async (_req, res) => {
let browser;
try {
const cacheValue = this.cache.get(steamStatusURL);
if (cacheValue !== undefined) {
res.send(cacheValue);
} else {
browser = await this.#getBrowser();
const page = await this.#goToSteamStatus(browser);
const jsonParsed = await this.#getJSON(page);
this.cache.set(steamStatusURL, jsonParsed);
res.send(jsonParsed);
}
} catch (e) {
res.sendStatus(500);
} finally {
if (browser) await browser.close();
}
};
/**
* Gets the JSON mapped after scraping the web.
* @returns JSON String.
*/
async #getJSON(page) {
const json = await page
.evaluate((selector) => {
const servicesData = [];
const elements = document.querySelectorAll(selector);
let name;
let status;
let alert;
for (let i = 0; i < elements.length; i++) {
const serviceDOM = elements[i];
if (serviceDOM.textContent != "") {
if (i % 2 == 0) {
name = serviceDOM.textContent.trim();
} else {
status = serviceDOM.textContent.trim();
alert = serviceDOM.className.split(" ")[1];
if (alert != null) {
servicesData.push(new Array(name, status, alert));
}
}
}
}
return servicesData;
}, ".service > span")
.then((services) => {
const mappedServices = this.#mapServices(services);
return JSON.stringify(mappedServices);
});
return json;
}
/**
* Instantiates a new Page and navigate to the Steam Status URL, then returns it.
* @returns An instance of Page.
*/
async #goToSteamStatus(browser) {
const page = await browser.newPage();
await page.setUserAgent("Chrome/93.0.4577.0");
await page.goto(steamStatusURL, {
waitUntil: "domcontentloaded",
});
await page.waitForTimeout(500);
return page;
}
/**
* Gets the browser with some arguments.
* @returns An instance of Browser.
*/
async #getBrowser() {
return await puppeteer.launch({
headless: true,
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
}
/**
* Maps the array of services.
* @param {Array} services Array of services and their states to be mapped.
* @returns
*/
#mapServices(services) {
for (let i = 0; i < services.length; i++) {
const service = services[i];
let data = { name: service[0], status: service[1], alert: service[2] };
switch (i) {
case 0:
status.steam_platform.online = data;
break;
case 1:
status.steam_platform.ingame = data;
break;
case 2:
status.steam_platform.store = data;
break;
case 3:
status.steam_platform.community = data;
break;
case 4:
status.steam_platform.webapi = data;
break;
case 5:
status.steam_platform.connection_managers = data;
break;
case 6:
status.game_coordinators.team_fortress2 = data;
break;
case 7:
status.game_coordinators.dota2 = data;
break;
case 8:
status.game_coordinators.csgo = data;
break;
case 9:
status.csgo_services.sessions_logon = data;
break;
case 10:
status.csgo_services.player_inventories = data;
break;
case 11:
status.csgo_services.matchmaking_scheduler = data;
break;
default:
break;
}
}
return status;
}
}
module.exports = iSteamAlive;
|
<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# <NAME>
#
'''
# Set SPARK_HOME and PYTHONPATH to use 2.4.0
export PYSPARK_SUBMIT_ARGS="--driver-memory 8g pyspark-shell"
export SPARK_HOME=/Users/em21/software/spark-2.4.0-bin-hadoop2.7
export PYTHONPATH=$SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-2.4.0-src.zip:$PYTHONPATH
'''
import os
import sys
import pyspark.sql
from pyspark.sql.types import *
from pyspark.sql.functions import *
from functools import reduce
def main():
# Make spark session
global spark
spark = (
pyspark.sql.SparkSession.builder
.getOrCreate()
)
print('Spark version: ', spark.version)
# Args
in_gwas_pattern = 'gs://genetics-portal-sumstats-b38/filtered/significant_window_2mb/gwas/*.parquet'
in_mol_path = 'gs://genetics-portal-sumstats-b38/filtered/significant_window_2mb/molecular_trait'
outf = 'gs://genetics-portal-sumstats-b38/filtered/significant_window_2mb/union'
n_parts = 800
molecular_trait_list = [
'ALASOO_2018.parquet',
'Blueprint.parquet',
'CEDAR.parquet',
'FAIRFAX_2012.parquet',
'FAIRFAX_2014.parquet',
'GENCORD.parquet',
'GEUVADIS.parquet',
'GTEX_v7.parquet',
'HIPSCI.parquet',
'NARANBHAI_2015.parquet',
'NEDELEC_2016.parquet',
'QUACH_2016.parquet',
'SCHWARTZENTRUBER_2018.parquet',
'SUN2018.parquet',
'TWINSUK.parquet',
'VAN_DE_BUNT_2015.parquet',
'eQTLGen.parquet'
]
#
# Load molecular trait datasets -------------------------------------------
#
# Load list of datasets
dfs = []
for in_path in [os.path.join(in_mol_path, study) for study in molecular_trait_list]:
df_temp = spark.read.parquet(in_path)
dfs.append(df_temp)
# Take union
mol_df = reduce(pyspark.sql.DataFrame.unionByName, dfs)
#
# Load GWAS datasets ------------------------------------------------------
#
# Load
gwas_df = spark.read.parquet(in_gwas_pattern)
#
# Take union --------------------------------------------------------------
#
df = gwas_df.unionByName(
mol_df.drop('num_tests')
)
# Repartition
df = (
df.repartitionByRange(n_parts, 'chrom', 'pos')
.sortWithinPartitions('chrom', 'pos')
)
# Save
(
df
.write.parquet(
outf,
mode='overwrite'
)
)
return 0
if __name__ == '__main__':
main()
|
class SceneMain extends Phaser.Scene {
constructor() {
super({ key: "SceneMain" });
}
preload() {
this.load.image("sprBoat", "content/Lyxbat.png");
this.load.image("sprBigBoat", "content/bigboat.png");
this.load.image("sprMediumBoat", "content/mediumboat.png");
this.load.image("sprTraktor", "content/traktor.png");
this.load.image("sprLeftTopSand", "content/leftTopSand.png");
this.load.image("sprLeftSand", "content/leftSand.png");
this.load.image("sprTopSand", "content/topSand.png");
this.load.image("sprRightTopSand", "content/rightTopSand.png");
this.load.image("sprRightSand", "content/rightSand.png");
this.load.image("sprMiddleSand", "content/middleSand.png");
this.load.image("sprPirateShip","content/piratskepp.png");
}
create() {
this.score = 0;
this.scoreText;
this.lost = false;
this.tick = 0;
this.pirateShipTick = 0;
this.spawnSpeed = 0.2;
this.piratespawnSpeed = 0.2;
this.boats = [];
this.selectedBoat = null;
this.wasDown = false;
// Background
this.graphics = this.add.graphics({ fillStyle: { color: 0x06a4d6 }, strokeStyle: { color: 0xffffff} });
this.whiteLine();
//tractors
this.tractors = this.physics.add.group({
velocityX: 50,
velocityY: 0
});
this.scoreText = this.add.text(16, 16, "Score 0", { fontSize: "32px", fill: "#000" });
this.createCoast();
this.boats.push(new Boat(this, Phaser.Math.Between(0, config.width), -50));
}
whiteLine() {
let ocean = new Phaser.Geom.Rectangle();
ocean.width = config.width;
ocean.height = config.height;
this.graphics.fillRectShape(ocean);
this.graphics.lineStyle(5, 0xFFFFFF, 0.3);
}
createCoast() {
this.westCoast = this.physics.add.staticGroup();
this.eastCoast = this.physics.add.staticGroup();
for (var y = 0; y < 11; y++) {
for (var x = 0; x <= 30; x++) {
if (y == 10) {
this.westCoast.add(new Coast(this, x * 15, (712-(y * 15)), "sprTopSand"));
this.eastCoast.add(new Coast(this, 1040 - (x * 15), (712-(y * 15)), "sprTopSand"));
}
else{
this.westCoast.add(new Coast(this, x * 15, (712-(y * 15)), "sprMiddleSand"));
this.eastCoast.add(new Coast(this, 1040 - (x * 15), (712-(y * 15)), "sprMiddleSand"));
}
}
let eastCorner = new Coast(this, 1040 - (x * 15), (712-(y * 15)), (y == 10 ? "sprLeftTopSand" : "sprLeftSand"))
let westCorner = new Coast(this, x * 15, (712-(y * 15)), (y == 10 ? "sprRightTopSand" : "sprRightSand"));
this.eastCoast.add(eastCorner);
this.westCoast.add(westCorner);
}
}
lose(scene) {
scene.physics.pause();
let gameOverText = scene.add.text(config.width / 2, config.height / 2, 'Game Over', { fontSize: '48px', fill: '#000' });
gameOverText.setOrigin(0.5)
scene.lost = true;
this.scene.tick = 0;
}
scareBoat(){
//this.boats.disableBody(true,true);
//Ge båten en random velocity åt något håll när den dunkar in i traktorn.
}
updateScore(boat){
//this.boats.disableBody(true,true);
//Ge båten en random velocity åt något håll när den dunkar in i traktorn.
boat.destroy();
this.score+=10;
console.log(this.score);
this.scoreText.setText('Points: ' + this.score);
}
update() {
let mouse = game.input.mousePointer;
// Spawn boats
if (this.tick >= 60 / this.spawnSpeed && !this.lost) {
this.tick = 0;
this.spawnSpeed += 0.001;
this.boats.push(new Boat(this, Phaser.Math.Between(0, config.width), -50));
}
else {
this.tick++;
}
//Spawn tractors
if(this.pirateShipTick >= 120 / this.piratespawnSpeed && !this.lost){
this.pirateShipTick = 0;
this.spawnSpeed += 0.001;
this.tractors.add(new Tractor(this, 10,Phaser.Math.Between(100,config.height-500)));
}
else {
this.pirateShipTick++;
}
// Move Boat
if (this.selectedBoat != null && mouse.isDown) {
if (!this.wasDown) {
this.wasDown = true;
this.selectedBoat.line = this.selectedBoat.graphics.beginPath();
this.selectedBoat.path = [];
}
let length = this.selectedBoat.path.length
if (this.pathIndex == 0 || length == 0 || (this.selectedBoat.path[length - 1].x != mouse.x || this.selectedBoat.path[length - 1].y != mouse.y)) {
this.selectedBoat.path.push(new Phaser.Geom.Point(mouse.x, mouse.y));
this.pathIndex++;
}
} else {
//this.fillBackIn()
this.wasDown = false;
this.selectedBoat = null;
}
this.boats.forEach(boat => {
if(boat.y>700 && boat.y<750){
this.boats.splice(this.boats.indexOf(boat),1);
this.updateScore(boat)
};
boat.followLine();
});
if (this.lost && this.tick > 300) {
this.scene.start("SceneStart");
}
}
}
|
<reponame>XiaoMiSum/agile-tester-ui
import request from '@/utils/request'
export function getSuiteList(params) {
return request({
url: '/testsuite',
method: 'get',
params
})
}
export function updateSuite(data) {
return request({
url: '/testsuite',
method: 'post',
data
})
}
|
<reponame>duongnguyensv/tiktok-videos
package unittestutil
import (
"testing"
)
// TestUtil - Utility for testing
type TestUtil struct {
T *testing.T
}
|
<filename>api/v1beta1/databaseserver_types.go
/*
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 v1beta1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// Database defines the database
type Database struct {
Name string `json:"name,omitempty"`
}
// DatabaseServerSpec defines the desired state of DatabaseServer
type DatabaseServerSpec struct {
// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
// Important: Run "make" to regenerate code after modifying this file
Name string `json:"name,omitempty"`
Image string `json:"image,omitempty"`
Port int32 `json:"port,omitempty"`
Password string `json:"password,omitempty"`
Databases []Database `json:"databases,omitempty"`
}
// DatabaseServerStatus defines the observed state of DatabaseServer
type DatabaseServerStatus struct {
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
// Important: Run "make" to regenerate code after modifying this file
}
// +kubebuilder:object:root=true
// DatabaseServer is the Schema for the databaseservers API
type DatabaseServer struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec DatabaseServerSpec `json:"spec,omitempty"`
Status DatabaseServerStatus `json:"status,omitempty"`
}
// +kubebuilder:object:root=true
// DatabaseServerList contains a list of DatabaseServer
type DatabaseServerList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []DatabaseServer `json:"items"`
}
func init() {
SchemeBuilder.Register(&DatabaseServer{}, &DatabaseServerList{})
}
|
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-NER/7-model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-NER/7-512+0+512-common-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_common_words_first_half_quarter --eval_function penultimate_quarter_eval |
#!/bin/bash
# Set the script to exit immediately if any command exits with a non-zero status, if any undefined variable is used, or if any command in a pipeline fails.
set -eou pipefail
# Enable the globstar option to allow recursive directory expansion.
shopt -s globstar
# Your additional script logic goes here to handle file operations and error handling.
# Example:
# Perform a specific action on all files within the directory structure.
# for file in **/*; do
# if [ -f "$file" ]; then
# # Perform the desired action on the file
# echo "Processing file: $file"
# fi
# done |
<filename>btalib/indicators/beta.py
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 <NAME>
# Use of this source code is governed by the MIT License
###############################################################################
from . import Indicator
class beta(Indicator):
'''
The description of the algorithm has been adapted from `ta-lib`
The Beta 'algorithm' is a measure of a stocks volatility vs from index. The
stock prices are given as the 1st input and the index prices are given in
the 2nd input. The size of the inputs should be equal. The algorithm is to
calculate the change between prices in both inputs and then 'plot' these
changes are points in the Euclidean plane. The x value of the point is
market return and the y value is the security return. The beta value is the
slope of a linear regression through these points. A beta of 1.0 is simple
the line y=x, so the stock varies precisely with the market. A beta of less
than 1.0 means the stock varies less thandd the market and a beta of more
than 1.0 means the stock varies more than market.
See:
- http://www.moneychimp.com/articles/risk/regression.htm
'''
group = 'statistic'
alias = 'BETA', 'Beta'
inputs = 'asset', 'market'
outputs = 'beta'
params = (
('period', 5, 'Period to consider'),
('_prets', 1, 'Lookback period to calculate the returns'),
('_rets', True, 'Calculate beta on returns'),
)
def __init__(self):
p, prets = self.p.period, self.p._prets
if self.p._rets:
x = self.i.asset.pct_change(periods=prets) # stock returns
y = self.i.market.pct_change(periods=prets) # market returns
else:
x, y = self.i.asset, self.i.market
s_x = x.rolling(window=p).sum()
s_y = y.rolling(window=p).sum()
s_xx = x.pow(2).rolling(window=p).sum()
s_xy = (x * y).rolling(window=p).sum()
self.o.beta = (p * s_xy - s_x * s_y) / (p * s_xx - s_x.pow(2))
|
use serde::Serialize;
#[derive(Debug)]
struct BuildConfig {
rustc_version: String,
rustflags: String,
profile: String,
}
#[derive(Serialize, Debug)]
struct GitInfo {
rev: String,
dirty: bool,
}
fn fetch_project_info() -> (BuildConfig, GitInfo) {
// Simulate fetching project information
let build_config = BuildConfig {
rustc_version: "1.55.0".to_string(),
rustflags: "-C opt-level=3".to_string(),
profile: "release".to_string(),
};
let git_info = GitInfo {
rev: "a1b2c3d4".to_string(),
dirty: false,
};
(build_config, git_info)
}
fn display_project_info(build_config: BuildConfig, git_info: GitInfo) {
println!("Rust Compiler Version: {}", build_config.rustc_version);
println!("Rust Flags: {}", build_config.rustflags);
println!("Build Profile: {}", build_config.profile);
println!("Git Revision: {}", git_info.rev);
println!("Working Directory Dirty: {}", git_info.dirty);
}
fn main() {
let (build_config, git_info) = fetch_project_info();
display_project_info(build_config, git_info);
} |
def bubbleSort(arr):
# We set swapped to True so the loop looks runs at least once
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
# Swap the elements
arr[i], arr[i + 1] = arr[i + 1], arr[i]
# Set the flag to True so we'll loop again
swapped = True
return arr
print(bubbleSort(arr)) |
import { combineReducers } from 'redux';
import commonReducer from './reducer';
const rootReducer = combineReducers({
common: commonReducer,
});
export default rootReducer;
|
<filename>django_business_rules/management/commands/dbr.py
import inspect
import pkgutil
from django.conf import settings
from django.core.management.base import BaseCommand
import six
from django_business_rules.business_rule import BusinessRule
from django_business_rules.models import BusinessRuleModel
class BusinessRuleGenerateException(Exception):
pass
class Command(BaseCommand):
help = 'Updates rules data in database'
BUSINESS_RULE_MODULE_NAME = 'rules'
def add_arguments(self, parser):
parser.add_argument(
'--noinput', '--no-input',
action='store_false',
dest='interactive',
help='Tells Django to NOT prompt the user for input of any kind.'
)
parser.add_argument(
'-r',
action='store_true',
dest='remove',
help='Removes from DB rules which are not supported by code any more.'
)
def handle(self, *args, **options):
self.stdout.write(
'This command will override all rules data in database.')
business_rule_classes = self._find_business_rule_classes(options)
self._validate(business_rule_classes, options)
self._save(business_rule_classes, options)
self.stdout.write('Done with SUCCESS.')
def _find_business_rule_classes(self, options):
result = []
root_path = settings.BASE_DIR
self._debug('Looking for business rules in: {} ...'.format(
root_path), options)
for module_loader, module_name, is_pkg in pkgutil.walk_packages([root_path]):
if self._is_business_rule_module(module_loader, module_name, is_pkg, root_path):
module = module_loader.find_module(
module_name).load_module(module_name)
result.extend(self._get_business_rule_classes(module))
self._debug('Found business rules: {}'.format(result), options)
return result
@classmethod
def _is_business_rule_module(cls, module_loader, module_name, is_pkg, root_path):
return module_loader.path.startswith(root_path) \
and not is_pkg \
and module_name.endswith(Command.BUSINESS_RULE_MODULE_NAME)
def _get_business_rule_classes(self, module):
result = []
for _, obj in inspect.getmembers(module):
if self._is_business_rule_class(obj):
result.append(obj)
return result
@classmethod
def _is_business_rule_class(cls, obj):
return inspect.isclass(obj) and issubclass(obj, BusinessRule) and obj is not BusinessRule
def _validate(self, business_rule_classes, options):
self._debug('Validating business rules...', options)
unique_rule_names = {}
for rule_class in business_rule_classes:
name = rule_class.get_name()
if name in unique_rule_names:
raise BusinessRuleGenerateException(
'Not unique names for classes: {} and {}'.format(
rule_class, unique_rule_names[name]
)
)
unique_rule_names[name] = rule_class
self._debug('Validation done', options)
def _save(self, business_rule_classes, options):
self._remove_not_supported_rules(business_rule_classes, options)
self._debug('Saving business rules...', options)
for rule_class in business_rule_classes:
self._debug('Generating: {}'.format(
rule_class.get_name()), options)
rule_class.generate()
self._debug('Saving done.', options)
def _remove_not_supported_rules(self, business_rule_classes, options):
self._debug(
'Removing business rules not supported by source code...', options)
supported_business_rule_names = [
business_rule_class.get_name() for business_rule_class in business_rule_classes
]
not_supported_business_rules_query = BusinessRuleModel.objects.exclude(
name__in=supported_business_rule_names)
not_supported_business_rule_names = [
business_rule_model.name
for business_rule_model in not_supported_business_rules_query
]
if not not_supported_business_rule_names:
self._debug('Nothing to delete', options)
return
if not options['interactive']:
if options['remove']:
not_supported_business_rules_query.delete()
self._debug(
'Removed rules not supported by source code:\n- ' +
'\n- '.join(not_supported_business_rule_names),
options
)
else:
self._debug(
'Left rules not supported by source code:\n- ' +
'\n- '.join(not_supported_business_rule_names),
options
)
else:
self.stdout.write('\n'.join(not_supported_business_rule_names))
delete_rules = six.input(
'These rules exist in DB but are no longer supported by source code, should they be deleted?(y/N)'
)
if delete_rules in ['Y', 'y', 'Yes', 'yes']:
not_supported_business_rules_query.delete()
self._debug('Rules removed', options)
def _debug(self, text, options):
if options['verbosity'] > 1:
self.stdout.write(text)
|
sudo apt-get update
sudo apt-get -y install wget curl
sudo apt-get -y install build-essential
sudo apt-get -y install g++ libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils
sudo apt-get -y install libboost-all-dev
sudo apt-get -y install software-properties-common
sudo apt-get update
sudo apt-get -y install libzmq3-dev libbz2-dev zlib1g
sudo apt-get -y install libprotobuf-dev protobuf-compiler
sudo apt-get -y install openssl
sudo apt-get -y install qt4-default
sudo apt-get -y install python-pip
sudo apt-get -y install python-setuptools
sudo pip install python-bitcoinrpc
sudo apt-get -y install git
git clone https://github.com/ShorelineCrypto/cheetah_cpuminer.git
# Berkeley DB: http://download.oracle.com/berkeley-db/db-4.8.30.NC.tar.gz
# This can not be compiled and used for GDNC wallet
# we obtained binaries from Ubuntu 18.04 and bundled in one folder
wget https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/v1.4.0.5/ubuntu18_armhf_db-4.8.30.NC.tgz
tar xvfz ubuntu18_armhf_db-4.8.30.NC.tgz
sudo rm -rf /opt/db-4.8.30.NC
sudo mv db-4.8.30.NC /opt/
sudo mv bitcoin.conf /etc/ld.so.conf.d/
wget https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/v1.4.0.5/ubuntu18_armhf_miniupnpc.tgz
tar xvfz ubuntu18_armhf_miniupnpc.tgz
sudo rm -rf /opt/miniupnpc
sudo mv miniupnpc /opt/
sudo mv miniupnpc.conf /etc/ld.so.conf.d/
wget https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/v1.4.0.5/ubuntu16_armhf_openssl1.0.tgz
tar xvfz ubuntu16_armhf_openssl1.0.tgz
sudo rm -rf /opt/openssl
sudo mv openssl /opt/
sudo mv openssl.conf /etc/ld.so.conf.d/
wget https://github.com/ShorelineCrypto/NewEnglandCoin/releases/download/v1.4.0.5/ubuntu16_armhf_boost1.58.tgz
tar xvfz ubuntu16_armhf_boost1.58.tgz
sudo rm -rf /opt/boost1.58
sudo mv boost1.58 /opt/
sudo mv boost1.58.conf /etc/ld.so.conf.d/
## link all libary files
sudo ldconfig
|
export GEM_PATH="$HOME/vendor/bundle/ruby/2.1.0:$GEM_PATH"
export LANG=${LANG:-en_US.UTF-8}
export PATH="$HOME/bin:$HOME/vendor/bundle/bin:$HOME/vendor/bundle/ruby/2.1.0/bin:$PATH"
export RACK_ENV=${RACK_ENV:-production}
export RAILS_ENV=${RAILS_ENV:-production}
export SECRET_KEY_BASE=${SECRET_KEY_BASE:-loremipsum}
export QUOTES_VAR="quotes here"
export SINGLE_QUOTES_VAR='single quotes here'
|
#!/usr/bin/env bash
# Set versions of software required
linter_version=1.30.0
mockgen_version=v1.4.4
function usage()
{
echo "USAGE: ${0##*/}"
echo "Install software required for golang project"
}
function args() {
while [ $# -gt 0 ]
do
case "$1" in
"--help") usage; exit;;
"-?") usage; exit;;
*) usage; exit;;
esac
done
}
function install_linter() {
TARGET=$(go env GOPATH)
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b "${TARGET}/bin" v${linter_version}
}
args "${@}"
sudo -E env >/dev/null 2>&1
if [ $? -eq 0 ]; then
sudo="sudo -E"
fi
echo "Running setup script to setup software"
GO111MODULE=on go get mvdan.cc/gofumpt/gofumports
golangci-lint --version 2>&1 | grep $linter_version >/dev/null
ret_code="${?}"
if [[ "${ret_code}" != "0" ]] ; then
echo "installing linter version: ${linter_version}"
install_linter
golangci-lint --version 2>&1 | grep $linter_version >/dev/null
ret_code="${?}"
if [ "${ret_code}" != "0" ] ; then
echo "Failed to install linter"
exit
fi
else
echo "linter version: `golangci-lint --version`"
fi
mockgen -version 2>&1 | grep ${mockgen_version} >/dev/null
ret_code="${?}"
if [[ "${ret_code}" != "0" ]] ; then
echo "installing mockgen version: ${mockgen_version}"
GO111MODULE=on go get github.com/golang/mock/mockgen@${mockgen_version}
mockgen -version 2>&1 | grep ${mockgen_version} >/dev/null
ret_code="${?}"
if [ "${ret_code}" != "0" ] ; then
echo "Failed to install mockgen"
exit
fi
else
echo "mockgen version: `mockgen -version`"
fi
|
<reponame>deyihu/maptalks-echarts-gl
import echarts from 'echarts/lib/echarts';
import componentViewControlMixin from '../../component/common/componentViewControlMixin';
import componentPostEffectMixin from '../../component/common/componentPostEffectMixin';
import componentLightMixin from '../../component/common/componentLightMixin';
import componentShadingMixin from '../../component/common/componentShadingMixin';
import geo3DModelMixin from '../../coord/geo3D/geo3DModelMixin';
import formatUtil from '../../util/format';
import formatTooltip from '../common/formatTooltip';
var Map3DModel = echarts.extendSeriesModel({
type: 'series.map3D',
layoutMode: 'box',
coordinateSystem: null,
visualColorAccessPath: 'itemStyle.areaColor',
optionUpdated: function (newOpt) {
newOpt = newOpt || {};
var coordSysType = this.get('coordinateSystem');
if (coordSysType == null || coordSysType === 'geo3D') {
return;
}
if (__DEV__) {
var propsNeedToCheck = [
'left', 'top', 'width', 'height',
'boxWidth', 'boxDepth', 'boxHeight',
'light', 'viewControl', 'postEffect', 'temporalSuperSampling',
'environment', 'groundPlane'
];
var ignoredProperties = [];
propsNeedToCheck.forEach(function (propName) {
if (newOpt[propName] != null) {
ignoredProperties.push(propName);
}
});
if (ignoredProperties.length) {
console.warn(
'Property %s in map3D series will be ignored if coordinate system is %s',
ignoredProperties.join(', '), coordSysType
);
}
}
if (this.get('groundPlane.show')) {
// Force disable groundPlane if map3D has other coordinate systems.
this.option.groundPlane.show = false;
}
},
getInitialData: function (option) {
option.data = this.getFilledRegions(option.data, option.map);
var dimensions = echarts.helper.completeDimensions(['value'], option.data);
var list = new echarts.List(dimensions, this);
list.initData(option.data);
var regionModelMap = {};
list.each(function (idx) {
var name = list.getName(idx);
var itemModel = list.getItemModel(idx);
regionModelMap[name] = itemModel;
});
this._regionModelMap = regionModelMap;
return list;
},
formatTooltip: function (dataIndex) {
return formatTooltip(this, dataIndex);
},
getRegionModel: function (name) {
return this._regionModelMap[name] || new echarts.Model(null, this);
},
/**
* Format label
* @param {string} name Region name
* @param {string} [status='normal'] 'normal' or 'emphasis'
* @return {string}
*/
getFormattedLabel: function (dataIndex, status) {
var text = formatUtil.getFormattedLabel(this, dataIndex, status);
if (text == null) {
text = this.getData().getName(dataIndex);
}
return text;
},
defaultOption: {
// Support geo3D, mapbox
coordinateSystem: 'geo3D',
// itemStyle: {},
// height,
// label: {}
data: null
}
});
echarts.util.merge(Map3DModel.prototype, geo3DModelMixin);
echarts.util.merge(Map3DModel.prototype, componentViewControlMixin);
echarts.util.merge(Map3DModel.prototype, componentPostEffectMixin);
echarts.util.merge(Map3DModel.prototype, componentLightMixin);
echarts.util.merge(Map3DModel.prototype, componentShadingMixin);
export default Map3DModel; |
CREATE DATABASE users_db;
USE users_db;
CREATE TABLE users (
user_id INT AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
PRIMARY KEY(user_id)
); |
<gh_stars>1-10
interface XraySelector {
(url: string, selector: string): XrayResult<string>;
(url: string, scope: string, selector: string): XrayResult<string>;
(url: string, selector: string[]): XrayResult<string[]>;
(url: string, scope: string, selector: string[]): XrayResult<string[]>;
<T>(url: string, selector: T): XrayResult<T>;
<T>(url: string, scope: string, selector: T): XrayResult<T>;
<T>(url: string, selector: [T]): XrayResult<[T]>;
<T>(url: string, scope: string, selector: [T]): XrayResult<[T]>;
}
interface XrayAPI {
(): XraySelector;
}
interface XrayConsume<T> {
(error: Error, result: T): void
}
interface XrayResult<T> {
(result: XrayConsume<T>): void
limit(count: number): XrayResult<T>
paginate(selector: string): XrayResult<T>
write(fileName: string): void
}
declare module "x-ray" {
export = x_ray
var x_ray: XrayAPI;
}
|
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --ntasks=18
#SBATCH --cpus-per-task=1
#SBATCH --nodes=1
#SBATCH --mem=40000
##create error log file for everything?
### CHANGING JU11398 to JT11398
#######################
# FILE LOCATIONS
#######################
python_version=/exports/people/andersenlab/kml436/python2/bin/python
bam_surgeon=/lscr2/andersenlab/kml436/git_repos2/bamsurgeon
reference=/lscr2/andersenlab/kml436/sv_sim2/c_elegans.PRJNA13758.WS245.genomic.fa
twobit=/lscr2/andersenlab/kml436/sv_sim2/c_elegans.PRJNA13758.WS245.genomic.2bit
#twobit=/lscr2/andersenlab/kml436/11_c_elegans_reference.2bit #####
#2bit=/lscr2/andersenlab/kml436/sv_sim2/c_elegans.PRJNA13758.WS245.genomic.2bit
#2bit=/lscr2/andersenlab/kml436/sv_sim2/c_elegans.PRJNA13758.WS245.genomic.2bit
TE_consensus=/lscr2/andersenlab/kml436/git_repos2/Transposons2/files/SET2/round2_consensus_set2.fasta
processors=18
TTR=/lscr2/andersenlab/kml436/git_repos2/mcclintock/
HL_gff=/lscr2/andersenlab/kml436/git_repos2/Transposons2/files/WB_pos_element_names_alias.bed
original_ref_pos=/lscr2/andersenlab/kml436/git_repos2/Transposons2/files/WB_pos_element_names.gff
TE_lengths=/lscr2/andersenlab/kml436/git_repos2/Transposons2/files/SET2/LENGTHS/lengths.txt
family_renames=/lscr2/andersenlab/kml436/git_repos2/Transposons2/files/round2_WB_familes_set2.txt
minimal_Distance_to_count=1000
minimal_supporting_reads=3
minimal_supporting_individuals=1
#######################
# PREPARE BAM NAMING
#######################
bam_name=${1}
echo "bam name is ${bam_name}"
dir_to_bam=/lscr2/andersenlab/dec211/RUN/v2_snpset/bam
bam=${dir_to_bam}/${bam_name}.bam
echo "full path is ${bam}"
mkdir ${bam_name}
cd ${bam_name}
dir=`pwd`
cp -s $bam ${bam_name}.sorted.bam
cp -s $bam.bai ${bam_name}.sorted.bam.bai
#######################
# RUN TEMP
#######################
mkdir raw_results_temp_insertion
cd raw_results_temp_insertion
echo "Running TEMP insertion caller..."
bash ${TTR}/TEMP/scripts/TEMP_Insertion.sh -i ../${bam_name}.sorted.bam -s ${TTR}/TEMP/scripts/ -x 30 -r $TE_consensus -t $HL_gff -m 1 -c 20 &> ../${bam_name}_TEMP_insertion_log.txt
cd ..
mkdir raw_results_temp_absence
cd raw_results_temp_absence
echo "Running TEMP absence caller..."
bash ${TTR}/TEMP/scripts/TEMP_Absence.sh -i ../${bam_name}.sorted.bam -s ${TTR}/TEMP/scripts/ -r $original_ref_pos -t $twobit -c 20 &> ../${bam_name}_TEMP_absence_log.txt
cd ..
#######################
# RUN TELOCATE
#######################
mkdir raw_results_telocate
cd raw_results_telocate
echo "Converting Bam to Sam..."
mkdir sam_file
cd sam_file
samtools view ../../${bam_name}.sorted.bam |sort --temporary-directory=${dir}/raw_results_telocate/sam_file > ${bam_name}.sorted.sam
cd ..
echo "Running TELOCATE absence caller..."
mkdir TELOCATE
cd ${TTR}/TE-locate/
perl TE_locate.pl 2 ${dir}/raw_results_telocate/sam_file/ $HL_gff $reference ${dir}/raw_results_telocate/TELOCATE/TEL $minimal_Distance_to_count $minimal_supporting_reads $minimal_supporting_individuals &> ${dir}/${bam_name}_TELOCATE_log.txt
cd ${dir}
#remove sam files and copied-over bam files to save space
###CHECK THE BELOW
rm raw_results_temp_insertion/${bam_name}.sorted.bam
rm raw_results_temp_insertion/${bam_name}.sorted.bam.bai
rm raw_results_temp_absence/${bam_name}.sorted.bam
rm raw_results_temp_absence/${bam_name}.sorted.bam.bai
########UNDO THE BELOW LINE ALTER!!!!!!!#########
rm -rf raw_results_telocate/sam_file
echo "Done"
#ADD IN TELOCATE
#ADD IN TEMP EXCISION
#mkdir final_results
|
<filename>play/last/js/Monsters.js
function newIceMonster(game){
this.game=game;
newCharacter.call(this,game); //iceMonster is extended of character
this.distance=60;
//Init
this.setName('iceMonster');
this.setHpMax(50);
this.setHp(this.getHpMax());
this.setDamage(40);
this.setArmor(0);
this.setSpeed(800);
this.setCoins(100);
this.setScore(250);
this.setSpriteImage('iceMonster');
//**************************Functions***********************************
this.create = function(){
//Sprite
this.createSprite();
this.createHpDisplay();
this.setDimensions(0.2);
this.setImmovable(true);
this.setGravityAllowed(false);
//Tween
iceMonsterTween = this.game.add.tween(this.getSpriteDisplay()).to({
y: this.getSpriteDisplay().y+this.distance
},this.getSpeed(),'Linear',true,0,this.getSpeed(),true);
};
this.setDistance = function(distance){
this.distance=distance;
};
}
function newJelly(game){
this.game=game;
newCharacter.call(this,game); //jelly is extended of character
//Init
this.setName('jelly');
this.setHpMax(100);
this.setHp(this.getHpMax());
this.setDamage(10);
this.setArmor(0);
this.setSpeed(14000);
this.setCoins(50);
this.setScore(100);
this.setSpriteImage('jelly');
this.distance=700;
//**************************Functions***********************************
this.create = function(){
//Sprite
this.createSprite();
this.createHpDisplay();
this.setDimensions(1);
this.setImmovable(false);
this.setGravityAllowed(true);
this.sprite.display.animations.add('run',[0,1,2],3,true);
//Tween
jellyTween = this.game.add.tween(this.getSpriteDisplay()).to({
x: this.getSpriteDisplay().x+this.distance
},this.getSpeed(),'Linear',true,0,this.getSpeed(),true);
};
this.update = function(){
this.getSpriteDisplay().animations.play('run');
//Update
this.getSpriteDisplay().body.velocity.x=0;
this.game.physics.arcade.collide(this.getSpriteDisplay(),map.getLayer());
if(this.alive()){
if(typeof player != 'undefined'){
if(player.getWeapon().name =='bow'){
for(i=0;i<player.getWeapon().projectile.children.length;i++){
if(player.getWeapon().projectile.children[i].alive && player.getWeapon().projectile.children[i].overlap(this.getSpriteDisplay())){
this.takeDamage(player.getDamage());
player.getWeapon().projectile.children[i].kill();
}
}
}else{
if(player.getWeapon().sprite.visible && player.getWeapon().sprite.overlap(this.getSpriteDisplay())){
this.takeDamage(player.getDamage());
}
}
}
this.updateInvulnerabilityDisplay();
this.updateHpDisplay();
this.game.physics.arcade.collide(this.getSpriteDisplay(),player.getSpriteDisplay(), this.collisionCallback, this.processCallback, this);
}
};
this.setDistance = function(distance){
this.distance=distance;
};
}
function newWall(game){
this.game=game;
newCharacter.call(this,game); //wall is extended of character
this.distance=60;
//Init
this.setName('wall');
this.setHpMax(0);
this.setHp(this.getHpMax());
this.setDamage(20);
this.setArmor(0);
this.setSpeed(800);
this.setSpriteImage('wall');
//**************************Functions***********************************
this.create = function(){
//Sprite
this.createSprite();
this.createHpDisplay();
this.setDimensions(0.2);
this.setImmovable(true);
this.setGravityAllowed(false);
//Tween
wallTween = this.game.add.tween(this.getSpriteDisplay()).to({
y: this.getSpriteDisplay().y+this.distance
},this.getSpeed(),'Linear',true,0,this.getSpeed(),true);
};
this.setDistance = function(distance){
this.distance=distance;
};
}
function newSpike(game){
this.game=game;
newCharacter.call(this,game); //spike is extended of character
this.distance=60;
//Init
this.setName('spike');
this.setHpMax(0);
this.setHp(this.getHpMax());
this.setDamage(20);;
this.setSpriteImage('spike');
//**************************Functions***********************************
this.create = function(){
//Sprite
this.createSprite();
this.createHpDisplay();
this.setDimensions(0.4);
this.setImmovable(true);
this.setGravityAllowed(false);
};
};
//////////////////////////////////////////////// OBJECT
function newBox(game){
this.game=game;
newCharacter.call(this,game); //Box is extended of character
//Init
this.setName('box');
this.setHpMax(0);
this.setHp(this.getHpMax());
this.setSpriteImage('box');
//**************************Functions***********************************
this.create = function(){
//Sprite
this.createSprite();
this.createHpDisplay();
this.setDimensions(0.2);
this.setImmovable(false);
this.setGravityAllowed(true);
};
}
function newChest(game){
this.game=game;
newCharacter.call(this,game); //chest is extended of character
//Init
this.setName('chest');
this.setHpMax(1);
this.setScore(0);
this.setCoins(300);
this.setHp(this.getHpMax());
this.setDamage(0);
this.setSpriteImage('chest');
//**************************Functions***********************************
this.create = function(){
//Sprite
this.createSprite();
this.setDimensions(0.2);
this.setImmovable(true);
this.setGravityAllowed(false);
};
} |
<gh_stars>0
//
// NSDictionary+WJHEventTap.h
// WJHEventTap
//
// Copyright (c) 2015 <NAME>. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSDictionary (WJHEventTap)
/**
Creates a dictionary object containing the specified CGEventTapInformation structure.
@param tapInfo the value for the new object
@return A new dictionary object that contains the @a tapInfo information.
Each field of the structure is contained in the dictionary, with the same name as in the actual structure. Each value is wrapped in an NSNumber object, as appropriate for the field value type.
*/
+ (NSDictionary*)wjh_dictionaryWithCGEventTapInformation:(CGEventTapInformation)tapInfo;
/**
The CGEventTapInformation structure representation of the value. Any field not found in the dictionary will be set to zero.
*/
@property (readonly) CGEventTapInformation wjh_CGEventTapInformationValue;
@end
|
import * as Stats from 'stats.js';
import {
AudioLoader,
CollisionSystem,
ColorSpriteFontGenerator,
GameObject,
GameLoop,
GameRenderer,
ImageLoader,
Logger,
RectFontLoader,
SpriteFontLoader,
SpriteLoader,
State,
Vector,
} from './core';
import { DebugGameLoopMenu, DebugInspector } from './debug';
import {
AudioManager,
GameUpdateArgs,
GameState,
GameStorage,
Session,
} from './game';
import { InputHintSettings, InputManager } from './input';
import { ManifestMapListReader, MapLoader } from './map';
import { PointsHighscoreManager } from './points';
import { GameSceneRouter, GameSceneType } from './scenes';
import * as config from './config';
import * as audioManifest from '../data/audio.manifest.json';
import * as spriteManifest from '../data/sprite.manifest.json';
import * as spriteFontConfig from '../data/fonts/sprite-font.json';
import * as rectFontConfig from '../data/fonts/rect-font.json';
import * as mapManifest from '../data/map.manifest.json';
const loadingElement = document.querySelector('[data-loading]');
const log = new Logger('main', Logger.Level.Debug);
const gameRenderer = new GameRenderer({
// debug: true,
height: config.CANVAS_HEIGHT,
width: config.CANVAS_WIDTH,
});
const gameStorage = new GameStorage(config.STORAGE_NAMESPACE);
gameStorage.load();
const inputManager = new InputManager(gameStorage);
inputManager.listen();
const audioLoader = new AudioLoader(audioManifest);
const imageLoader = new ImageLoader();
const spriteFontLoader = new SpriteFontLoader(imageLoader);
spriteFontLoader.register(config.PRIMARY_SPRITE_FONT_ID, spriteFontConfig);
const colorSpriteFontGenerator = new ColorSpriteFontGenerator(spriteFontLoader);
colorSpriteFontGenerator.register(
config.PRIMARY_SPRITE_FONT_ID,
config.COLOR_BLACK,
);
const spriteLoader = new SpriteLoader(imageLoader, spriteManifest);
const rectFontLoader = new RectFontLoader();
rectFontLoader.register(config.PRIMARY_RECT_FONT_ID, rectFontConfig, {
scale: config.TILE_SIZE_SMALL,
});
const manifestMapListReader = new ManifestMapListReader(mapManifest);
const mapLoader = new MapLoader(manifestMapListReader);
const audioManager = new AudioManager(audioLoader, gameStorage);
audioManager.loadSettings();
const session = new Session();
const inputHintSettings = new InputHintSettings(gameStorage);
const pointsHighscoreManager = new PointsHighscoreManager(gameStorage);
const collisionSystem = new CollisionSystem();
const sceneRouter = new GameSceneRouter();
sceneRouter.start(GameSceneType.MainMenu);
sceneRouter.transitionStarted.addListener(() => {
collisionSystem.reset();
});
const debugInspector = new DebugInspector(gameRenderer.getDomElement());
debugInspector.listen();
debugInspector.click.addListener((position: Vector) => {
const intersections: GameObject[] = [];
const scene = sceneRouter.getCurrentScene();
scene.getRoot().traverseDescedants((child) => {
if (child.getWorldBoundingBox().containsPoint(position)) {
intersections.push(child);
}
});
log.debug(intersections);
});
const gameState = new State<GameState>(GameState.Playing);
const updateArgs: GameUpdateArgs = {
audioManager,
audioLoader,
collisionSystem,
colorSpriteFontGenerator,
deltaTime: 0,
gameStorage,
imageLoader,
inputHintSettings,
inputManager,
gameState,
mapLoader,
pointsHighscoreManager,
rectFontLoader,
session,
spriteFontLoader,
spriteLoader,
};
const gameLoop = new GameLoop();
const stats = new Stats();
const debugGameLoopMenu = new DebugGameLoopMenu(gameLoop);
if (config.IS_DEV) {
document.body.appendChild(stats.dom);
debugGameLoopMenu.attach();
}
gameLoop.tick.addListener((event) => {
stats.begin();
inputManager.update();
updateArgs.deltaTime = event.deltaTime;
const scene = sceneRouter.getCurrentScene();
scene.invokeUpdate(updateArgs);
gameRenderer.render(scene.getRoot());
gameState.update();
stats.end();
});
async function main(): Promise<void> {
log.time('Audio preload');
loadingElement.textContent = 'Loading audio...';
await audioLoader.preloadAllAsync();
log.timeEnd('Audio preload');
log.time('Rect font preload');
loadingElement.textContent = 'Loading rects fonts...';
await rectFontLoader.preloadAll();
log.timeEnd('Rect font preload');
log.time('Sprite font preload');
loadingElement.textContent = 'Loading sprite fonts...';
await spriteFontLoader.preloadAllAsync();
log.timeEnd('Sprite font preload');
log.time('Color sprite font generation');
loadingElement.textContent = 'Generating sprite font colors...';
colorSpriteFontGenerator.generate(
config.PRIMARY_SPRITE_FONT_ID,
config.COLOR_WHITE,
);
colorSpriteFontGenerator.generate(
config.PRIMARY_SPRITE_FONT_ID,
config.COLOR_GRAY,
);
colorSpriteFontGenerator.generate(
config.PRIMARY_SPRITE_FONT_ID,
config.COLOR_RED,
);
colorSpriteFontGenerator.generate(
config.PRIMARY_SPRITE_FONT_ID,
config.COLOR_YELLOW,
);
log.timeEnd('Color sprite font generation');
log.time('Sprites preload');
loadingElement.textContent = 'Loading sprites...';
await spriteLoader.preloadAllAsync();
log.timeEnd('Sprites preload');
log.time('Input bindings load');
loadingElement.textContent = 'Loading input bindings...';
inputManager.loadAllBindings();
log.timeEnd('Input bindings load');
document.body.removeChild(loadingElement);
document.body.appendChild(gameRenderer.getDomElement());
gameLoop.start();
// gameLoop.next();
}
main();
if (config.IS_DEV) {
window.gameLoop = gameLoop;
}
|
import FPop from '../components/pop'
import { sumArray } from '../shared/utils'
import { xmatrix,ymatrix} from '../shared/popover'
export default {
beforeMount(el:HTMLElement,binding:any){
const {arg,value} = binding
let lock = false
el.addEventListener(arg,()=>{
if(lock)return
lock = true
const {left,top,width,height} = el.getBoundingClientRect()
const {title,position,theme,done,cancel} = value as {
title:string,
position?:string,
theme?:'normal'|'reverse',
done?:()=>void,
cancel?:()=>void
}
const pos = position||"tc"
const
x = sumArray(xmatrix[pos],[left,top,width,height]),
y = sumArray(ymatrix[pos],[left,top,width,height]);
const noop = ()=>void(0)
FPop.showConfirm({title,x,y,theme,position:pos as 'tc'}).done(done||noop).cancel(cancel||noop);
setTimeout(()=>{
lock = false
},300)
})
}
} |
<filename>keras/mlp_mixer_imagenet_pretrain_embeddings.py
import numpy as np
import tensorflow as tf
import keras
import time
import sys
import os
import tensorflow.keras.layers.experimental.preprocessing as preprocessing
pretrained_path = sys.argv[1]
train_data_path = sys.argv[2]
npy_save_file = sys.argv[3]
# MLP Block
def MlpBlock(input_dim: int, hidden_dim: int, pretrained_params, inputs):
dense_0 = tf.keras.layers.Dense(hidden_dim, activation='gelu')
x = dense_0(inputs)
dense_1 = tf.keras.layers.Dense(input_dim)
outputs = dense_1(x)
if pretrained_params is not None:
dense_params_0 = pretrained_params['Dense_0']
dense_0.set_weights([dense_params_0['kernel'], dense_params_0['bias']])
dense_0.trainable = False
dense_params_1 = pretrained_params['Dense_1']
dense_1.set_weights([dense_params_1['kernel'], dense_params_1['bias']])
dense_1.trainable = False
return outputs
# Mixer Block
def MixerBlock(n_tokens: int, n_channels: int, token_mixer_hidden_dim: int, channel_mixer_hidden_dim, pretrained_params, inputs):
# inputs = tf.keras.Input(shape=(n_channels, n_tokens))
layer_norm_0 = tf.keras.layers.LayerNormalization()
y = layer_norm_0(inputs)
if pretrained_params is not None:
layer_params_0 = pretrained_params['LayerNorm_0']
layer_norm_0.set_weights([layer_params_0['scale'], layer_params_0['bias']])
layer_norm_0.trainable = False
y = tf.keras.layers.Permute((2, 1))(y)
# batch_size = y.shape[0]
y = tf.reshape(y, (-1, n_tokens))
token_mixer_params = pretrained_params['token_mixing'] if pretrained_params is not None else None
y = MlpBlock(n_tokens, token_mixer_hidden_dim, token_mixer_params, y)
y = tf.reshape(y, (-1, n_channels, n_tokens))
y = tf.keras.layers.Permute((2, 1))(y)
x = tf.keras.layers.Add()([inputs, y])
layer_norm_1 = tf.keras.layers.LayerNormalization()
y = layer_norm_1(x);
if pretrained_params is not None:
layer_params_1 = pretrained_params['LayerNorm_1']
layer_norm_1.set_weights([layer_params_1['scale'], layer_params_1['bias']])
layer_norm_1.trainable = False
y = tf.reshape(y, (-1, n_channels))
channel_mixer_params = pretrained_params['channel_mixing'] if pretrained_params is not None else None
y = MlpBlock(n_channels, channel_mixer_hidden_dim, channel_mixer_params, y)
y = tf.reshape(y, (-1, n_tokens, n_channels))
outputs = tf.keras.layers.Add()([x, y])
return outputs
# return tf.keras.Model(inputs, outputs)
def PatchAndProject(n_channels: int, patch_width: int, pretrained_params, inputs):
conv = tf.keras.layers.Conv2D(n_channels, patch_width, strides=patch_width)
outputs = conv(inputs)
if pretrained_params is not None:
conv.set_weights([pretrained_params['kernel'], pretrained_params['bias']])
conv.trainable = False
return outputs
def MlpMixer(
patch_width: int,
image_width: int,
n_input_channels: int,
n_channels: int,
n_classes: int,
n_mixer_blocks: int,
token_mixer_hidden_dim: int,
channel_mixer_hidden_dim: int,
pretrained_params
):
n_patches_side = int(image_width / patch_width)
n_patches = int(n_patches_side ** 2)
inputs = tf.keras.layers.Input([image_width,image_width,n_input_channels])
# Normal mixer
patch_and_project_params = pretrained_params['stem'] if pretrained_params is not None else None
h = PatchAndProject(n_channels, patch_width, patch_and_project_params, inputs)
h = tf.reshape(h, (-1, n_patches, n_channels))
for i in range(n_mixer_blocks):
mixer_block_params = pretrained_params[f'MixerBlock_{i}'] if pretrained_params is not None else None
h = MixerBlock(n_patches, n_channels, token_mixer_hidden_dim, channel_mixer_hidden_dim, mixer_block_params, h)
layer_norm = tf.keras.layers.LayerNormalization()
h = layer_norm(h)
if pretrained_params is not None:
layer_norm_params = pretrained_params['pre_head_layer_norm']
layer_norm.set_weights([layer_norm_params['scale'], layer_norm_params['bias']])
layer_norm.trainable = False
outputs = tf.keras.layers.GlobalAveragePooling1D(data_format="channels_last")(h)
return tf.keras.Model(inputs, outputs)
model = MlpMixer(filter_size, img_shape, n_channels, n_embedding_channels, n_classes, n_mixer_blocks, token_mixer_hidden_dim, channel_mixer_hidden_dim, pretrained_params=params)
params = np.load(pretrained_path, allow_pickle=True)[()]
filter_size = 16
n_channels = 3
n_embedding_channels = 768
feat_hash_dim = 100000 # for each patch separately
batch_size = 64
img_shape = 224
n_patches = (img_shape**2)//(filter_size**2)
top_k = 5 # per patch non-zeros
n_classes = 325
n_mixer_blocks = 12
token_mixer_hidden_dim = 384
channel_mixer_hidden_dim = 3072
train_data = tf.keras.preprocessing.image_dataset_from_directory(
directory=train_data_path,
labels="inferred",
label_mode="int",
class_names=None,
color_mode="rgb",
batch_size=batch_size, #TODO: CHANGE TO 100K if not datagen!!!
image_size=(img_shape, img_shape),
shuffle=True,
seed=None,
validation_split=None,
subset=None,
interpolation="bilinear",
follow_links=False,
crop_to_aspect_ratio=False,
)
train_data_for_datagen = tf.keras.preprocessing.image_dataset_from_directory(
directory=train_data_path,
labels="inferred",
label_mode="int",
class_names=None,
color_mode="rgb",
batch_size=100000, #TODO: CHANGE TO 100K if not datagen!!!
image_size=(img_shape, img_shape),
shuffle=True,
seed=None,
validation_split=None,
subset=None,
interpolation="bilinear",
follow_links=False,
crop_to_aspect_ratio=False,
)
for batch in train_data_for_datagen:
x_train, y_train = batch
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
# samplewise_center=True,
# samplewise_std_normalization=True,
# rotation_range=90,
# width_shift_range=0.4,
# height_shift_range=0.4,
brightness_range=(0.6, 1.2),
# shear_range=0.2,
zoom_range=0.3,
channel_shift_range=10.0,
horizontal_flip=True,
vertical_flip=True,
)
outputs = np.ndarray([0, n_embedding_channels])
for batch in train_data:
x = (batch[0] - 127.5) / 127.5
new_output = model(x)
np.append(outputs, new_output, 0)
print(outputs.shape)
for batch in datagen.flow(x_train, y_train, batch_size=batch_size):
x = (batch[0] - 127.5) / 127.5
new_output = model(x)
np.append(outputs, new_output, 0)
print(outputs.shape)
np.save(npy_save_file, outputs) |
<gh_stars>1-10
package elasta.composer.impl;
import com.google.common.collect.ImmutableMap;
import elasta.composer.MsgEnterEventHandlerP;
import elasta.composer.StateHandlersMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Created by sohan on 7/7/2017.
*/
final public class StateHandlersMapImpl implements StateHandlersMap {
final Map<Class, MsgEnterEventHandlerP> map;
public StateHandlersMapImpl(Map<Class, MsgEnterEventHandlerP> map) {
Objects.requireNonNull(map);
this.map = ImmutableMap.copyOf(map);
}
@Override
public <T extends MsgEnterEventHandlerP<P, R>, P, R> Optional<T> get(Class<T> tClass) {
return Optional.ofNullable(
(T) map.get(tClass)
);
}
@Override
public Set<Class> keys() {
return map.keySet();
}
@Override
public Map<Class, MsgEnterEventHandlerP> getMap() {
return map;
}
}
|
package com.ty.fm.models;
public class RelationshipLineRoutePattern
{
}
|
<gh_stars>0
# ~*~ encoding: utf-8 ~*~
require 'pathname'
module Gollum
module MarkupRegisterUtils
# Check if a gem exists. This implementation requires Gem::Specificaton to
# be filled.
def gem_exists?(name)
Gem::Specification.find {|spec| spec.name == name} != nil
end
def all_gems_available?(names)
names.each do |name|
return false unless gem_exists?(name)
end
true
end
# Check if an executable exists. This implementation comes from
# stackoverflow question 2108727.
def executable_exists?(name)
exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") : [""]
paths = ENV["PATH"].split(::File::PATH_SEPARATOR)
paths.each do |path|
exts.each do |ext|
exe = Pathname(path) + "#{name}#{ext}"
return true if exe.executable?
end
end
return false
end
# Whether the current markdown renderer is pandoc
def using_pandoc?
GitHub::Markup::Markdown.implementation_name == 'pandoc-ruby'
end
end
end
include Gollum::MarkupRegisterUtils
module GitHub
module Markup
class Markdown < Implementation
class << self
def implementation_name
@implementation_name ||= MARKDOWN_GEMS.keys.detect {|gem_name| self.new.send(:try_require, gem_name) }
end
end
end
end
end
module Gollum
class Markup
if gem_exists?('pandoc-ruby')
GitHub::Markup::Markdown::MARKDOWN_GEMS.delete('kramdown')
GitHub::Markup::Markdown::MARKDOWN_GEMS['pandoc-ruby'] = proc { |content|
PandocRuby.convert(content, :from => :markdown, :to => :html, :filter => 'pandoc-citeproc')
}
else
GitHub::Markup::Markdown::MARKDOWN_GEMS['kramdown'] = proc { |content|
Kramdown::Document.new(content, :input => "GFM", :hard_wrap => 'false', :auto_ids => false, :math_engine => nil, :smart_quotes => ["'", "'", '"', '"'].map{|char| char.codepoints.first}).to_html
}
end
# markdown, rdoc, and plain text are always supported.
register(:markdown, "Markdown", :extensions => ['md','mkd','mkdn','mdown','markdown'])
register(:rdoc, "RDoc")
register(:txt, "Plain Text",
:skip_filters => Proc.new {|filter| ![:PlainText,:YAML].include?(filter) })
# the following formats are available only when certain gem is installed
# or certain program exists.
register(:textile, "Textile",
:enabled => MarkupRegisterUtils::gem_exists?("RedCloth"))
register(:org, "Org-mode",
:enabled => MarkupRegisterUtils::gem_exists?("org-ruby"))
register(:creole, "Creole",
:enabled => MarkupRegisterUtils::gem_exists?("creole"),
:reverse_links => true)
register(:rst, "reStructuredText",
:enabled => MarkupRegisterUtils::executable_exists?("python2"),
:extensions => ['rest', 'rst'])
register(:asciidoc, "AsciiDoc",
:skip_filters => [:Tags],
:enabled => MarkupRegisterUtils::gem_exists?("asciidoctor"),
:extensions => ['adoc','asciidoc'])
register(:mediawiki, "MediaWiki",
:enabled => MarkupRegisterUtils::gem_exists?("wikicloth"),
:extensions => ['mediawiki','wiki'], :reverse_links => true)
register(:pod, "Pod",
:enabled => MarkupRegisterUtils::executable_exists?("perl"))
register(:bib, "BibTeX", :extensions => ['bib'],
:enabled => MarkupRegisterUtils::all_gems_available?(["bibtex-ruby", "citeproc-ruby", "csl"]),
:skip_filters => Proc.new {|filter| true unless [:YAML,:BibTeX,:Sanitize].include?(filter)})
end
end
|
<reponame>mol42/rn-animations<gh_stars>0
import React, {Component} from 'react';
import {View, Animated, StyleSheet} from 'react-native';
export default class InterpolationExample extends Component {
constructor(props) {
super(props);
this.state = {
startValue: new Animated.Value(0),
endValue: 1,
duration: 5000,
};
}
componentDidMount() {
Animated.timing(this.state.startValue, {
toValue: this.state.endValue,
duration: this.state.duration,
useNativeDriver: true,
}).start();
}
render() {
return (
<View style={styles.container}>
{/*
<View komponentini anime etmek istersek "Attempted to assign to readonly property" hatasi aliriz
cunku anime edilebilir view'lar icin RN ekstra ayarlamalar yapmaktadir.
*/}
<Animated.View
style={[
styles.square,
{
opacity: this.state.startValue,
transform: [
{
translateY: this.state.startValue.interpolate({
inputRange: [0, 1],
outputRange: [300, 0], // 0 : 150, 0.5 : 75, 1 : 0
}),
},
],
},
]}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
},
square: {
height: 50,
width: 50,
backgroundColor: 'green',
},
}); |
$(document).ready(function () {
var inputGet = $("#input_get");
var inputRawGet = $("#input_raw_get");
inputGet.click(getMessage);
inputRawGet.click(getRawMessage);
function getMessage() {
$.get("test/message", function (data, err) {
console.log("get data: " + data);
protobuf.load("proto/message.proto", function (err, root) {
if (err) {
console.error(err);
throw err;
}
var message = root.lookupType("Person");
var array = JSON.parse(data);
var test = Uint8Array.from(array);
var result = message.decode(test);
console.log("result: " + JSON.stringify(result));
});
});
}
function getRawMessage() {
var url = "fakeData/protobuff/price2.txt";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (ev) {
var responseArray = new Uint8Array(this.response);
protobuf.load("proto/best_price.proto", function (err, root) {
if (err) {
console.error(err);
throw err;
}
var message = root.lookupType("BestPriceList");
var result = message.decode(responseArray);
console.log("result: " + JSON.stringify(result));
});
};
xhr.send();
}
});
|
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100, required=True)
place = forms.CharField(max_length=20)
email = forms.EmailField(required=True)
phone = forms.CharField(max_length=13)
message = forms.CharField(max_length=1000, required=True, widget=forms.Textarea) |
/*=============================================================================
Copyright (c) 2014-2020 <NAME>. All rights reserved.
Distributed under the MIT License [ https://opensource.org/licenses/MIT ]
=============================================================================*/
#define CATCH_CONFIG_MAIN
#include <infra/catch.hpp>
#include <q/support/literals.hpp>
#include <q/pitch/pitch_detector.hpp>
#include <vector>
#include <iostream>
#include "notes.hpp"
namespace q = cycfi::q;
using namespace q::literals;
using std::fixed;
constexpr auto pi = q::pi;
constexpr auto sps = 44100;
// Set this to 1 or 2 if you want verbose print outs
constexpr auto verbosity = 0;
struct test_result
{
float ave_error = 0.0f;
float min_error = 100.0f;
float max_error = 0.0f;
};
test_result process(
std::vector<float>&& in
, q::frequency actual_frequency
, q::frequency lowest_freq
, q::frequency highest_freq
, std::string name = "")
{
if (verbosity > 1)
std::cout << fixed << "Actual Frequency: "
<< double(actual_frequency) << std::endl;
if (name.empty())
name = std::to_string(int(double(actual_frequency)));
////////////////////////////////////////////////////////////////////////////
// Process
q::pitch_detector pd(lowest_freq, highest_freq, sps, -45_dB);
auto result = test_result{};
auto frames = 0;
for (auto i = 0; i != in.size(); ++i)
{
auto s = in[i];
// Period Detection
bool is_ready = pd(s);
if (is_ready)
{
auto frequency = pd.get_frequency();
if (frequency != 0.0f)
{
auto error = 1200.0 * std::log2(frequency / double(actual_frequency));
if (verbosity > 1)
{
std::cout
<< fixed
<< frequency
<< " Error: "
<< error
<< " cent(s)."
<< std::endl
;
}
result.ave_error += std::abs(error);
++frames;
result.min_error = std::min<float>(result.min_error, std::abs(error));
result.max_error = std::max<float>(result.max_error, std::abs(error));
}
}
}
result.ave_error /= frames;
return result;
}
struct params
{
float _offset = 0.0f; // Waveform offset
float _2nd_harmonic = 2.0f; // Second harmonic multiple
float _3rd_harmonic = 3.0f; // Second harmonic multiple
float _1st_level = 0.3f; // Fundamental level
float _2nd_level = 0.4f; // Second harmonic level
float _3rd_level = 0.3f; // Third harmonic level
float _1st_offset = 0.0f; // Fundamental phase offset
float _2nd_offset = 0.0f; // Second harmonic phase offset
float _3rd_offset = 0.0f; // Third harmonic phase offset
};
std::vector<float>
gen_harmonics(q::frequency freq, params const& params_)
{
auto period = double(sps / freq);
float offset = params_._offset;
std::size_t buff_size = sps; // 1 second
std::vector<float> signal(buff_size);
for (int i = 0; i < buff_size; i++)
{
auto angle = (i + offset) / period;
signal[i] += params_._1st_level
* std::sin(2 * pi * (angle + params_._1st_offset));
signal[i] += params_._2nd_level
* std::sin(params_._2nd_harmonic * 2 * pi * (angle + params_._2nd_offset));
signal[i] += params_._3rd_level
* std::sin(params_._3rd_harmonic * 2 * pi * (angle + params_._3rd_offset));
}
return signal;
}
float max_error = 0.01; // 1% error or error
void check(float x, float expected, char const* what)
{
if (x == 0 && expected == 0)
return;
auto error_percent = max_error * 100;
auto error_threshold = expected * max_error;
{
INFO(
what
<< " exceeded "
<< error_percent
<< "%. Got: "
<< x
<< ", Expecting: ("
<< (expected - error_threshold)
<< "..."
<< (expected + error_threshold)
<< ')'
);
CHECK(x < (expected + error_threshold));
}
}
void process(
params const& params_
, q::frequency actual_frequency
, q::frequency lowest_freq
, q::frequency highest_freq
, double ave_error_expected
, double min_error_expected
, double max_error_expected
, std::string name = ""
)
{
auto result = process(
gen_harmonics(actual_frequency, params_)
, actual_frequency, lowest_freq, highest_freq, name
);
if (verbosity > 0)
{
std::cout << fixed << "Average Error: " << result.ave_error << " cent(s)." << std::endl;
std::cout << fixed << "Min Error: " << result.min_error << " cent(s)." << std::endl;
std::cout << fixed << "Max Error: " << result.max_error << " cent(s)." << std::endl;
}
check(result.ave_error, ave_error_expected, "Average error");
check(result.min_error, min_error_expected, "Minimum error");
check(result.max_error, max_error_expected, "Maximum error");
}
void process(
params const& params_
, q::frequency actual_frequency
, q::frequency lowest_freq
, double ave_error_expected = 0.01
, double min_error_expected = 0.01
, double max_error_expected = 0.01
, std::string name = ""
)
{
process(
params_, actual_frequency, lowest_freq * 0.8, lowest_freq * 5
, ave_error_expected, min_error_expected, max_error_expected, name
);
}
void process(
params const& params_
, q::frequency actual_frequency
, q::frequency lowest_freq
, std::string name
)
{
process(
params_, actual_frequency, lowest_freq * 0.8, lowest_freq * 5
, 0.01, 0.01, 0.01, name
);
}
using namespace notes;
TEST_CASE("Test_middle_C")
{
process(params{}, middle_c, 200_Hz);
}
TEST_CASE("Test_middle_A")
{
process(params{}, 440_Hz, 200_Hz);
}
TEST_CASE("Test_low_E")
{
process(params{}, low_e, low_e);
}
TEST_CASE("Test_E_12th")
{
process(params{}, low_e_12th, low_e);
}
TEST_CASE("Test_E_24th")
{
process(params{}, low_e_24th, low_e, "low_e_24th");
}
TEST_CASE("Test_A")
{
process(params{}, a, a);
}
TEST_CASE("Test_A_12th")
{
process(params{}, a_12th, a);
}
TEST_CASE("Test_A_24th")
{
process(params{}, a_24th, a);
}
TEST_CASE("Test_D")
{
process(params{}, d, d);
}
TEST_CASE("Test_D_12th")
{
process(params{}, d_12th, d);
}
TEST_CASE("Test_D_24th")
{
process(params{}, d_24th, d);
}
TEST_CASE("Test_G")
{
process(params{}, g, g);
}
TEST_CASE("Test_G_12th")
{
process(params{}, g_12th, g);
}
TEST_CASE("Test_G_24th")
{
process(params{}, g_24th, g, 0.01517, 0.01, 0.0343084);
}
TEST_CASE("Test_B")
{
process(params{}, b, b);
}
TEST_CASE("Test_B_12th")
{
process(params{}, b_12th, b, 0.01, 0.01, 0.016048);
}
TEST_CASE("Test_B_24th")
{
process(params{}, b_24th, b, 0.0363396, 0.01, 0.100026);
}
TEST_CASE("Test_high_E")
{
process(params{}, high_e, high_e);
}
TEST_CASE("Test_high_E_12th")
{
process(params{}, high_e_12th, high_e, 0.01, 0.01, 0.0133378);
}
TEST_CASE("Test_high_E_24th")
{
process(params{}, high_e_24th, high_e, 0.023045, 0.01, 0.0649471);
}
TEST_CASE("Test_non_integer_harmonics")
{
params params_;
params_._2nd_harmonic = 2.003;
process(params_, low_e, low_e, 1.025, 0.951, 1.12708, "non_integer");
}
TEST_CASE("Test_phase_offsets")
{
params params_;
params_._1st_offset = 0.1;
params_._2nd_offset = 0.5;
params_._3rd_offset = 0.4;
process(params_, low_e, low_e, "phase_offset");
}
TEST_CASE("Test_missing_fundamental")
{
params params_;
params_._1st_level = 0.0;
params_._2nd_level = 0.5;
params_._3rd_level = 0.5;
process(params_, low_e, low_e, "missing_fundamental");
}
|
export namespace JsonFormConstants {
export const VALID_TYPES = ['string', 'number', 'integer'];
export const FORMAT_DATE = 'date-time';
}
|
#!/bin/bash
clear
echo "Setting up serives..."
echo "Downloading required necessary packages"
sudo apt install ffmpeg -y
echo "Setting up config files..."
cat <<EOT >> /usr/local/bin/startmic
echo "Starting Audio input service..."
echo ""
echo "Make sure you have started the server from the app with following config"
echo ""
echo "---------------------------"
echo " |"
echo " TARGET ADDRESS: 127.0.0.1|"
echo " TARGET PORT: 55555 |"
echo " MODE: Manual |"
echo " FORMAT: G.722 |"
echo " |"
echo "---------------------------"
echo ""
ffplay -i rtp://@127.0.0.1:55555 > output.log 2>&1 < /dev/null &
echo ""
echo " Black window will popup if Audio Input has been enabled"
echo " To stop audio input close the window"
echo "If no window pops up check you have started server with proper config"
echo "Also open new Termux session and type pluseaudio --start"
EOT
chmod +x /usr/local/bin/startmic
echo "To start the mic input next time type: startmic"
|
<filename>project/plugins.sbt
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.7.0")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "0.3.2")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.1")
|
/* eslint-disable import/no-unresolved */
import validate from '@functions/transfer/transfer/validate';
import faker from 'faker';
describe('#validate', () => {
describe('when a schema is valid', () => {
const data = [
{
bucket: faker.random.word(),
prefix: '/some/random/key',
roleArn: {
'Fn::GetParam': ['DeployOutput', 'Outputs.json', 'S3BucketKey'],
},
src: ['BuildOutput::out/**/*.png'],
},
];
it('resolves with the correct object', () =>
expect(validate(data)).resolves.toMatchObject(data));
});
describe('when a schema is invalid', () => {
it('rejects on empty schema', () => expect(validate({})).rejects.toEqual(expect.any(Error)));
});
});
|
#!/bin/bash
# Exit on error
set -e
# Setup code goes here
test -e $MRT_MARIAN/mnist_example
test -e $MRT_DATA/exdb_mnist/train-images-idx3-ubyte
test -e $MRT_DATA/exdb_mnist/train-labels-idx1-ubyte
test -e $MRT_DATA/exdb_mnist/t10k-images-idx3-ubyte
test -e $MRT_DATA/exdb_mnist/t10k-labels-idx1-ubyte
test -e *-ubyte || cp $MRT_DATA/exdb_mnist/*-ubyte .
# Exit with success code
exit 0
|
<reponame>isabella232/whimsy
#!/usr/bin/env ruby
$LOAD_PATH.unshift '/srv/whimsy/lib'
=begin
APP to generate the correct ezmlm syntax for moderators
=end
require 'wunderbar'
require 'wunderbar/bootstrap'
require 'whimsy/asf'
_html do
# ensure the generated text is selected ready for copy-pasting
_script %{
window.onload=function() {
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
var dest = document.getElementById('dest');
range.selectNodeContents(dest);
sel.addRange(range);
// TODO auto copy to clipboard (tricky)
}
}
_body? do
_whimsy_body(
title: 'Mail List Moderation Helper',
subtitle: 'How-To Use Moderator Commands',
related: {
'https://www.apache.org/foundation/mailinglists.html' => 'Apache Mailing List Info Page',
'https://lists.apache.org' => 'Apache Mailing List Archives',
'/committers/subscribe.cgi' => 'Mailing List Subscription Helper',
'http://www.apache.org/foundation/mailinglists.html#subscribing' => 'Information on Subscribing/Unsubscribing',
'http://apache.org/dev/committers.html#mail-moderate' => 'Guide for moderators',
'http://apache.org/dev/committers.html#problem_posts' => 'Guide for moderators - dealing with problem posts',
'http://untroubled.org/ezmlm/manual/Sending-commands.html#Sending-commands' => 'EZMLM Command Help',
'https://issues.apache.org/jira/browse/INFRA-10476' => 'INFRA-10476 - Provide a way to force specific subscribers to be moderated'
},
helpblock: -> {
_p 'This form generates ezmlm mailing list addresses for various moderator requests.'
_p do
_ 'Enter the ASF mailing list name, select the operation to perform, and enter a subscriber email (if needed).'
_br
_ 'Press Generate. The To: address below can be copy/pasted into an email to send. In most cases you must be a moderator for that list.'
_br
_span.text_danger 'Note that you must send the email from the address which is registered as a moderator.'
end
_p do
_ul do
_li 'subscribers can post and will receive mail'
_li 'allow-subscribers can post; they do not get copies of mails (this is used for e.g. press@. Also useful for bots.)'
_li 'deny-subscribers cannot post; their posts will be rejected without needing moderation'
_li 'sendsubscribertomod-subscribers will have all posts moderated (for posters who are borderline problems) - ask INFRA to enable the setting for the list'
end
end
_p do
_span.text_danger 'BETA SOFTWARE: double-check the command first. '
_a "Feedback welcome!", href: "mailto:<EMAIL>?Subject=Feedback on moderation helper app"
end
_p do
_span '** If you are not a moderator, you can contact them by emailing <<EMAIL> **'
end
}
) do
_form method: 'post' do
_fieldset do
_table do
_tr do
_th 'Mailing list'
_th 'Subscriber'
end
_tr do
_td do
_input.name name: 'maillist', size: 40, pattern: '[^@]+@([-\w]+)?', required: true, value: @maillist,
placeholder: 'user@project or announce@'
_ '.apache.org '
end
_td do
_input.name name: 'email', size: 40, pattern: '[^@]+@[^@]+', value: @email, placeholder: '<EMAIL>'
end
end
_tr do
_td ''
_td do
_p do
_b 'WARNING'
_ 'Some providers are known to block our emails as SPAM.'
_br
_ 'Please see the following for details: '
_a 'email provider issues', href: '../commiters/emailissues', target: '_blank'
_ ' (opens in new page)'
end
end
end
_tr do
_td {
_br
_p 'The following commands operate on the list only:'
}
_td {
_br
_p 'The following commands also require a subscriber email address:'
}
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "list", required: true, checked: (@cmd == "list")
_ 'list (current subscribers)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "subscribe", required: true, checked: (@cmd == "subscribe")
_ 'subscribe (normal subscription: can post and gets messages)'
end
end
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "log", required: true, checked: (@cmd == "log")
_ 'log (history of subscription changes)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "unsubscribe", required: true, checked: (@cmd == "unsubscribe" || @cmd == nil)
_ 'unsubscribe (from list)'
end
end
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "allow-list", required: true, checked: (@cmd == "allow-list")
_ 'allow-list (currently allowed to post)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "allow-subscribe", required: true, checked: (@cmd == "allow-subscribe")
_ 'allow-subscribe (allow posting without getting messages - e.g. for bots)'
end
end
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "allow-log", required: true, checked: (@cmd == "allow-log")
_ 'allow-log (history of subscriptions to allow list)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "allow-unsubscribe", required: true, checked: (@cmd == "allow-unsubscribe")
_ 'allow-unsubscribe (drop allow posting)'
end
end
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "deny-list", required: true, checked: (@cmd == "deny-list")
_ 'deny-list (list those currently denied to post)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "deny-subscribe", required: true, checked: (@cmd == "deny-subscribe")
_ 'deny-subscribe (prevent subscriber from posting)'
end
end
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "deny-log", required: true, checked: (@cmd == "deny-log")
_ 'deny-log (history of deny subscriptions)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "deny-unsubscribe", required: true, checked: (@cmd == "deny-unsubscribe")
_ 'deny-unsubscribe (remove from list of denied posters)'
end
end
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "sendsubscribertomod-list", required: true, checked: (@cmd == "sendsubscribertomod-subscribe")
_ 'sendsubscribertomod-list (list of moderated subscribers)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "sendsubscribertomod-subscribe", required: true, checked: (@cmd == "sendsubscribertomod-subscribe")
_ 'sendsubscribertomod-subscribe (add to list of moderated subscribers - ask INFRA to enable this for the list)'
end
end
end
_tr do
_td do
_label do
_input type: "radio", name: "cmd", value: "sendsubscribertomod-log", required: true, checked: (@cmd == "sendsubscribertomod-subscribe")
_ 'sendsubscribertomod-log (history of moderated subscribers)'
end
end
_td do
_label do
_input type: "radio", name: "cmd", value: "sendsubscribertomod-unsubscribe", required: true, checked: (@cmd == "sendsubscribertomod-unsubscribe")
_ 'sendsubscribertomod-unsubscribe (remove from list of moderated subscribers)'
end
end
end
end
_p {
_br
_input type: 'submit', value: 'Generate'
}
end
end
if _.post?
_div.well do
ml0,ml1 = @maillist.split('@')
if ml1
# enable escape for apachecon.com
ml1 += '.apache.org' unless ml1 =~ /\.(org|com)$/
else
ml1 = 'apache.org'
end
em = @email.split('@')
_br
if @cmd.end_with? 'subscribe' # also catches unsubscribe
unless @email.length > 0
_h3.error 'Need subscriber email address'
break
end
dest = "#{ml0}-#{@cmd}-#{em[0]}=#{em[1]}@#{ml1}"
else
dest = "#{ml0}-#{@cmd}@#{ml1}"
end
_span 'Copy this email address: '
_span.dest! dest
_br
_br
_a 'or Click to Send Mail', href: "mailto:#{dest}?Subject=#{dest}"
end
end
end
end
end
|
<filename>server/limiter.go<gh_stars>0
package server
/*
* mimi
*
* Copyright (c) 2018 beito
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
**/
import (
"net"
"time"
)
type Addr struct {
IP net.IP
Counter int
LastTime time.Time
Blocked bool
BlockedTime time.Time
}
type Limiter struct {
Addrs []*Addr
BlockExpire time.Duration
MaxCount int
lastUpdateTime time.Time
}
func (hand *Limiter) Update() {
now := time.Now()
if now.Sub(hand.lastUpdateTime) > time.Second*1 {
new := make([]*Addr, 0)
for _, addr := range hand.Addrs {
if addr.Counter > hand.MaxCount {
hand.SetBlock(addr.IP, true)
}
addr.Counter = 0
if addr.Blocked {
if now.Sub(addr.BlockedTime) < hand.BlockExpire {
new = append(new, addr)
}
}
}
hand.Addrs = new
hand.lastUpdateTime = now
}
}
func (hand *Limiter) AddAddr(ip net.IP) {
hand.Addrs = append(hand.Addrs, &Addr{
IP: ip,
})
}
func (hand *Limiter) getAddr(ip net.IP) *Addr {
for _, addr := range hand.Addrs {
if addr.IP.Equal(ip) {
return addr
}
}
return nil
}
func (hand *Limiter) HasAddr(ip net.IP) bool {
return hand.getAddr(ip) != nil
}
func (hand *Limiter) IsBlocked(ip net.IP) bool {
addr := hand.getAddr(ip)
return addr.Blocked
}
func (hand *Limiter) SetBlock(ip net.IP, b bool) {
addr := hand.getAddr(ip)
if addr != nil {
addr.Blocked = b
if b {
addr.BlockedTime = time.Now()
}
}
}
func (hand *Limiter) Check(ip net.IP) (bool, error) {
hand.Update()
if !hand.HasAddr(ip) {
hand.AddAddr(ip)
}
addr := hand.getAddr(ip)
if addr.Blocked {
return false, nil
}
addr.Counter++
return true, nil
}
|
#!/bin/bash
set -e
for dir in simple subdirs separatedirs ; do
pushd ${dir}
debos --disable-fakemachine main.yaml
popd
done
|
#!/bin/bash
#
# Demo of the bash completion API.
#
# It's used by core/completion_test.py, and you can run it manually.
#
# The reason we use unit tests is that some of the postprocessing in GNU
# readline is untestable from the "outside".
#
# Usage:
# source testdata/completion/osh-unit.bash
# For testing if ls completion works AUTOMATICALLY
complete -W 'one two' ls
alias ll='ls -l'
alias ll_classify='ll --classify' # a second level of alias expansion
alias ll_trailing='ls -l ' # trailing space shouldn't make a difference
alias ll_own_completion='ls -l'
complete -W 'own words' ll_own_completion
argv() {
spec/bin/argv.py "$@"
}
# Complete a fixed set of words
complete_mywords() {
local first=$1
local cur=$2
local prev=$3
for candidate in one two three bin; do
if [[ $candidate == $cur* ]]; then
COMPREPLY+=("$candidate")
fi
done
}
foo() { argv foo "$@"; }
complete_foo() {
local first=$1
local cur=$2
local prev=$3
echo
argv args "$@"
# NOTE: If you pass foo 'hi', then the words are quoted! This is a mistake!
# Also true for \hi and "hi".
# If you pass foo $x, you get literally $x as a word! It's BEFORE
# evaluation rather than AFTER evaluation!
#
# This is asking the completion function to do something impossible!!!
argv COMP_WORDS "${COMP_WORDS[@]}"
argv COMP_CWORD "${COMP_CWORD}"
argv COMP_LINE "${COMP_LINE}"
# Somehow completion doesn't trigger in the middle of a word, so this is
# always equal to ${#COMP_LINE} ?
argv COMP_POINT "${COMP_POINT}"
# This value is used in main bash_completion script.
argv source "${BASH_SOURCE[@]}"
argv 'source[0]' "${BASH_SOURCE[0]}"
# Test for prefix
# bin is a dir
for candidate in one two three bin; do
if [[ $candidate == $cur* ]]; then
COMPREPLY+=("$candidate")
fi
done
}
# dirnames: add dirs if nothing matches
# plusdirs: always add dirs
# filenames: adds trailing slash if it is a directory
complete -F complete_foo -o dirnames -o filenames foo
complete -F complete_foo -o nospace foo2
complete_filedir() {
local first=$1
local cur=$2
local prev=$3
COMPREPLY=( $( compgen -d "$cur" ) )
}
# from _filedir
complete -F complete_filedir filedir
complete_bug() {
# Regression for issue where readline swallows SystemExit.
comsub=$(echo comsub)
COMPREPLY=(one two three $comsub)
}
# isolated bug
complete -F complete_bug bug
complete_optdemo() {
local first=$1
local cur=$2
local prev=$3
# Dynamically set
#compopt -o nospace
# -o nospace doesn't work here, but it's accepted!
COMPREPLY=( $( compgen -o nospace -d "$cur" ) )
}
# Test how the options work. git uses nospace.
complete -F complete_optdemo -o nospace optdemo
optdynamic() { argv optdynamic "$@"; }
complete_optdynamic() {
local first=$1
local cur=$2
local prev=$3
# Suppress space on anything that starts with b
if [[ "$cur" == b* ]]; then
compopt -o nospace
fi
COMPREPLY=( $( compgen -A file "$cur" ) )
}
complete -F complete_optdynamic optdynamic
files_func() { argv "$@"; }
complete_files_func() {
local first=$1
local cur=$2
local prev=$3
# This MESSES up the trailing slashes. Need -o filenames.
COMPREPLY=( $( compgen -A file "$cur" ) )
}
# everything else completes files
#complete -D -A file
complete -F complete_files_func files_func # messes up trailing slashes
# Check trailing backslashes for the 'fileuser' command
# Hm somehow it knows to distinguish. Gah.
fu_builtin() { argv "$@"; }
complete -A user -A file fu_builtin
# This behaves the same way as above because of -o filenames.
# If you have both a dir and a user named root, it gets a trailing slash, which
# makes sense.
fu_func() { argv "$@"; }
complete_users_files() {
local first=$1
local cur=$2
COMPREPLY=( $( compgen -A user -A file "$cur" ) )
}
complete -F complete_users_files -o filenames fu_func
complete_op_chars() {
local first=$1
local cur=$2
for candidate in '$$$' '(((' '```' ';;;'; do
if [[ $candidate == $cur* ]]; then
COMPREPLY+=("$candidate")
fi
done
}
# Bash does NOT quote these! So they do not get sent into commands. It is
# conflating shell syntax and tool syntax.
op_chars() { argv "$@"; }
complete -F complete_op_chars op_chars
# Aha but this does the right thing! I think OSH should do this all the time!
# User-defined functions shouldn't be repsonsible for quoting.
op_chars_filenames() { argv "$@"; }
complete -F complete_op_chars -o filenames op_chars_filenames
# This shows that x is evaluated at RUNTIME, not at registration time!
W_runtime() { argv "$@"; }
complete -W 'foo $x $(echo --$x)' W_runtime
W_runtime_error() { argv "$@"; }
complete -W 'foo $(( 1 / 0 )) bar' W_runtime_error
F_runtime_error() { argv "$@"; }
complete_F_runtime_error() {
COMPREPLY=( foo bar )
COMPREPLY+=( $(( 1 / 0 )) ) # FATAL, but we still have candidates
}
complete -F complete_F_runtime_error F_runtime_error
#
# Test out the "124" protocol for lazy loading of completions.
#
# https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html
_completion_loader()
{
# If the file exists, we will return 124 and reload it.
# TODO: It would be nice to have a debug_f builtin to trace this!
. "testdata/completion/${1}_completion.bash" >/dev/null 2>&1 && return 124
}
complete -D -F _completion_loader
#
# Unit tests use this
#
# For testing interactively
flagX() { argv "$@"; }
flagX_bang() { argv "$@"; }
flagX_prefix() { argv "$@"; }
prefix_plusdirs() { argv "$@"; }
flagX_plusdirs() { argv "$@"; }
prefix_dirnames() { argv "$@"; }
complete -F complete_mywords mywords
complete -F complete_mywords -o nospace mywords_nospace
# This REMOVES two of them. 'three' should not be removed
# since it's not an exact match.
# Hm filtering comes BEFORE the prefix.
complete -X '@(two|bin|thre)' -F complete_mywords flagX
# Silly negation syntax
complete -X '!@(two|bin)' -F complete_mywords flagX_bang
complete -P __ -X '@(two|bin|thre)' -F complete_mywords flagX_prefix
complete -P __ -o plusdirs -F complete_mywords prefix_plusdirs
# Filter out bin, is it added back? Yes, it appears to work.
complete -X '@(two|bin)' -o plusdirs -F complete_mywords flagX_plusdirs
complete -P __ -o dirnames prefix_dirnames
|
class NamePredictionModel:
def __init__(self):
self._trained = False
def name(self):
"""Return name prediction column."""
return self._name
@property
def is_trained(self):
"""Check if the model is trained."""
return self._trained |
# relaunch DWM if the binary changes, otherwise bail
csum=""
new_csum=$(sha1sum $(which dwm))
while true
do
if [ "$csum" != "$new_csum" ]
then
csum=$new_csum
dwm
else
exit 0
fi
new_csum=$(sha1sum $(which dwm))
sleep 0.5
done |
# File: I (Python 2.4)
from direct.gui.DirectGui import *
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import *
from pirates.piratesgui import GuiPanel, PiratesGuiGlobals
from pirates.piratesbase import PiratesGlobals
from pirates.piratesbase import PLocalizer
from otp.otpbase import OTPLocalizer
from pirates.inventory.InventoryUIGlobals import *
from pirates.uberdog.UberDogGlobals import InventoryType
from pirates.inventory.InventoryGlobals import Locations
from pirates.inventory import ItemGlobals
from pirates.inventory import InventoryUISlotContainer
class InventoryUIClothingContainer(InventoryUISlotContainer.InventoryUISlotContainer):
def __init__(self, manager, sizeX = 1.0, sizeZ = 1.0, countX = 4, countZ = 4, slotList = None):
InventoryUISlotContainer.InventoryUISlotContainer.__init__(self, manager, sizeX, sizeZ, countX, countZ, slotList)
self.initialiseoptions(InventoryUIClothingContainer)
self.rightClickAction = {
InventoryType.ItemTypeClothing: (None, Locations.CLOTHING_TYPE_TO_RANGE, 1) }
self.overflowInfo = DirectLabel(parent = self, relief = None, textMayChange = 0, text = PLocalizer.OverflowHint, text_font = PiratesGlobals.getPirateBoldOutlineFont(), text_fg = PiratesGuiGlobals.TextFG2, text_scale = 0.040000000000000001, text_align = TextNode.ACenter, text_shadow = PiratesGuiGlobals.TextShadow, text_pos = (0, 0))
self.overflowInfo.setPos(0.25, 0, 1.0700000000000001)
self.overflowInfo.hide()
base.clothPage = self
self.accept('overflowChanged', self.handleOverflow)
def setupBackground(self):
gui = loader.loadModel('models/gui/gui_main')
scale = 0.33500000000000002
self.background = self.attachNewNode('background')
self.background.setScale(scale)
self.background.setPos(0.23000000000000001, 0, 0.52000000000000002)
gui.find('**/gui_inv_clothing').copyTo(self.background)
PiratesGlobals.flattenOrdered(self.background)
def setTitleInfo(self):
gui = loader.loadModel('models/gui/toplevel_gui')
self.titleImageOpen = gui.find('**/topgui_icon_clothing')
self.titleImageClosed = gui.find('**/topgui_icon_clothing')
self.titleName = PLocalizer.InventoryPageClothing
self.titleImageOpen.setScale(0.22)
self.titleImageClosed.setScale(0.22)
def handleOverflow(self, info = None):
self.overflowInfo.hide()
overflowItems = localAvatar.getInventory().getOverflowItems()
for item in overflowItems:
if item[0] in (InventoryType.ItemTypeClothing,):
self.overflowInfo.show()
return None
continue
def postUpdate(self, cell):
if cell in self.cellList:
self.checkReqsForCell(cell)
avInv = localAvatar.getInventory()
if avInv and avInv.findAvailableLocation(InventoryType.ItemTypeClothing) in [
Locations.INVALID_LOCATION,
Locations.NON_LOCATION]:
localAvatar.sendRequestContext(InventoryType.InventoryFull)
|
<filename>src/api/mochaITOM/faultAlarm.js
import Axios from '../http'
export default {
listAllFaultAlarms: params => Axios.post(`/basic/v1/manageOperation/listAllFaultAlarms`, params), //获取所有故障报警
listUnhandledFaultAlarms: params => Axios.post(`/basic/v1/manageOperation/listUnhandledFaultAlarms`, params), //获取未处理故障报警
batchProcessingOfFailureAlarms: params => Axios.post(`/basic/v1/manageOperation/batchProcessingOfFailureAlarms`, params), //批量忽略故障报警
processingOfFailureAlarms: params => Axios.post(`/basic/v1/manageOperation/processingOfFailureAlarms`, params), //批量忽略故障报警
batchForwardingOfRepairWorkOrders: params => Axios.post(`/basic/v1/manageOperation/batchForwardingOfRepairWorkOrders`, params), //批量转报修工单
getFailureAlarms: params => Axios.get(`/basic/v1/manageOperation/getFailureAlarms`, { params }), //批量转报修工单
}
|
<gh_stars>0
public interface Controlador {
public abstract void bind();
public abstract void off();
public abstract void openMenu();
public abstract void closeMenu();
public abstract void increaseVolume();
public abstract void decreaseVolume();
public abstract void callmute();
public abstract void mutedoff();
public abstract void play();
public abstract void pause();
}
|
def group_modulo(list_numbers, num):
result = {i:[] for i in range(num)}
for number in list_numbers:
result[number % num].append(number)
return result
result = group_modulo(list_numbers, num)
print(result) |
import numpy as np
Amp = 7.5*np.pi/180
Base = 90*np.pi/180
Freq = 2*np.pi
# N_seconds = 1
# N = N_seconds*10000 + 1
# t = np.linspace(0,N_seconds,N)
# dt = t[1]-t[0]
### Reference Trajectory ###
# coeffs = [126,-420,540,-315,70]
#
# r = lambda t: float(np.piecewise(t,[t%1<0.5,t%1>=0.5],
# [
# lambda t : (Base+Amp) - 2*Amp*(
# coeffs[0]*((t%1)/0.5)**5
# + coeffs[1]*((t%1)/0.5)**6
# + coeffs[2]*((t%1)/0.5)**7
# + coeffs[3]*((t%1)/0.5)**8
# + coeffs[4]*((t%1)/0.5)**9
# ),
# lambda t : (Base-Amp) + 2*Amp*(
# coeffs[0]*((t%1-0.5)/0.5)**5
# + coeffs[1]*((t%1-0.5)/0.5)**6
# + coeffs[2]*((t%1-0.5)/0.5)**7
# + coeffs[3]*((t%1-0.5)/0.5)**8
# + coeffs[4]*((t%1-0.5)/0.5)**9
# )
# ]
# ))
# dr = lambda t: float(np.piecewise(t,[t%1<0.5,t%1>=0.5],
# [
# lambda t : -2*Amp/(0.5)*(
# 5*coeffs[0]*((t%1)/0.5)**(5-1)
# + 6*coeffs[1]*((t%1)/0.5)**(6-1)
# + 7*coeffs[2]*((t%1)/0.5)**(7-1)
# + 8*coeffs[3]*((t%1)/0.5)**(8-1)
# + 9*coeffs[4]*((t%1)/0.5)**(9-1)
# ),
# lambda t : 2*Amp/(0.5)*(
# 5*coeffs[0]*((t%1-0.5)/0.5)**(5-1)
# + 6*coeffs[1]*((t%1-0.5)/0.5)**(6-1)
# + 7*coeffs[2]*((t%1-0.5)/0.5)**(7-1)
# + 8*coeffs[3]*((t%1-0.5)/0.5)**(8-1)
# + 9*coeffs[4]*((t%1-0.5)/0.5)**(9-1)
# )
# ]
# ))
# d2r = lambda t: float(np.piecewise(t,[t%1<0.5,t%1>=0.5],
# [
# lambda t : -2*Amp/(0.5**2)*(
# (5-1)*5*coeffs[0]*((t%1)/0.5)**(5-2)
# + (6-1)*6*coeffs[1]*((t%1)/0.5)**(6-2)
# + (7-1)*7*coeffs[2]*((t%1)/0.5)**(7-2)
# + (8-1)*8*coeffs[3]*((t%1)/0.5)**(8-2)
# + (9-1)*9*coeffs[4]*((t%1)/0.5)**(9-2)
# ),
# lambda t : 2*Amp/(0.5**2)*(
# (5-1)*5*coeffs[0]*((t%1-0.5)/0.5)**(5-2)
# + (6-1)*6*coeffs[1]*((t%1-0.5)/0.5)**(6-2)
# + (7-1)*7*coeffs[2]*((t%1-0.5)/0.5)**(7-2)
# + (8-1)*8*coeffs[3]*((t%1-0.5)/0.5)**(8-2)
# + (9-1)*9*coeffs[4]*((t%1-0.5)/0.5)**(9-2)
# )
# ]
# ))
# d3r = lambda t: float(np.piecewise(t,[t%1<0.5,t%1>=0.5],
# [
# lambda t : -2*Amp/(0.5**3)*(
# (5-2)*(5-1)*5*coeffs[0]*((t%1)/0.5)**(5-3)
# + (6-2)*(6-1)*6*coeffs[1]*((t%1)/0.5)**(6-3)
# + (7-2)*(7-1)*7*coeffs[2]*((t%1)/0.5)**(7-3)
# + (8-2)*(8-1)*8*coeffs[3]*((t%1)/0.5)**(8-3)
# + (9-2)*(9-1)*9*coeffs[4]*((t%1)/0.5)**(9-3)
# ),
# lambda t : 2*Amp/(0.5**3)*(
# (5-2)*(5-1)*5*coeffs[0]*((t%1-0.5)/0.5)**(5-3)
# + (6-2)*(6-1)*6*coeffs[1]*((t%1-0.5)/0.5)**(6-3)
# + (7-2)*(7-1)*7*coeffs[2]*((t%1-0.5)/0.5)**(7-3)
# + (8-2)*(8-1)*8*coeffs[3]*((t%1-0.5)/0.5)**(8-3)
# + (9-2)*(9-1)*9*coeffs[4]*((t%1-0.5)/0.5)**(9-3)
# )
# ]
# ))
# d4r = lambda t: float(np.piecewise(t,[t%1<0.5,t%1>=0.5],
# [
# lambda t : -2*Amp/(0.5**4)*(
# (5-3)*(5-2)*(5-1)*5*coeffs[0]*((t%1)/0.5)**(5-4)
# + (6-3)*(6-2)*(6-1)*6*coeffs[1]*((t%1)/0.5)**(6-4)
# + (7-3)*(7-2)*(7-1)*7*coeffs[2]*((t%1)/0.5)**(7-4)
# + (8-3)*(8-2)*(8-1)*8*coeffs[3]*((t%1)/0.5)**(8-4)
# + (9-3)*(9-2)*(9-1)*9*coeffs[4]*((t%1)/0.5)**(9-4)
# ),
# lambda t : 2*Amp/(0.5**4)*(
# (5-3)*(5-2)*(5-1)*5*coeffs[0]*((t%1-0.5)/0.5)**(5-4)
# + (6-3)*(6-2)*(6-1)*6*coeffs[1]*((t%1-0.5)/0.5)**(6-4)
# + (7-3)*(7-2)*(7-1)*7*coeffs[2]*((t%1-0.5)/0.5)**(7-4)
# + (8-3)*(8-2)*(8-1)*8*coeffs[3]*((t%1-0.5)/0.5)**(8-4)
# + (9-3)*(9-2)*(9-1)*9*coeffs[4]*((t%1-0.5)/0.5)**(9-4)
# )
# ]
# ))
r = lambda t: Amp*np.cos(Freq*t) + Base
dr = lambda t: -Amp*Freq*np.sin(Freq*t)
d2r = lambda t: -Amp*Freq**2*np.cos(Freq*t)
d3r = lambda t: Amp*Freq**3*np.sin(Freq*t)
d4r = lambda t: Amp*Freq**4*np.cos(Freq*t)
############################
|
// ***********************************************************************************************
// *** G O L A N D S T U D I O S ***
// ***********************************************************************************************
// * Auth: ColeCai
// * Date: 2021/12/14 10:48:14
// * File: utils.go
// * Proj: go-tools
// * Pack: utils
// * Ides: GoLand
// *----------------------------------------------------------------------------------------------
// * Functions:
// * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
package utils
import "time"
const (
MinuteSecond = 60
HourSecond = MinuteSecond * 60
DaySecond = HourSecond * 24
)
// ***********************************************************************************************
// * SUMMARY:
// * WARNING: input params is timestamp.
// * HISTORY:
// * -create: 2021/12/14 10:50:40 ColeCai.
// ***********************************************************************************************
func IsSameDay(time1, time2 int64) bool {
tm1 := time.Unix(time1, 0)
tm2 := time.Unix(time2, 0)
return tm1.Year() == tm2.Year() && tm1.YearDay() == tm2.YearDay()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING: input param is timestamp.
// * HISTORY:
// * -create: 2021/12/14 10:51:33 ColeCai.
// ***********************************************************************************************
func IsCurDay(tm int64) bool {
tm1 := time.Now()
tm2 := time.Unix(tm, 0)
return tm1.Year() == tm2.Year() && tm1.YearDay() == tm2.YearDay()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING: input params is timestamp.
// * HISTORY:
// * -create: 2021/12/14 10:52:02 ColeCai.
// ***********************************************************************************************
func IsSameWeek(time1, time2 int64) bool {
tm1 := time.Unix(time1, 0)
tm2 := time.Unix(time2, 0)
if tm1.Year() != tm2.Year() {
return false
}
_, week1 := tm1.ISOWeek()
_, week2 := tm2.ISOWeek()
return week1 == week2
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING: input param is timestamp.
// * HISTORY:
// * -create: 2021/12/14 10:53:21 ColeCai.
// ***********************************************************************************************
func IsCurWeek(tm int64) bool {
tm1 := time.Now()
tm2 := time.Unix(tm, 0)
if tm1.Year() != tm2.Year() {
return false
}
_, week1 := tm1.ISOWeek()
_, week2 := tm2.ISOWeek()
return week1 == week2
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING: input params is timestamp.
// * HISTORY:
// * -create: 2021/12/14 10:54:32 ColeCai.
// ***********************************************************************************************
func IsSameMonth(time1, time2 int64) bool {
tm1 := time.Unix(time1, 0)
tm2 := time.Unix(time2, 0)
return tm1.Year() == tm2.Year() && tm1.Month() == tm2.Month()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING: input param is timestamp.
// * HISTORY:
// * -create: 2021/12/14 10:55:18 ColeCai.
// ***********************************************************************************************
func IsCurMonth(tm int64) bool {
tm1 := time.Now()
tm2 := time.Unix(tm, 0)
return tm1.Year() == tm2.Year() && tm1.Month() == tm2.Month()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2021/12/14 10:56:32 ColeCai.
// ***********************************************************************************************
func CurDayLeftSecond() int64 {
curTm := time.Now()
endTm := time.Date(curTm.Year(), curTm.Month(), curTm.Day(), 24, 0, 0, 0, curTm.Location()).Unix()
return endTm - curTm.Unix()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * -week start with monday and end with sunday.
// * HISTORY:
// * -create: 2021/12/14 10:57:12 ColeCai.
// * -update: 2021/12/31 14:39:14 ColeCai.fix bug when weekday is sunday.
// ***********************************************************************************************
func CurWeekLeftSecond() int64 {
return CurWeekEnd() - time.Now().Unix()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * -week start with monday and end with sunday.
// * HISTORY:
// * -create: 2022/12/31 14:22:33 ColeCai.
// ***********************************************************************************************
func CurWeekStart() int64 {
return WeekStart(time.Now()).Unix()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * -week start with monday and end with sunday.
// * -current day 24 o'clock is same as after day 0 o'clock. but 24 o'clock timestamp transform
// standard time is after day's date.so here use 23:59:59 as day end time.if you want accurate
// timestamp please add 1 second.
// * HISTORY:
// * -create: 2022/12/31 14:24:28 ColeCai.
// ***********************************************************************************************
func CurWeekEnd() int64 {
return WeekEnd(time.Now()).Unix()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/12/31 14:41:28 ColeCai.
// ***********************************************************************************************
func GetMonthDays(year, month int) int {
switch month {
case 1, 3, 5, 7, 8, 10, 12:
return 31
case 4, 6, 9, 11:
return 30
default:
if IsLeapYear(year) {
return 29
}
return 28
}
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/12/31 14:58:53 ColeCai.
// ***********************************************************************************************
func IsLeapYear(year int) bool {
return year%400 == 0 || (year%4 == 0 && year%100 != 0)
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/12/31 14:59:41 ColeCai.
// ***********************************************************************************************
func CurMonthStart() int64 {
return MonthStart(time.Now()).Unix()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/12/31 15:09:46 ColeCai.
// ***********************************************************************************************
func CurMonthEnd() int64 {
return MonthEnd(time.Now()).Unix()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/12/31 15:19:43 ColeCai.
// ***********************************************************************************************
func CurMonthLeftSecond() int64 {
return CurMonthEnd() - time.Now().Unix()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/12/31 15:20:23 ColeCai.
// ***********************************************************************************************
func MonthStart(t time.Time) time.Time {
days := t.Day()
stm := t.AddDate(0, 0, -days+1)
return time.Date(stm.Year(), stm.Month(), stm.Day(), 0, 0, 0, 0, stm.Location())
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * -current day 24 o'clock is same as after day 0 o'clock. but 24 o'clock timestamp transform
// standard time is after day's date.so here use 23:59:59 as day end time.if you want accurate
// timestamp please add 1 second.
// * HISTORY:
// * -create: 2022/12/31 15:20:57 ColeCai.
// ***********************************************************************************************
func MonthEnd(t time.Time) time.Time {
year := t.Year()
month := t.Month()
monthDays := GetMonthDays(year, int(month))
etm := t.AddDate(0, 0, monthDays-t.Day())
return time.Date(etm.Year(), etm.Month(), etm.Day(), 23, 59, 59, 0, etm.Location())
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/12/31 15:22:06 ColeCai.
// ***********************************************************************************************
func WeekStart(t time.Time) time.Time {
weekDay := t.Weekday()
if weekDay == time.Sunday {
weekDay = 7
}
ntm := t.AddDate(0, 0, -int(weekDay)+1)
return time.Date(ntm.Year(), ntm.Month(), ntm.Day(), 0, 0, 0, 0, ntm.Location())
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * -current day 24 o'clock is same as after day 0 o'clock. but 24 o'clock timestamp transform
// standard time is after day's date.so here use 23:59:59 as day end time.if you want accurate
// timestamp please add 1 second.
// * HISTORY:
// * -create: 2022/12/31 15:23:15 ColeCai.
// ***********************************************************************************************
func WeekEnd(t time.Time) time.Time {
weekDay := t.Weekday()
if weekDay == time.Sunday {
weekDay = 7
}
ntm := t.AddDate(0, 0, 7-int(weekDay))
return time.Date(ntm.Year(), ntm.Month(), ntm.Day(), 23, 59, 59, 0, ntm.Location())
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * -yesterday n o'clock to today n o'clock format to yesterday date. today n o'clock to
// * tomorrow n o'clock format to today date.
// * eg: 2022-01-01 06:00:00 - 2022-01-02 06:00:00 is 2022-01-01
// * HISTORY:
// * -create: 2022/01/06 15:33:56 ColeCai.
// ***********************************************************************************************
func DateByClock(n int, tm time.Time) time.Time {
hour := tm.Hour()
if hour < n {
return tm.AddDate(0, 0, -1)
} else {
return tm
}
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * -yesterday n o'clock to today n o'clock format to yesterday date. today n o'clock to
// * tomorrow n o'clock format to today date.
// * eg: 2022-01-01 06:00:00 - 2022-01-02 06:00:00 is 2022-01-01
// * HISTORY:
// * -create: 2022/01/06 15:38:57 ColeCai.
// ***********************************************************************************************
func DateStrByClock(n int, layout string) string {
tm := DateByClock(n, time.Now())
return tm.Format(layout)
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/02/14 11:19:45 ColeCai.
// ***********************************************************************************************
func GetTimeWeek(tm time.Time) int {
_, week := tm.ISOWeek()
return week
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/02/14 11:21:11 ColeCai.
// ***********************************************************************************************
func GetCutWeek() int {
return GetTimeWeek(time.Now())
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/02/14 11:21:41 ColeCai.
// ***********************************************************************************************
func GetTimeYearWeek(tm time.Time) (int, int) {
return tm.ISOWeek()
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/02/14 11:22:14 ColeCai.
// ***********************************************************************************************
func GetCurYearWeek() (int, int) {
return GetTimeYearWeek(time.Now())
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/02/14 11:22:58 ColeCai.
// ***********************************************************************************************
func GetTimeStampWeek(tm int64) int {
t := time.Unix(tm, 0)
return GetTimeWeek(t)
}
// ***********************************************************************************************
// * SUMMARY:
// * WARNING:
// * HISTORY:
// * -create: 2022/02/14 11:24:02 ColeCai.
// ***********************************************************************************************
func GetTimeStampYearWeek(tm int64) (int, int) {
t := time.Unix(tm, 0)
return GetTimeYearWeek(t)
}
|
import enGb from './src/index';
export default enGb;
|
let answer = [];
for (let i = 0; i <= 1000; i++) {
if (i % 5 == 0 && i % 6 == 0) {
answer.push(i);
}
}
console.log(answer); |
from __future__ import absolute_import
import os
import sys
common_utils_path = os.path.join(
"/", *os.path.abspath(__file__).split("/")[:-4], "utils")
sys.path.append(common_utils_path)
from yaml_wrapper import read_yaml
from misc import AttrDict
from comm import CommunicatorWrapper
from gan_losses import RelativisticAverageGanLoss, GanLoss
|
import ProgressPar from './ProgressPar';
export default ProgressPar; |
#!/bin/bash
# CocoaHeadsRu (c)
# Description: this is the shell script for the cocoaheadsru server deploy and start
# Author: Dmitry, ditansu@gmail.com
##SETINGS
#Get from Jenkins pipeline
PROJECT=$CH_BUILD
WEBROOT=$CH_WEBROOT
#Permisions
USER="www-data"
GROUP="www-data"
#Commands
SUPERVISOR=/usr/bin/supervisorctl
SERVICE="cocoaheadsru"
##WORK
echo "Stop $SERVICE..."
$SUPERVISOR stop $SERVICE
rm -rf $WEBROOT/server.bak
mv -f $WEBROOT/server $WEBROOT/server.bak
echo "Copy $PROJECT to $WEBROOT"
cp -r $PROJECT $WEBROOT/server
echo "Chown $USER:$GROUP for $WEBROOT"
chown -fR $USER:$GROUP $WEBROOT
echo "Start $SERVICE..."
RESULT=$($SUPERVISOR start $SERVICE)
echo ""
echo "Result is $RESULT"
echo ""
if [[ $RESULT == *"ERROR"* ]]; then
echo "Something was wrong, let try start to rollback deploy..."
exit 1
fi
exit 0
|
<reponame>super-effective/colorutil
import { Rgb } from 'colorTypes';
function hueToRgb(p: number, q: number, t: number) {
let clampedT = t;
if (t < 0) {
clampedT += 360;
}
if (clampedT > 360) {
clampedT -= 360;
}
if(clampedT < 60) {
return p + (q - p) * 6 * (clampedT / 360);
}
if(clampedT < 180) {
return q;
}
if(clampedT < 240) {
return p + (q - p) * ((240 - clampedT) / 360) * 6;
}
return p;
}
/**
* Takes given hue, saturation and lightness and returns the respective RGB values
* @param {number} hue The hue of the color (0.0 - 360.0)
* @param {number} saturation The saturation of the color (0.0 - 1.0)
* @param {number} lightness The value of the color (0.0 - 1.0)
* @returns {Rgb} The RGB values for the color
*/
export default function hslToRgb(hue: number, saturation: number, lightness: number): Rgb {
// Bounds check
if ((hue < 0 || hue > 360)
|| (saturation < 0 || saturation > 1)
|| (lightness < 0 || lightness > 1)) {
throw new Error('Invalid hue, saturation, or value - all values must be between 0 and 1');
}
// Achromatic
if (saturation === 0) {
const rgb = Math.round(lightness * 255);
return {
red: rgb,
green: rgb,
blue: rgb,
};
}
const q = (lightness < 0.5) ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
const red = hueToRgb(p, q, hue + 120);
const green = hueToRgb(p, q, hue);
const blue = hueToRgb(p, q, hue - 120);
return {
red: Math.round(red * 255),
green: Math.round(green * 255),
blue: Math.round(blue * 255),
};
}
|
#!/usr/bin/env bash
set -e
cd "$(dirname "${BASH_SOURCE[0]}")"
source yaml.sh
create_variables ../params.yaml
gcloud beta builds triggers create github --name=${aggregation_continuous_development_trigger_name} \
--description="${aggregation_continuous_development_trigger_description}" \
--repo-owner=${aggregation_continuous_development_trigger_repo_owner} \
--repo-name=${aggregation_continuous_development_trigger_repo_name} \
--branch-pattern=${aggregation_continuous_development_trigger_branch_pattern} \
--included-files=${aggregation_continuous_development_trigger_files_included} \
--build-config=${aggregation_continuous_development_trigger_build_config}
|
from typing import List, Tuple
def find_slowest_router(routers: List[Tuple[str, int]]) -> str:
slowest_router = ''
slowest_speed = float('inf')
for router_id, speed in routers:
if speed < slowest_speed:
slowest_speed = speed
slowest_router = router_id
return slowest_router |
class Book {
var title: String
var author: String
var pages: Int
var publicationYear: Int
init(title: String, author: String, pages: Int, publicationYear: Int) {
self.title = title
self.author = author
self.pages = pages
self.publicationYear = publicationYear
}
} |
#!/usr/bin/env sh
# generated from catkin/cmake/template/local_setup.sh.in
# since this file is sourced either use the provided _CATKIN_SETUP_DIR
# or fall back to the destination set at configure time
: ${_CATKIN_SETUP_DIR:=/root/catkin_ws/devel/.private/lawn_tractor_sim}
CATKIN_SETUP_UTIL_ARGS="--extend --local"
. "$_CATKIN_SETUP_DIR/setup.sh"
unset CATKIN_SETUP_UTIL_ARGS
|
def is_valid_palindrome(polin: str, polin_test: str) -> str:
polin = ''.join(e for e in polin if e.isalnum()).lower()
polin_test = ''.join(e for e in polin_test if e.isalnum()).lower()
return "YES" if polin == polin_test else "NO" |
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public static String encrypt(String plaintext, String key) {
// generate initialization vector (IV)
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
// create cipher
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key), ivSpec);
// encrypt plaintext
byte[] ciphertext = cipher.doFinal(plaintext.getBytes());
// encode initialization vector + ciphertext
byte[] encoded = new byte[iv.length + ciphertext.length];
System.arraycopy(iv, 0, encoded, 0, iv.length);
System.arraycopy(ciphertext, 0, encoded, iv.length, ciphertext.length);
// return Base64 encoded string
return Base64.getEncoder().encodeToString(encoded);
}
private static SecretKey getSecretKey(String key) {
byte[] bytes = key.getBytes();
return new SecretKeySpec(bytes, "AES");
} |
import Link from "next/link";
function Header() {
return (
<>
<nav className="flex justify-center flex-wrap bg-blue-900 p-4">
<div className="w-1/5">
<p className="flex justify-start text-blue-300 text-3xl">Master DAO</p>
</div>
<div className="w-4/5 flex justify-start p-1">
<ul>
<li>
<Link href="/">
<a className="m-5 text-white underline">Home</a>
</Link>
</li>
</ul>
<ul>
<li>
<Link href="/members">
<a className="m-5 text-white underline">Members</a>
</Link>
</li>
</ul>
<ul>
<li>
<Link href="/">
<a className="m-5 text-white underline">Proposals</a>
</Link>
</li>
</ul>
<ul>
<li>
<Link href="/">
<a className="m-5 text-white underline">Donate2(specific DAO)</a>
</Link>
</li>
</ul>
<ul>
<li>
<Link href="/">
<a className="m-5 text-white underline">Donate2(Master DAO)</a>
</Link>
</li>
</ul>
</div>
</nav>
</>
);
}
export default Header;
|
<reponame>CristianMSilice/webSilice2<gh_stars>0
import { Component, OnInit } from '@angular/core';
import { DataWpService } from '../../services/data-wp.service';
@Component({
selector: 'infografia',
templateUrl: './infografia.component.html'
})
export class InfografiaComponent implements OnInit {
public data: any
constructor(
private dataWpService: DataWpService
) { }
ngOnInit() {
this.dataWpService.getSomos('infografia').subscribe(res => {
this.data = res
this.animateData()
})
}
animateData = function () {
this.data.forEach(dato => {
let time = 1500;
let timeStep = time / dato.expected;
let mintime = 60;
let step = 1;
if (timeStep < mintime) step = Math.ceil(dato.expected / (time / mintime));
dato.interval = setInterval(() => {
if (dato.expected > dato.initial) {
dato.initial = dato.initial + step;
}
else {
dato.initial = dato.expected
clearInterval(dato.interval);
}
}, timeStep)
})
}
}
|
import React from 'react';
interface ICheckboxGroupProps {
readonly children: React.ReactNode[];
label?: string;
className?: string;
}
export const CheckboxGroup = ({
children,
label,
className = '',
}: ICheckboxGroupProps): JSX.Element => {
return (
<fieldset className={`space-y-3 ${className}`}>
{label && <legend className="sr-only">{label}</legend>}
{/* eslint-disable react/no-array-index-key */}
{children.map((child, index) => {
if (index !== 0) {
return <div key={`checkbox-${index}`}>{child}</div>;
}
return child;
})}
{/* eslint-enable react/no-array-index-key */}
</fieldset>
);
};
|
#!/bin/bash
set -e
current_folder=$(pwd)
cd standalone
parameter_files=$(find .. | grep .tfvars | sed 's/.*/-var-file &/' | xargs)
echo $parameter_files
terraform init
eval terraform apply ${parameter_files} \
-var tags='{testing_job_id='"${1}"'}' \
-var var_folder_path=${current_folder} \
-input=false \
-auto-approve
eval terraform destroy ${parameter_files} \
-var tags='{testing_job_id='"${1}"'}' \
-var var_folder_path=${current_folder} \
-input=false \
-auto-approve
|
<reponame>jkennerley/mashid<gh_stars>0
module.exports = function (config) {
config.set({
basePath: '',
client: {
useIframe: false
},
frameworks: ['mocha', 'expect'],
files: [
{ pattern: 'node_modules/requirejs/require.js', included: false },
{ pattern: 'test/fixture/amd.html', watched: true, served: true, included: false },
{ pattern: 'build/power-assert.js', watched: true, served: true, included: true },
{ pattern: 'espowered_tests/tobe_instrumented/assertion.js', watched: true, served: true, included: true },
{ pattern: 'espowered_tests/tobe_instrumented/assertion.es6.js', watched: true, served: true, included: true },
{ pattern: 'espowered_tests/tobe_instrumented/customization.js', watched: true, served: true, included: true },
{ pattern: 'espowered_tests/not_tobe_instrumented/not_instrumented.js', watched: true, served: true, included: true },
{ pattern: 'espowered_tests/tobe_instrumented/modules.js', watched: true, served: true, included: true }
],
reporters: ['dots'],
port: 9876,
colors: true,
browsers: ['PhantomJS', 'Chrome', 'Firefox'],
singleRun: true
});
};
|
import React from 'react'
import { BiHeart } from 'react-icons/bi'
export const Heart = ({ rating }) => {
return (
<div className='ms-auto'>
<div className='d-flex'>
<BiHeart className='color-lightn hover-color-primary me-2 mt-1 p-medium' />
<div className='color-lightn p-medium'>{rating}</div>
</div>
</div>
)
}
|
#!/bin/bash
#SBATCH --account=def-dkulic
#SBATCH --mem=8000M # memory per node
#SBATCH --time=23:00:00 # time (DD-HH:MM)
#SBATCH --output=/project/6001934/lingheng/Double_DDPG_Job_output/continuous_RoboschoolHalfCheetah-v1_doule_ddpg_softcopy_action_noise_seed3_run6_%N-%j.out # %N for node name, %j for jobID
module load qt/5.9.6 python/3.6.3 nixpkgs/16.09 gcc/7.3.0 boost/1.68.0 cuda cudnn
source ~/tf_cpu/bin/activate
python ./ddpg_discrete_action.py --env RoboschoolHalfCheetah-v1 --random-seed 3 --exploration-strategy action_noise --summary-dir ../Double_DDPG_Results_no_monitor/continuous/RoboschoolHalfCheetah-v1/doule_ddpg_softcopy_action_noise_seed3_run6 --continuous-act-space-flag
|
jQuery(document).ready(function() {
var sticky = new Waypoint.Sticky({
element: jQuery('.primary-nav')[0]
})
jQuery("html").niceScroll({
cursorcolor: "#1a1a1a",
cursorborder: "#1a1a1a",
cursoropacitymin: 0.2,
cursorwidth: 10,
zindex: 10,
scrollspeed: 60,
mousescrollstep: 40
});
window.sr = new scrollReveal();
jQuery('a.scrolltrue').bind('click', function(event) {
event.preventDefault();
var $href = jQuery(this);
jQuery('html, body').stop().animate({
scrollTop: jQuery($href.attr('href')).offset().top
}, 1000, 'easeInOutQuad');
});
}); |
function getParentUrl() {
var isInIframe = (parent !== window),
parentUrl = null;
if (isInIframe) {
parentUrl = document.referrer;
}
return parentUrl;
}
var parent_url = getParentUrl();
var isEdge = false; // todo find out where this would come from
var isFirefox = !!navigator.mozGetUserMedia;
var isOpera = !!window.opera || navigator.userAgent.indexOf('OPR/') !== -1;
var isChrome = !isOpera && !isEdge && !!navigator.webkitGetUserMedia;
if (parent_url.indexOf('https') > -1) {
// todo record audio only
// todo record video and audio
//Voicemessage.js
var leftchannel = [];
var rightchannel = [];
var recorder = null;
var recording = false;
var recordingLength = 0;
var volume = null;
var audioInput = null;
var sampleRate = null;
var audioContext = null;
var context = null;
var outputElement = document.getElementById('output');
var outputString;
var audioMessage;
var audiostorage = "/uploads/audio/";
var isFirefox = !!navigator.mozGetUserMedia;
var first = true;
$('#popup18 .btn-popup,#popup2 .btn-popup,#popup30 .start-video').click(function(){
if($('.check_domain').val() === 'true') {
$('#popup20 #play').hide();
$('#popup4 #play').hide();
$('#popup32 #play').hide();
// var mediaConstraints = {
// audio: true
// };
// if (!navigator.getUserMedia){
// navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
// }
// navigator.getUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
if (!navigator.getUserMedia)
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia){
navigator.getUserMedia({audio:true}, success , function(e) {
alert('Error capturing audio.');
});
} else alert('getUserMedia not supported in this browser.');
}
});
function onMediaSuccess(stream) {
// if(!isFirefox){
// mediaRecorder = new MediaStreamRecorder(stream);
// mediaRecorder.mimeType = 'audio/wav';
// mediaRecorder.audioChannels = 1;
// mediaRecorder.ondataavailable = function (blob) {
// audioMessage = blob;
// };
mediaRecorder = new MultiStreamRecorder(stream);
mediaRecorder.video = video;
mediaRecorder.ondataavailable = function (blobs) {
audioMessage = blobs.audio;
videoMessage = blobs.video;
};
// } else {
// recordRTC = RecordRTC(stream);
// }
$('#popup20 #play').show();
$('#popup4 #play').show();
$('#popup32 #play').show();
}
function onMediaError(e) {
alert('Oops!!! You have a problem with Your camera or You don\'t have permissions to use it!!!');
}
var isPaused = false;
var seconds1 = 0;
var seconds2 = 0;
var minutes = 0;
var message_length = '0:00';
if($('#record_length').length !== 0) {
document.getElementById("record_length").innerHTML = message_length;
}
function func() {
seconds2++;
if(seconds2 == 10){
seconds2 = 0;
seconds1++;
}
if(seconds1 == 6){
seconds1 = 0;
minutes++;
}
message_length = minutes+":"+seconds1+seconds2;
document.getElementById("record_length").innerHTML = message_length;
}
if (typeof $.timer != 'undefined'){
var timer = $.timer(func, 1000, true);
timer.stop();
}
$(".play").on('click', function(){
if($('.check_domain').val() === 'true') {
document.getElementById('play').style.display = 'none';
document.getElementById('stop').style.display = 'inline-block';
timer.play();
recording = true;
if($('.is_premium').val() == false){
if(first)
setTimeout(getAudio, 300000);
first = true;
} else {
if(first)
setTimeout(getAudio, 600000);
first = true;
}
}
});
// $(".pause").on('click', function(){
// if($('.check_domain').val() === 'true') {
// document.getElementById('pause').style.display = 'none';
// document.getElementById('play').style.display = 'inline-block';
// timer.pause();
// /*isPaused = true;*/
// recording = false;
// }
// });
function getAudio(){
first = false;
if($('.check_domain').val() === 'true') {
$('.display_div').hide();
$('.display_div:nth-child(5)').show();
}
// if(!isFirefox)
// mediaRecorder.stop();
// else{
// recordRTC.stopRecording(function(videoURL) {
// audioMessage = recordRTC.getBlob();
// });
// }
timer.stop();
// document.getElementById('pause').style.display = 'none';
document.getElementById('play').style.display = 'inline-block';
recording = false;
var leftBuffer = mergeBuffers ( leftchannel, recordingLength );
var rightBuffer = mergeBuffers ( rightchannel, recordingLength );
var interleaved = interleave ( leftBuffer, rightBuffer );
var buffer = new ArrayBuffer(44 + interleaved.length * 2);
var view = new DataView(buffer);
writeUTFBytes(view, 0, 'RIFF');
view.setUint32(4, 44 + interleaved.length * 2, true);
writeUTFBytes(view, 8, 'WAVE');
writeUTFBytes(view, 12, 'fmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, 2, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * 4, true);
view.setUint16(32, 4, true);
view.setUint16(34, 16, true);
writeUTFBytes(view, 36, 'data');
view.setUint32(40, interleaved.length * 2, true);
var lng = interleaved.length;
var index = 44;
var volume = 1;
for (var i = 0; i < lng; i++){
view.setInt16(index, interleaved[i] * (0x7FFF * volume), true);
index += 2;
}
var blob = new Blob ( [ view ], { type : 'audio/wav' } );
var xhr=new XMLHttpRequest();
var fd = new FormData();
fd.append("file",blob);
xhr.open("POST","/messages/upload-file");
$("#spanimg").css("display", "inline-block");
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status != 200) {
alert("An Error Occured.");
} else {
$("#spanimg").css("display", "none");
$('#playing').show();
$('.hidden_div').show();
localStorage.message_length = message_length;
localStorage.fileName = JSON.parse(xhr.responseText).file_name;
localStorage.id = JSON.parse(xhr.responseText).id;
localStorage.file = audiostorage + JSON.parse(xhr.responseText).file_name;
$('#music').prop('src', localStorage.file);
document.getElementById('message_length').innerHTML = localStorage.message_length;
document.getElementById("file_name").value = localStorage.fileName;
document.getElementById("duration").value = localStorage.message_length;
document.getElementById('token').value = localStorage.token;
seconds1 = 0;
seconds2 = 0;
minutes = 0;
message_length = '0:00';
leftchannel.length = rightchannel.length = 0;
recordingLength = 0;
}
}
xhr.send(fd);
}
$(".stop").on('click', function(){
if($('.check_domain').val() === 'true') {
getAudio();
}
});
function interleave(leftChannel, rightChannel){
var length = leftChannel.length + rightChannel.length;
var result = new Float32Array(length);
var inputIndex = 0;
for (var index = 0; index < length; ){
result[index++] = leftChannel[inputIndex];
result[index++] = rightChannel[inputIndex];
inputIndex++;
}
return result;
}
function mergeBuffers(channelBuffer, recordingLength){
var result = new Float32Array(recordingLength);
var offset = 0;
var lng = channelBuffer.length;
for (var i = 0; i < lng; i++){
var buffer = channelBuffer[i];
result.set(buffer, offset);
offset += buffer.length;
}
return result;
}
function writeUTFBytes(view, offset, string){
var lng = string.length;
for (var i = 0; i < lng; i++){
view.setUint8(offset + i, string.charCodeAt(i));
}
}
function success(e){
audioContext = window.AudioContext || window.webkitAudioContext;
context = new audioContext();
sampleRate = context.sampleRate;
volume = context.createGain();
audioInput = context.createMediaStreamSource(e);
audioInput.connect(volume);
var bufferSize = 2048;
recorder = context.createScriptProcessor(bufferSize, 2, 2);
recorder.onaudioprocess = function(e){
if (!recording) return;
var left = e.inputBuffer.getChannelData (0);
var right = e.inputBuffer.getChannelData (1);
leftchannel.push (new Float32Array (left));
rightchannel.push (new Float32Array (right));
recordingLength += bufferSize;
}
volume.connect (recorder);
recorder.connect (context.destination);
$('#popup20 #play').show();
$('#popup4 #play').show();
$('#popup32 #play').show();
}
//Videomessage.js
var videostorage = "/uploads/video/";
var mediaRecorder;
var recordRTC;
var audioMessage = "";
var videoMessage = "";
var video;
var first = true;
var isFirefox = !!navigator.mozGetUserMedia;
$('#popup7 .btn-popup,#popup13 .btn-popup,#popup25 .start-video').click(function() {
if($('.check_domain').val() === 'true') {
$('#popup9 #capture').hide();
$('#popup15 #capture').hide();
$('#popup27 #capture').hide();
var mediaConstraints = {
audio: true,
video: true
};
if (!navigator.getUserMedia) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
}
navigator.getUserMedia(mediaConstraints, onMediaSuccess, onMediaError);
}
});
function onMediaSuccess(stream) {
if(stream.getVideoTracks().length == 0) {
alert('Error Capturing Video!!! Please check is camera connected or Have You a permission to use it!!!');
return false;
}
video = document.querySelector('video');
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
video.src = window.URL.createObjectURL(stream);
var options = {};
//if(!isFirefox) {
// mediaRecorder = new MultiStreamRecorder(stream);
// mediaRecorder.video = video;
// mediaRecorder.audioChannels = 1;
// mediaRecorder.ondataavailable = function (blobs) {
// if(first){
// audioMessage = blobs.audio;
// videoMessage = blobs.video;
// getVideo();
// } else {
// audioMessage = blobs.audio;
// videoMessage = blobs.video;
// }
// first = true;
// };
//} else {
recordRTC = RecordRTC(stream, options);
//}
$('#popup9 #capture').show();
$('#popup15 #capture').show();
$('#popup27 #capture').show();
}
function onMediaError(e) {
alert('Error Capturing Video!!! Please check is camera connected or Have You a permission to use it!!!');
}
var isPaused = false;
var seconds1 = 0;
var seconds2 = 0;
var minutes = 0;
var message_length = '0:00';
if($('#record_length').length !== 0) {
document.getElementById("record_length").innerHTML = message_length;
}
function func() {
seconds2++;
if(seconds2 == 10){
seconds2 = 0;
seconds1++;
}
if(seconds1 == 6){
seconds1 = 0;
minutes++;
}
message_length = minutes+":"+seconds1+seconds2;
document.getElementById("record_length").innerHTML = message_length;
}
if (typeof $.timer != 'undefined') {
var timer = $.timer(func, 1000, true);
timer.stop();
}
$("#capture").on('click', function() {
if($('.check_domain').val() === 'true') {
document.getElementById('capture').style.display = 'none';
document.getElementById('video-stop').style.display = 'inline-block';
//if(!isFirefox) {
// mediaRecorder.start(6000000);
// if($('.is_premium').val() == false) {
// setTimeout(getVideo, 300000);
// } else {
// setTimeout(getVideo, 600000);
// }
//} else {
recordRTC.startRecording();
if($('.is_premium').val() == false) {
if(first)
setTimeout(getVideo, 300000);
first = true;
} else {
if(first)
setTimeout(getVideo, 600000);
first = true;
}
//}
timer.play();
}
});
$("#video-stop").on('click', function() {
if($('.check_domain').val() === 'true') {
getVideo();
}
});
$('#play_back').on('click', function() {
if($('.check_domain').val() === 'true') {
$('#play_back').hide();
$('#video-pause').show();
var video = document.getElementById('video_watch');
video.play();
}
});
$('#video-pause').on('click', function() {
if($('.check_domain').val() === 'true') {
$('#play_back').show();
$('#video-pause').hide();
var video = document.getElementById('video_watch');
video.pause();
}
})
function getVideo() {
first = false;
if($('.check_domain').val() === 'true') {
$('.display_div').hide();
$('.display_div:nth-child(10)').show();
}
//if(!isFirefox) {
// mediaRecorder.stop();
//} else {
recordRTC.stopRecording(function(videoURL) {
videoMessage = recordRTC.getBlob();
});
//}
timer.stop();
document.getElementById('video-pause').style.display = 'none';
document.getElementById('video-stop').style.display = 'none';
document.getElementById('capture').style.display = 'inline-block';
//var fileType = 'video';
//var xhr = new XMLHttpRequest();
// todo check if i need this timeout
setTimeout(function() {
var formData = new FormData();
//if(!isFirefox) {
formData.append('audiofile', audioMessage);
//}
formData.append('videofile', videoMessage);
formData.append('length', message_length);
$("#videospanimg").css("display", "inline-block");
$.ajax({
method: "POST",
url: "/messages/upload-file",
data: formData,
processData: false,
contentType: false,
})
.complete(function(res) {
console.log('ajax complete: ', res);
$("#videospanimg").css("display", "none");
$('.btn-holder').show();
localStorage.message_length = message_length;
localStorage.fileName = JSON.parse(res.responseText).file_name;
localStorage.file = videostorage + JSON.parse(res.responseText).file_name;
localStorage.id = JSON.parse(res.responseText).id;
console.log('show recording');
$('#video_watch').prop('src', localStorage.file);
document.getElementById('message_length').innerHTML = localStorage.message_length;
document.getElementById("video_file_name").value = localStorage.fileName;
document.getElementById("video_duration").value = localStorage.message_length;
document.getElementById('video_token').value = localStorage.token;
seconds1 = 0;
seconds2 = 0;
minutes = 0;
message_length = '0:00';
})
.error(function(err) {
console.log('ajax error: ', err);
});
}, 3000);
}
} else {
console.log('load flash');
console.log('http is no longer supported by Voicestak, please use https instead of http');
}
// Credit to Ludwig: http://stackoverflow.com/questions/9514179/how-to-find-the-operating-system-version-using-javascript
(function (window) {
{
var unknown = ' ';
// screen
var screenSize = '';
if (screen.width) {
var width = (screen.width) ? screen.width : '';
var height = (screen.height) ? screen.height : '';
screenSize += '' + width + " x " + height;
}
// browser
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browser = navigator.appName;
var version = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;
// Opera
if ((verOffset = nAgt.indexOf('Opera')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Opera Next
if ((verOffset = nAgt.indexOf('OPR')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 4);
}
// MSIE
else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
}
// Chrome
else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
browser = 'Chrome';
version = nAgt.substring(verOffset + 7);
}
// Safari
else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
browser = 'Safari';
version = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Firefox
else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
browser = 'Firefox';
version = nAgt.substring(verOffset + 8);
}
// MSIE 11+
else if (nAgt.indexOf('Trident/') != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(nAgt.indexOf('rv:') + 3);
}
// Other browsers
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
browser = nAgt.substring(nameOffset, verOffset);
version = nAgt.substring(verOffset + 1);
if (browser.toLowerCase() == browser.toUpperCase()) {
browser = navigator.appName;
}
}
// trim the version string
if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);
majorVersion = parseInt('' + version, 10);
if (isNaN(majorVersion)) {
version = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
// mobile version
var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
// cookie
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
}
// system
var os = unknown;
var clientStrings = [
{s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
{s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
{s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
{s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
{s:'Windows Vista', r:/Windows NT 6.0/},
{s:'Windows Server 2003', r:/Windows NT 5.2/},
{s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
{s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
{s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
{s:'Windows 98', r:/(Windows 98|Win98)/},
{s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
{s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
{s:'Windows CE', r:/Windows CE/},
{s:'Windows 3.11', r:/Win16/},
{s:'Android', r:/Android/},
{s:'Open BSD', r:/OpenBSD/},
{s:'Sun OS', r:/SunOS/},
{s:'Linux', r:/(Linux|X11)/},
{s:'iOS', r:/(iPhone|iPad|iPod)/},
{s:'Mac OS X', r:/Mac OS X/},
{s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
{s:'QNX', r:/QNX/},
{s:'UNIX', r:/UNIX/},
{s:'BeOS', r:/BeOS/},
{s:'OS/2', r:/OS\/2/},
{s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
];
for (var id in clientStrings) {
var cs = clientStrings[id];
if (cs.r.test(nAgt)) {
os = cs.s;
break;
}
}
var osVersion = unknown;
if (/Windows/.test(os)) {
osVersion = /Windows (.*)/.exec(os)[1];
os = 'Windows';
}
switch (os) {
case 'Mac OS X':
osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
break;
case 'Android':
osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
break;
case 'iOS':
osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
break;
}
// flash (you'll need to include swfobject)
/* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
var flashVersion = 'no check';
if (typeof swfobject != 'undefined') {
var fv = swfobject.getFlashPlayerVersion();
if (fv.major > 0) {
flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
}
else {
flashVersion = unknown;
}
}
}
window.jscd = {
screen: screenSize,
browser: browser,
browserVersion: version,
browserMajorVersion: majorVersion,
mobile: mobile,
os: os,
osVersion: osVersion,
cookies: cookieEnabled,
flashVersion: flashVersion
};
}(this)); |
<reponame>Sasha7b9Work/S8-53M2
///////////////////////////////////////////////////////////////////////////////
// Name: mediaplayer.cpp
// Purpose: wxMediaCtrl sample
// Author: <NAME>
// Modified by:
// Created: 11/10/04
// Copyright: (c) <NAME>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// MediaPlayer
//
// This is a somewhat comprehensive example of how to use all the funtionality
// of the wxMediaCtrl class in wxWidgets.
//
// To use this sample, simply select Open File from the file menu,
// select the file you want to play - and MediaPlayer will play the file in a
// the current notebook page, showing video if necessary.
//
// You can select one of the menu options, or move the slider around
// to manipulate what is playing.
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Known bugs with wxMediaCtrl:
//
// 1) Certain backends can't play the same media file at the same time (MCI,
// Cocoa NSMovieView-Quicktime).
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// ============================================================================
// Definitions
// ============================================================================
// ----------------------------------------------------------------------------
// Pre-compiled header stuff
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
// ----------------------------------------------------------------------------
// Headers
// ----------------------------------------------------------------------------
#include "wx/mediactrl.h" // for wxMediaCtrl
#include "wx/filedlg.h" // for opening files from OpenFile
#include "wx/slider.h" // for a slider for seeking within media
#include "wx/sizer.h" // for positioning controls/wxBoxSizer
#include "wx/timer.h" // timer for updating status bar
#include "wx/textdlg.h" // for getting user text from OpenURL/Debug
#include "wx/notebook.h" // for wxNotebook and putting movies in pages
#include "wx/cmdline.h" // for wxCmdLineParser (optional)
#include "wx/listctrl.h" // for wxListCtrl
#include "wx/dnd.h" // drag and drop for the playlist
#include "wx/filename.h" // For wxFileName::GetName()
#include "wx/config.h" // for native wxConfig
#include "wx/vector.h"
// Under MSW we have several different backends but when linking statically
// they may be discarded by the linker (this definitely happens with MSVC) so
// force linking them. You don't have to do this in your code if you don't plan
// to use them, of course.
#if defined(__WXMSW__) && !defined(WXUSINGDLL)
#include "wx/link.h"
wxFORCE_LINK_MODULE(wxmediabackend_am)
wxFORCE_LINK_MODULE(wxmediabackend_qt)
wxFORCE_LINK_MODULE(wxmediabackend_wmp10)
#endif // static wxMSW build
#ifndef wxHAS_IMAGES_IN_RESOURCES
#include "../sample.xpm"
#endif
// ----------------------------------------------------------------------------
// Bail out if the user doesn't want one of the
// things we need
// ----------------------------------------------------------------------------
#if !wxUSE_MEDIACTRL || !wxUSE_MENUS || !wxUSE_SLIDER || !wxUSE_TIMER || \
!wxUSE_NOTEBOOK || !wxUSE_LISTCTRL
#error "Not all required elements are enabled. Please modify setup.h!"
#endif
// ============================================================================
// Declarations
// ============================================================================
// ----------------------------------------------------------------------------
// Enumurations
// ----------------------------------------------------------------------------
// IDs for the controls and the menu commands
enum
{
// Menu event IDs
wxID_LOOP = 1,
wxID_OPENFILESAMEPAGE,
wxID_OPENFILENEWPAGE,
wxID_OPENURLSAMEPAGE,
wxID_OPENURLNEWPAGE,
wxID_CLOSECURRENTPAGE,
wxID_PLAY,
wxID_PAUSE,
wxID_NEXT,
wxID_PREV,
wxID_SELECTBACKEND,
wxID_SHOWINTERFACE,
// wxID_STOP, [built-in to wxWidgets]
// wxID_ABOUT, [built-in to wxWidgets]
// wxID_EXIT, [built-in to wxWidgets]
// Control event IDs
wxID_SLIDER,
wxID_PBSLIDER,
wxID_VOLSLIDER,
wxID_NOTEBOOK,
wxID_MEDIACTRL,
wxID_BUTTONNEXT,
wxID_BUTTONPREV,
wxID_BUTTONSTOP,
wxID_BUTTONPLAY,
wxID_BUTTONVD,
wxID_BUTTONVU,
wxID_LISTCTRL,
wxID_GAUGE
};
// ----------------------------------------------------------------------------
// wxMediaPlayerApp
// ----------------------------------------------------------------------------
class wxMediaPlayerApp : public wxApp
{
public:
#ifdef __WXMAC__
virtual void MacOpenFiles(const wxArrayString & fileNames ) wxOVERRIDE;
#endif
#if wxUSE_CMDLINE_PARSER
virtual void OnInitCmdLine(wxCmdLineParser& parser) wxOVERRIDE;
virtual bool OnCmdLineParsed(wxCmdLineParser& parser) wxOVERRIDE;
// Files specified on the command line, if any.
wxVector<wxString> m_params;
#endif // wxUSE_CMDLINE_PARSER
virtual bool OnInit() wxOVERRIDE;
protected:
class wxMediaPlayerFrame* m_frame;
};
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame
// ----------------------------------------------------------------------------
class wxMediaPlayerFrame : public wxFrame
{
public:
// Ctor/Dtor
wxMediaPlayerFrame(const wxString& title);
~wxMediaPlayerFrame();
// Menu event handlers
void OnQuit(wxCommandEvent& event);
void OnAbout(wxCommandEvent& event);
void OnOpenFileSamePage(wxCommandEvent& event);
void OnOpenFileNewPage(wxCommandEvent& event);
void OnOpenURLSamePage(wxCommandEvent& event);
void OnOpenURLNewPage(wxCommandEvent& event);
void OnCloseCurrentPage(wxCommandEvent& event);
void OnPlay(wxCommandEvent& event);
void OnPause(wxCommandEvent& event);
void OnStop(wxCommandEvent& event);
void OnNext(wxCommandEvent& event);
void OnPrev(wxCommandEvent& event);
void OnVolumeDown(wxCommandEvent& event);
void OnVolumeUp(wxCommandEvent& event);
void OnLoop(wxCommandEvent& event);
void OnShowInterface(wxCommandEvent& event);
void OnSelectBackend(wxCommandEvent& event);
// Key event handlers
void OnKeyDown(wxKeyEvent& event);
// Quickie for playing from command line
void AddToPlayList(const wxString& szString);
// ListCtrl event handlers
void OnChangeSong(wxListEvent& event);
// Media event handlers
void OnMediaLoaded(wxMediaEvent& event);
// Close event handlers
void OnClose(wxCloseEvent& event);
private:
// Common open file code
void OpenFile(bool bNewPage);
void OpenURL(bool bNewPage);
void DoOpenFile(const wxString& path, bool bNewPage);
void DoPlayFile(const wxString& path);
class wxMediaPlayerTimer* m_timer; // Timer to write info to status bar
wxNotebook* m_notebook; // Notebook containing our pages
// Maybe I should use more accessors, but for simplicity
// I'll allow the other classes access to our members
friend class wxMediaPlayerApp;
friend class wxMediaPlayerNotebookPage;
friend class wxMediaPlayerTimer;
};
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage
// ----------------------------------------------------------------------------
class wxMediaPlayerNotebookPage : public wxPanel
{
wxMediaPlayerNotebookPage(wxMediaPlayerFrame* parentFrame,
wxNotebook* book, const wxString& be = wxEmptyString);
// Slider event handlers
void OnBeginSeek(wxScrollEvent& event);
void OnEndSeek(wxScrollEvent& event);
void OnPBChange(wxScrollEvent& event);
void OnVolChange(wxScrollEvent& event);
// Media event handlers
void OnMediaPlay(wxMediaEvent& event);
void OnMediaPause(wxMediaEvent& event);
void OnMediaStop(wxMediaEvent& event);
void OnMediaFinished(wxMediaEvent& event);
public:
bool IsBeingDragged(); // accessor for m_bIsBeingDragged
// make wxMediaPlayerFrame able to access the private members
friend class wxMediaPlayerFrame;
int m_nLastFileId; // List ID of played file in listctrl
wxString m_szFile; // Name of currently playing file/location
wxMediaCtrl* m_mediactrl; // Our media control
class wxMediaPlayerListCtrl* m_playlist; // Our playlist
wxSlider* m_slider; // The slider below our media control
wxSlider* m_pbSlider; // Lower-left slider for adjusting speed
wxSlider* m_volSlider; // Lower-right slider for adjusting volume
int m_nLoops; // Number of times media has looped
bool m_bLoop; // Whether we are looping or not
bool m_bIsBeingDragged; // Whether the user is dragging the scroll bar
wxMediaPlayerFrame* m_parentFrame; // Main wxFrame of our sample
wxButton* m_prevButton; // Go to previous file button
wxButton* m_playButton; // Play/pause file button
wxButton* m_stopButton; // Stop playing file button
wxButton* m_nextButton; // Next file button
wxButton* m_vdButton; // Volume down button
wxButton* m_vuButton; // Volume up button
wxGauge* m_gauge; // Gauge to keep in line with slider
};
// ----------------------------------------------------------------------------
// wxMediaPlayerTimer
// ----------------------------------------------------------------------------
class wxMediaPlayerTimer : public wxTimer
{
public:
// Ctor
wxMediaPlayerTimer(wxMediaPlayerFrame* frame) {m_frame = frame;}
// Called each time the timer's timeout expires
void Notify() wxOVERRIDE;
wxMediaPlayerFrame* m_frame; // The wxMediaPlayerFrame
};
// ----------------------------------------------------------------------------
// wxMediaPlayerListCtrl
// ----------------------------------------------------------------------------
class wxMediaPlayerListCtrl : public wxListCtrl
{
public:
void AddToPlayList(const wxString& szString)
{
wxListItem kNewItem;
kNewItem.SetAlign(wxLIST_FORMAT_LEFT);
int nID = this->GetItemCount();
kNewItem.SetId(nID);
kNewItem.SetMask(wxLIST_MASK_DATA);
kNewItem.SetData(new wxString(szString));
this->InsertItem(kNewItem);
this->SetItem(nID, 0, "*");
this->SetItem(nID, 1, wxFileName(szString).GetName());
if (nID % 2)
{
kNewItem.SetBackgroundColour(wxColour(192,192,192));
this->SetItem(kNewItem);
}
}
void GetSelectedItem(wxListItem& listitem)
{
listitem.SetMask(wxLIST_MASK_TEXT | wxLIST_MASK_DATA);
int nLast = -1, nLastSelected = -1;
while ((nLast = this->GetNextItem(nLast,
wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED)) != -1)
{
listitem.SetId(nLast);
this->GetItem(listitem);
if ((listitem.GetState() & wxLIST_STATE_FOCUSED) )
break;
nLastSelected = nLast;
}
if (nLast == -1 && nLastSelected == -1)
return;
listitem.SetId(nLastSelected == -1 ? nLast : nLastSelected);
this->GetItem(listitem);
}
};
// ----------------------------------------------------------------------------
// wxPlayListDropTarget
//
// Drop target for playlist (i.e. allows users to drag a file from explorer into
// the playlist to add that file)
// ----------------------------------------------------------------------------
#if wxUSE_DRAG_AND_DROP
class wxPlayListDropTarget : public wxFileDropTarget
{
public:
wxPlayListDropTarget(wxMediaPlayerListCtrl& list) : m_list(list) {}
~wxPlayListDropTarget(){}
virtual bool OnDropFiles(wxCoord WXUNUSED(x), wxCoord WXUNUSED(y),
const wxArrayString& files) wxOVERRIDE
{
for (size_t i = 0; i < files.GetCount(); ++i)
{
m_list.AddToPlayList(files[i]);
}
return true;
}
wxMediaPlayerListCtrl& m_list;
};
#endif
// ============================================================================
//
// Implementation
//
// ============================================================================
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// [Functions]
//
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ----------------------------------------------------------------------------
// wxGetMediaStateText
//
// Converts a wxMediaCtrl state into something useful that we can display
// to the user
// ----------------------------------------------------------------------------
const wxString wxGetMediaStateText(int nState)
{
switch(nState)
{
case wxMEDIASTATE_PLAYING:
return "Playing";
case wxMEDIASTATE_STOPPED:
return "Stopped";
///case wxMEDIASTATE_PAUSED:
default:
return "Paused";
}
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// wxMediaPlayerApp
//
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ----------------------------------------------------------------------------
// This sets up this wxApp as the global wxApp that gui calls in wxWidgets
// use. For example, if you were to be in windows and use a file dialog,
// wxWidgets would use wxTheApp->GetHInstance() which would get the instance
// handle of the application. These routines in wx _DO NOT_ check to see if
// the wxApp exists, and thus will crash the application if you try it.
//
// wxIMPLEMENT_APP does this, and also implements the platform-specific entry
// routine, such as main or WinMain(). Use wxIMPLEMENT_APP_NO_MAIN if you do
// not desire this behaviour.
// ----------------------------------------------------------------------------
wxIMPLEMENT_APP(wxMediaPlayerApp);
// ----------------------------------------------------------------------------
// wxMediaPlayerApp command line parsing
// ----------------------------------------------------------------------------
#if wxUSE_CMDLINE_PARSER
void wxMediaPlayerApp::OnInitCmdLine(wxCmdLineParser& parser)
{
wxApp::OnInitCmdLine(parser);
parser.AddParam("input files",
wxCMD_LINE_VAL_STRING,
wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
}
bool wxMediaPlayerApp::OnCmdLineParsed(wxCmdLineParser& parser)
{
if ( !wxApp::OnCmdLineParsed(parser) )
return false;
for (size_t paramNr=0; paramNr < parser.GetParamCount(); ++paramNr)
m_params.push_back(parser.GetParam(paramNr));
return true;
}
#endif // wxUSE_CMDLINE_PARSER
// ----------------------------------------------------------------------------
// wxMediaPlayerApp::OnInit
//
// Where execution starts - akin to a main or WinMain.
// 1) Create the frame and show it to the user
// 2) Process filenames from the commandline
// 3) return true specifying that we want execution to continue past OnInit
// ----------------------------------------------------------------------------
bool wxMediaPlayerApp::OnInit()
{
if ( !wxApp::OnInit() )
return false;
// SetAppName() lets wxConfig and others know where to write
SetAppName("wxMediaPlayer");
wxMediaPlayerFrame *frame =
new wxMediaPlayerFrame("MediaPlayer wxWidgets Sample");
frame->Show(true);
#if wxUSE_CMDLINE_PARSER
if ( !m_params.empty() )
{
for ( size_t n = 0; n < m_params.size(); n++ )
frame->AddToPlayList(m_params[n]);
wxCommandEvent theEvent(wxEVT_MENU, wxID_NEXT);
frame->AddPendingEvent(theEvent);
}
#endif // wxUSE_CMDLINE_PARSER
return true;
}
#ifdef __WXMAC__
void wxMediaPlayerApp::MacOpenFiles(const wxArrayString & fileNames )
{
// Called when a user drags files over our app
m_frame->DoOpenFile(fileNames[0], true /* new page */);
}
#endif // __WXMAC__
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// wxMediaPlayerFrame
//
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame Constructor
//
// 1) Create our menus
// 2) Create our notebook control and add it to the frame
// 3) Create our status bar
// 4) Connect our events
// 5) Start our timer
// ----------------------------------------------------------------------------
wxMediaPlayerFrame::wxMediaPlayerFrame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(600,600))
{
SetIcon(wxICON(sample));
//
// Create Menus
//
wxMenu *fileMenu = new wxMenu;
wxMenu *controlsMenu = new wxMenu;
wxMenu *optionsMenu = new wxMenu;
wxMenu *helpMenu = new wxMenu;
wxMenu *debugMenu = new wxMenu;
fileMenu->Append(wxID_OPENFILESAMEPAGE, "&Open File\tCtrl-Shift-O",
"Open a File in the current notebook page");
fileMenu->Append(wxID_OPENFILENEWPAGE, "&Open File in a new page",
"Open a File in a new notebook page");
fileMenu->Append(wxID_OPENURLSAMEPAGE, "&Open URL",
"Open a URL in the current notebook page");
fileMenu->Append(wxID_OPENURLNEWPAGE, "&Open URL in a new page",
"Open a URL in a new notebook page");
fileMenu->AppendSeparator();
fileMenu->Append(wxID_CLOSECURRENTPAGE, "&Close Current Page\tCtrl-C",
"Close current notebook page");
fileMenu->AppendSeparator();
fileMenu->Append(wxID_EXIT,
"E&xit\tAlt-X",
"Quit this program");
controlsMenu->Append(wxID_PLAY, "&Play/Pause\tCtrl-P", "Resume/Pause playback");
controlsMenu->Append(wxID_STOP, "&Stop\tCtrl-S", "Stop playback");
controlsMenu->AppendSeparator();
controlsMenu->Append(wxID_PREV, "&Previous\tCtrl-B", "Go to previous track");
controlsMenu->Append(wxID_NEXT, "&Next\tCtrl-N", "Skip to next track");
optionsMenu->AppendCheckItem(wxID_LOOP,
"&Loop\tCtrl-L",
"Loop Selected Media");
optionsMenu->AppendCheckItem(wxID_SHOWINTERFACE,
"&Show Interface\tCtrl-I",
"Show wxMediaCtrl native controls");
debugMenu->Append(wxID_SELECTBACKEND,
"&Select Backend...\tCtrl-D",
"Select a backend manually");
helpMenu->Append(wxID_ABOUT,
"&About\tF1",
"Show about dialog");
wxMenuBar *menuBar = new wxMenuBar();
menuBar->Append(fileMenu, "&File");
menuBar->Append(controlsMenu, "&Controls");
menuBar->Append(optionsMenu, "&Options");
menuBar->Append(debugMenu, "&Debug");
menuBar->Append(helpMenu, "&Help");
SetMenuBar(menuBar);
//
// Create our notebook - using wxNotebook is luckily pretty
// simple and self-explanatory in most cases
//
m_notebook = new wxNotebook(this, wxID_NOTEBOOK);
//
// Create our status bar
//
#if wxUSE_STATUSBAR
// create a status bar just for fun (by default with 1 pane only)
CreateStatusBar(1);
#endif // wxUSE_STATUSBAR
//
// Connect events.
//
//
// Menu events
//
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnQuit, this,
wxID_EXIT);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnAbout, this,
wxID_ABOUT);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnLoop, this,
wxID_LOOP);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnShowInterface, this,
wxID_SHOWINTERFACE);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnOpenFileNewPage, this,
wxID_OPENFILENEWPAGE);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnOpenFileSamePage, this,
wxID_OPENFILESAMEPAGE);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnOpenURLNewPage, this,
wxID_OPENURLNEWPAGE);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnOpenURLSamePage, this,
wxID_OPENURLSAMEPAGE);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnCloseCurrentPage, this,
wxID_CLOSECURRENTPAGE);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnPlay, this,
wxID_PLAY);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnStop, this,
wxID_STOP);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnNext, this,
wxID_NEXT);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnPrev, this,
wxID_PREV);
Bind(wxEVT_MENU, &wxMediaPlayerFrame::OnSelectBackend, this,
wxID_SELECTBACKEND);
//
// Key events
//
wxTheApp->Bind(wxEVT_KEY_DOWN, &wxMediaPlayerFrame::OnKeyDown, this);
//
// Close events
//
Bind(wxEVT_CLOSE_WINDOW, &wxMediaPlayerFrame::OnClose, this);
//
// End of Events
//
//
// Create an initial notebook page so the user has something
// to work with without having to go file->open every time :).
//
wxMediaPlayerNotebookPage* page =
new wxMediaPlayerNotebookPage(this, m_notebook);
m_notebook->AddPage(page,
"",
true);
// Don't load previous files if we have some specified on the command line,
// we wouldn't play them otherwise (they'd have to be inserted into the
// play list at the beginning instead of being appended but we don't
// support this).
#if wxUSE_CMDLINE_PARSER
if ( wxGetApp().m_params.empty() )
#endif // wxUSE_CMDLINE_PARSER
{
//
// Here we load the our configuration -
// in our case we load all the files that were left in
// the playlist the last time the user closed our application
//
// As an exercise to the reader try modifying it so that
// it properly loads the playlist for each page without
// conflicting (loading the same data) with the other ones.
//
wxConfig conf;
wxString key, outstring;
for(int i = 0; ; ++i)
{
key.clear();
key << i;
if(!conf.Read(key, &outstring))
break;
page->m_playlist->AddToPlayList(outstring);
}
}
//
// Create a timer to update our status bar
//
m_timer = new wxMediaPlayerTimer(this);
m_timer->Start(500);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame Destructor
//
// 1) Deletes child objects implicitly
// 2) Delete our timer explicitly
// ----------------------------------------------------------------------------
wxMediaPlayerFrame::~wxMediaPlayerFrame()
{
// Shut down our timer
delete m_timer;
//
// Here we save our info to the registry or whatever
// mechanism the OS uses.
//
// This makes it so that when mediaplayer loads up again
// it restores the same files that were in the playlist
// this time, rather than the user manually re-adding them.
//
// We need to do conf->DeleteAll() here because by default
// the config still contains the same files as last time
// so we need to clear it before writing our new ones.
//
// TODO: Maybe you could add a menu option to the
// options menu to delete the configuration on exit -
// all you'd need to do is just remove everything after
// conf->DeleteAll() here
//
// As an exercise to the reader, try modifying this so
// that it saves the data for each notebook page
//
wxMediaPlayerListCtrl* playlist =
((wxMediaPlayerNotebookPage*)m_notebook->GetPage(0))->m_playlist;
wxConfig conf;
conf.DeleteAll();
for(int i = 0; i < playlist->GetItemCount(); ++i)
{
wxString* pData = (wxString*) playlist->GetItemData(i);
wxString s;
s << i;
conf.Write(s, *(pData));
delete pData;
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnClose
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnClose(wxCloseEvent& event)
{
event.Skip(); // really close the frame
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::AddToPlayList
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::AddToPlayList(const wxString& szString)
{
wxMediaPlayerNotebookPage* currentpage =
((wxMediaPlayerNotebookPage*)m_notebook->GetCurrentPage());
currentpage->m_playlist->AddToPlayList(szString);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnQuit
//
// Called from file->quit.
// Closes this application.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
// true is to force the frame to close
Close(true);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnAbout
//
// Called from help->about.
// Gets some info about this application.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
wxString msg;
msg.Printf( "This is a test of wxMediaCtrl.\n\n"
"Instructions:\n"
"The top slider shows the current the current position, "
"which you can change by dragging and releasing it.\n"
"The gauge (progress bar) shows the progress in "
"downloading data of the current file - it may always be "
"empty due to lack of support from the current backend.\n"
"The lower-left slider controls the volume and the lower-"
"right slider controls the playback rate/speed of the "
"media\n\n"
"Currently using: %s", wxVERSION_STRING);
wxMessageBox(msg, "About wxMediaCtrl test",
wxOK | wxICON_INFORMATION, this);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnLoop
//
// Called from file->loop.
// Changes the state of whether we want to loop or not.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnLoop(wxCommandEvent& WXUNUSED(event))
{
wxMediaPlayerNotebookPage* currentpage =
((wxMediaPlayerNotebookPage*)m_notebook->GetCurrentPage());
currentpage->m_bLoop = !currentpage->m_bLoop;
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnLoop
//
// Called from file->loop.
// Changes the state of whether we want to loop or not.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnShowInterface(wxCommandEvent& event)
{
wxMediaPlayerNotebookPage* currentpage =
((wxMediaPlayerNotebookPage*)m_notebook->GetCurrentPage());
if( !currentpage->m_mediactrl->ShowPlayerControls(event.IsChecked() ?
wxMEDIACTRLPLAYERCONTROLS_DEFAULT :
wxMEDIACTRLPLAYERCONTROLS_NONE) )
{
// error - uncheck and warn user
wxMenuItem* pSIItem = GetMenuBar()->FindItem(wxID_SHOWINTERFACE);
wxASSERT(pSIItem);
pSIItem->Check(!event.IsChecked());
if(event.IsChecked())
wxMessageBox("Could not show player controls");
else
wxMessageBox("Could not hide player controls");
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnOpenFileSamePage
//
// Called from file->openfile.
// Opens and plays a media file in the current notebook page
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnOpenFileSamePage(wxCommandEvent& WXUNUSED(event))
{
OpenFile(false);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnOpenFileNewPage
//
// Called from file->openfileinnewpage.
// Opens and plays a media file in a new notebook page
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnOpenFileNewPage(wxCommandEvent& WXUNUSED(event))
{
OpenFile(true);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OpenFile
//
// Opens a file dialog asking the user for a filename, then
// calls DoOpenFile which will add the file to the playlist and play it
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OpenFile(bool bNewPage)
{
wxFileDialog fd(this);
if(fd.ShowModal() == wxID_OK)
{
DoOpenFile(fd.GetPath(), bNewPage);
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::DoOpenFile
//
// Adds the file to our playlist, selects it in the playlist,
// and then calls DoPlayFile to play it
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::DoOpenFile(const wxString& path, bool bNewPage)
{
if(bNewPage)
{
m_notebook->AddPage(
new wxMediaPlayerNotebookPage(this, m_notebook),
path,
true);
}
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
if(currentpage->m_nLastFileId != -1)
currentpage->m_playlist->SetItemState(currentpage->m_nLastFileId,
0, wxLIST_STATE_SELECTED);
wxListItem newlistitem;
newlistitem.SetAlign(wxLIST_FORMAT_LEFT);
int nID;
newlistitem.SetId(nID = currentpage->m_playlist->GetItemCount());
newlistitem.SetMask(wxLIST_MASK_DATA | wxLIST_MASK_STATE);
newlistitem.SetState(wxLIST_STATE_SELECTED);
newlistitem.SetData(new wxString(path));
currentpage->m_playlist->InsertItem(newlistitem);
currentpage->m_playlist->SetItem(nID, 0, "*");
currentpage->m_playlist->SetItem(nID, 1, wxFileName(path).GetName());
if (nID % 2)
{
newlistitem.SetBackgroundColour(wxColour(192,192,192));
currentpage->m_playlist->SetItem(newlistitem);
}
DoPlayFile(path);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::DoPlayFile
//
// Pauses the file if its the currently playing file,
// otherwise it plays the file
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::DoPlayFile(const wxString& path)
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
wxListItem listitem;
currentpage->m_playlist->GetSelectedItem(listitem);
if( ( listitem.GetData() &&
currentpage->m_nLastFileId == listitem.GetId() &&
currentpage->m_szFile.compare(path) == 0 ) ||
( !listitem.GetData() &&
currentpage->m_nLastFileId != -1 &&
currentpage->m_szFile.compare(path) == 0)
)
{
if(currentpage->m_mediactrl->GetState() == wxMEDIASTATE_PLAYING)
{
if( !currentpage->m_mediactrl->Pause() )
wxMessageBox("Couldn't pause movie!");
}
else
{
if( !currentpage->m_mediactrl->Play() )
wxMessageBox("Couldn't play movie!");
}
}
else
{
int nNewId = listitem.GetData() ? listitem.GetId() :
currentpage->m_playlist->GetItemCount()-1;
m_notebook->SetPageText(m_notebook->GetSelection(),
wxFileName(path).GetName());
if(currentpage->m_nLastFileId != -1)
currentpage->m_playlist->SetItem(
currentpage->m_nLastFileId, 0, "*");
wxURI uripath(path);
if( uripath.IsReference() )
{
if( !currentpage->m_mediactrl->Load(path) )
{
wxMessageBox("Couldn't load file!");
currentpage->m_playlist->SetItem(nNewId, 0, "E");
}
else
{
currentpage->m_playlist->SetItem(nNewId, 0, "O");
}
}
else
{
if( !currentpage->m_mediactrl->Load(uripath) )
{
wxMessageBox("Couldn't load URL!");
currentpage->m_playlist->SetItem(nNewId, 0, "E");
}
else
{
currentpage->m_playlist->SetItem(nNewId, 0, "O");
}
}
currentpage->m_nLastFileId = nNewId;
currentpage->m_szFile = path;
currentpage->m_playlist->SetItem(currentpage->m_nLastFileId,
1, wxFileName(path).GetName());
currentpage->m_playlist->SetItem(currentpage->m_nLastFileId,
2, "");
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnMediaLoaded
//
// Called when the media is ready to be played - and does
// so, also gets the length of media and shows that in the list control
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnMediaLoaded(wxMediaEvent& WXUNUSED(evt))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
if( !currentpage->m_mediactrl->Play() )
{
wxMessageBox("Couldn't play movie!");
currentpage->m_playlist->SetItem(currentpage->m_nLastFileId, 0, "E");
}
else
{
currentpage->m_playlist->SetItem(currentpage->m_nLastFileId, 0, ">");
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnSelectBackend
//
// Little debugging routine - enter the class name of a backend and it
// will use that instead of letting wxMediaCtrl search the wxMediaBackend
// RTTI class list.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnSelectBackend(wxCommandEvent& WXUNUSED(evt))
{
wxString sBackend = wxGetTextFromUser("Enter backend to use");
if(sBackend.empty() == false) // could have been cancelled by the user
{
int sel = m_notebook->GetSelection();
if (sel != wxNOT_FOUND)
{
m_notebook->DeletePage(sel);
}
m_notebook->AddPage(new wxMediaPlayerNotebookPage(this, m_notebook,
sBackend
), "", true);
DoOpenFile(
((wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage())->m_szFile,
false);
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnOpenURLSamePage
//
// Called from file->openurl.
// Opens and plays a media file from a URL in the current notebook page
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnOpenURLSamePage(wxCommandEvent& WXUNUSED(event))
{
OpenURL(false);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnOpenURLNewPage
//
// Called from file->openurlinnewpage.
// Opens and plays a media file from a URL in a new notebook page
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnOpenURLNewPage(wxCommandEvent& WXUNUSED(event))
{
OpenURL(true);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OpenURL
//
// Just calls DoOpenFile with the url path - which calls DoPlayFile
// which handles the real dirty work
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OpenURL(bool bNewPage)
{
wxString sUrl = wxGetTextFromUser(
"Enter the URL that has the movie to play"
);
if(sUrl.empty() == false) // could have been cancelled by user
{
DoOpenFile(sUrl, bNewPage);
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnCloseCurrentPage
//
// Called when the user wants to close the current notebook page
//
// 1) Get the current page number (wxControl::GetSelection)
// 2) If there is no current page, break out
// 3) Delete the current page
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnCloseCurrentPage(wxCommandEvent& WXUNUSED(event))
{
if( m_notebook->GetPageCount() > 1 )
{
int sel = m_notebook->GetSelection();
if (sel != wxNOT_FOUND)
{
m_notebook->DeletePage(sel);
}
}
else
{
wxMessageBox("Cannot close main page");
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnPlay
//
// Called from file->play.
// Resumes the media if it is paused or stopped.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnPlay(wxCommandEvent& WXUNUSED(event))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
wxListItem listitem;
currentpage->m_playlist->GetSelectedItem(listitem);
if ( !listitem.GetData() )
{
int nLast = -1;
if ((nLast = currentpage->m_playlist->GetNextItem(nLast,
wxLIST_NEXT_ALL,
wxLIST_STATE_DONTCARE)) == -1)
{
// no items in list
wxMessageBox("No items in playlist!");
}
else
{
listitem.SetId(nLast);
currentpage->m_playlist->GetItem(listitem);
listitem.SetMask(listitem.GetMask() | wxLIST_MASK_STATE);
listitem.SetState(listitem.GetState() | wxLIST_STATE_SELECTED);
currentpage->m_playlist->SetItem(listitem);
wxASSERT(listitem.GetData());
DoPlayFile((*((wxString*) listitem.GetData())));
}
}
else
{
wxASSERT(listitem.GetData());
DoPlayFile((*((wxString*) listitem.GetData())));
}
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnKeyDown
//
// Deletes all selected files from the playlist if the backspace key is pressed
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnKeyDown(wxKeyEvent& event)
{
if(event.GetKeyCode() == WXK_BACK/*DELETE*/)
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
// delete all selected items
while(true)
{
wxInt32 nSelectedItem = currentpage->m_playlist->GetNextItem(
-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (nSelectedItem == -1)
break;
wxListItem listitem;
listitem.SetId(nSelectedItem);
currentpage->m_playlist->GetItem(listitem);
delete (wxString*) listitem.GetData();
currentpage->m_playlist->DeleteItem(nSelectedItem);
}
}
// Could be wxGetTextFromUser or something else important
if(event.GetEventObject() != this)
event.Skip();
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnStop
//
// Called from file->stop.
// Where it stops depends on whether you can seek in the
// media control or not - if you can it stops and seeks to the beginning,
// otherwise it will appear to be at the end - but it will start over again
// when Play() is called
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnStop(wxCommandEvent& WXUNUSED(evt))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
if( !currentpage->m_mediactrl->Stop() )
wxMessageBox("Couldn't stop movie!");
else
currentpage->m_playlist->SetItem(
currentpage->m_nLastFileId, 0, "[]");
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnChangeSong
//
// Routine that plays the currently selected file in the playlist.
// Called when the user actives the song from the playlist,
// and from other various places in the sample
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnChangeSong(wxListEvent& WXUNUSED(evt))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
wxListItem listitem;
currentpage->m_playlist->GetSelectedItem(listitem);
if(listitem.GetData())
DoPlayFile((*((wxString*) listitem.GetData())));
else
wxMessageBox("No selected item!");
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnPrev
//
// Tedious wxListCtrl stuff. Goes to prevous song in list, or if at the
// beginning goes to the last in the list.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnPrev(wxCommandEvent& WXUNUSED(event))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
if (currentpage->m_playlist->GetItemCount() == 0)
return;
wxInt32 nLastSelectedItem = -1;
while(true)
{
wxInt32 nSelectedItem = currentpage->m_playlist->GetNextItem(nLastSelectedItem,
wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (nSelectedItem == -1)
break;
nLastSelectedItem = nSelectedItem;
currentpage->m_playlist->SetItemState(nSelectedItem, 0, wxLIST_STATE_SELECTED);
}
if (nLastSelectedItem == -1)
{
// nothing selected, default to the file before the currently playing one
if(currentpage->m_nLastFileId == 0)
nLastSelectedItem = currentpage->m_playlist->GetItemCount() - 1;
else
nLastSelectedItem = currentpage->m_nLastFileId - 1;
}
else if (nLastSelectedItem == 0)
nLastSelectedItem = currentpage->m_playlist->GetItemCount() - 1;
else
nLastSelectedItem -= 1;
if(nLastSelectedItem == currentpage->m_nLastFileId)
return; // already playing... nothing to do
wxListItem listitem;
listitem.SetId(nLastSelectedItem);
listitem.SetMask(wxLIST_MASK_TEXT | wxLIST_MASK_DATA);
currentpage->m_playlist->GetItem(listitem);
listitem.SetMask(listitem.GetMask() | wxLIST_MASK_STATE);
listitem.SetState(listitem.GetState() | wxLIST_STATE_SELECTED);
currentpage->m_playlist->SetItem(listitem);
wxASSERT(listitem.GetData());
DoPlayFile((*((wxString*) listitem.GetData())));
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnNext
//
// Tedious wxListCtrl stuff. Goes to next song in list, or if at the
// end goes to the first in the list.
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnNext(wxCommandEvent& WXUNUSED(event))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
if (currentpage->m_playlist->GetItemCount() == 0)
return;
wxInt32 nLastSelectedItem = -1;
while(true)
{
wxInt32 nSelectedItem = currentpage->m_playlist->GetNextItem(nLastSelectedItem,
wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
if (nSelectedItem == -1)
break;
nLastSelectedItem = nSelectedItem;
currentpage->m_playlist->SetItemState(nSelectedItem, 0, wxLIST_STATE_SELECTED);
}
if (nLastSelectedItem == -1)
{
if(currentpage->m_nLastFileId == currentpage->m_playlist->GetItemCount() - 1)
nLastSelectedItem = 0;
else
nLastSelectedItem = currentpage->m_nLastFileId + 1;
}
else if (nLastSelectedItem == currentpage->m_playlist->GetItemCount() - 1)
nLastSelectedItem = 0;
else
nLastSelectedItem += 1;
if(nLastSelectedItem == currentpage->m_nLastFileId)
return; // already playing... nothing to do
wxListItem listitem;
listitem.SetMask(wxLIST_MASK_TEXT | wxLIST_MASK_DATA);
listitem.SetId(nLastSelectedItem);
currentpage->m_playlist->GetItem(listitem);
listitem.SetMask(listitem.GetMask() | wxLIST_MASK_STATE);
listitem.SetState(listitem.GetState() | wxLIST_STATE_SELECTED);
currentpage->m_playlist->SetItem(listitem);
wxASSERT(listitem.GetData());
DoPlayFile((*((wxString*) listitem.GetData())));
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnVolumeDown
//
// Lowers the volume of the media control by 5%
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnVolumeDown(wxCommandEvent& WXUNUSED(event))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
double dVolume = currentpage->m_mediactrl->GetVolume();
currentpage->m_mediactrl->SetVolume(dVolume < 0.05 ? 0.0 : dVolume - .05);
}
// ----------------------------------------------------------------------------
// wxMediaPlayerFrame::OnVolumeUp
//
// Increases the volume of the media control by 5%
// ----------------------------------------------------------------------------
void wxMediaPlayerFrame::OnVolumeUp(wxCommandEvent& WXUNUSED(event))
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_notebook->GetCurrentPage();
double dVolume = currentpage->m_mediactrl->GetVolume();
currentpage->m_mediactrl->SetVolume(dVolume > 0.95 ? 1.0 : dVolume + .05);
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// wxMediaPlayerTimer
//
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ----------------------------------------------------------------------------
// wxMediaPlayerTimer::Notify
//
// 1) Updates media information on the status bar
// 2) Sets the max/min length of the slider and guage
//
// Note that the reason we continually do this and don't cache it is because
// some backends such as GStreamer are dynamic change values all the time
// and often don't have things like duration or video size available
// until the media is actually being played
// ----------------------------------------------------------------------------
void wxMediaPlayerTimer::Notify()
{
wxMediaPlayerNotebookPage* currentpage =
(wxMediaPlayerNotebookPage*) m_frame->m_notebook->GetCurrentPage();
wxMediaCtrl* currentMediaCtrl = currentpage->m_mediactrl;
// Number of minutes/seconds total
wxLongLong llLength = currentpage->m_mediactrl->Length();
int nMinutes = (int) (llLength / 60000).GetValue();
int nSeconds = (int) ((llLength % 60000)/1000).GetValue();
// Duration string (i.e. MM:SS)
wxString sDuration;
sDuration.Printf("%2i:%02i", nMinutes, nSeconds);
// Number of minutes/seconds total
wxLongLong llTell = currentpage->m_mediactrl->Tell();
nMinutes = (int) (llTell / 60000).GetValue();
nSeconds = (int) ((llTell % 60000)/1000).GetValue();
// Position string (i.e. MM:SS)
wxString sPosition;
sPosition.Printf("%2i:%02i", nMinutes, nSeconds);
// Set the third item in the listctrl entry to the duration string
if(currentpage->m_nLastFileId >= 0)
currentpage->m_playlist->SetItem(
currentpage->m_nLastFileId, 2, sDuration);
// Setup the slider and gauge min/max values
currentpage->m_slider->SetRange(0, (int)(llLength / 1000).GetValue());
currentpage->m_gauge->SetRange(100);
// if the slider is not being dragged then update it with the song position
if(currentpage->IsBeingDragged() == false)
currentpage->m_slider->SetValue((long)(llTell / 1000).GetValue());
// Update the gauge with the download progress
wxLongLong llDownloadProgress =
currentpage->m_mediactrl->GetDownloadProgress();
wxLongLong llDownloadTotal =
currentpage->m_mediactrl->GetDownloadTotal();
if(llDownloadTotal.GetValue() != 0)
{
currentpage->m_gauge->SetValue(
(int) ((llDownloadProgress * 100) / llDownloadTotal).GetValue()
);
}
// GetBestSize holds the original video size
wxSize videoSize = currentMediaCtrl->GetBestSize();
// Now the big part - set the status bar text to
// hold various metadata about the media
#if wxUSE_STATUSBAR
m_frame->SetStatusText(wxString::Format(
"Size(x,y):%i,%i "
"Position:%s/%s Speed:%1.1fx "
"State:%s Loops:%i D/T:[%i]/[%i] V:%i%%",
videoSize.x,
videoSize.y,
sPosition,
sDuration,
currentMediaCtrl->GetPlaybackRate(),
wxGetMediaStateText(currentpage->m_mediactrl->GetState()),
currentpage->m_nLoops,
(int)llDownloadProgress.GetValue(),
(int)llDownloadTotal.GetValue(),
(int)(currentpage->m_mediactrl->GetVolume() * 100)));
#endif // wxUSE_STATUSBAR
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// wxMediaPlayerNotebookPage
//
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage Constructor
//
// Creates a media control and slider and adds it to this panel,
// along with some sizers for positioning
// ----------------------------------------------------------------------------
wxMediaPlayerNotebookPage::wxMediaPlayerNotebookPage(wxMediaPlayerFrame* parentFrame,
wxNotebook* theBook,
const wxString& szBackend)
: wxPanel(theBook, wxID_ANY),
m_nLastFileId(-1),
m_nLoops(0),
m_bLoop(false),
m_bIsBeingDragged(false),
m_parentFrame(parentFrame)
{
//
// Layout
//
// [wxMediaCtrl]
// [playlist]
// [5 control buttons]
// [slider]
// [gauge]
//
//
// Create and attach a 2-column grid sizer
//
wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
sizer->AddGrowableCol(0);
this->SetSizer(sizer);
//
// Create our media control
//
m_mediactrl = new wxMediaCtrl();
// Make sure creation was successful
bool bOK = m_mediactrl->Create(this, wxID_MEDIACTRL, wxEmptyString,
wxDefaultPosition, wxDefaultSize, 0,
// you could specify a macro backend here like
// wxMEDIABACKEND_WMP10);
// "wxPDFMediaBackend");
szBackend);
// you could change the cursor here like
// m_mediactrl->SetCursor(wxCURSOR_BLANK);
// note that this may not effect it if SetPlayerControls
// is set to something else than wxMEDIACTRLPLAYERCONTROLS_NONE
wxASSERT_MSG(bOK, "Could not create media control!");
wxUnusedVar(bOK);
sizer->Add(m_mediactrl, wxSizerFlags().Expand().Border());
//
// Create the playlist/listctrl
//
m_playlist = new wxMediaPlayerListCtrl();
m_playlist->Create(this, wxID_LISTCTRL, wxDefaultPosition,
wxDefaultSize,
wxLC_REPORT // wxLC_LIST
| wxSUNKEN_BORDER);
// Set the background of our listctrl to white
m_playlist->SetBackgroundColour(*wxWHITE);
// The layout of the headers of the listctrl are like
// | | File | Length
//
// Where Column one is a character representing the state the file is in:
// * - not the current file
// E - Error has occured
// > - Currently Playing
// [] - Stopped
// || - Paused
// (( - Volume Down 5%
// )) - Volume Up 5%
//
// Column two is the name of the file
//
// Column three is the length in seconds of the file
m_playlist->AppendColumn(_(""), wxLIST_FORMAT_CENTER, 20);
m_playlist->AppendColumn(_("File"), wxLIST_FORMAT_LEFT, /*wxLIST_AUTOSIZE_USEHEADER*/305);
m_playlist->AppendColumn(_("Length"), wxLIST_FORMAT_CENTER, 75);
#if wxUSE_DRAG_AND_DROP
m_playlist->SetDropTarget(new wxPlayListDropTarget(*m_playlist));
#endif
sizer->Add(m_playlist, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND, 5);
//
// Create the control buttons
// TODO/FIXME/HACK: This part about sizers is really a nice hack
// and probably isn't proper
//
wxBoxSizer* horsizer1 = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer* vertsizer = new wxBoxSizer(wxHORIZONTAL);
m_prevButton = new wxButton();
m_playButton = new wxButton();
m_stopButton = new wxButton();
m_nextButton = new wxButton();
m_vdButton = new wxButton();
m_vuButton = new wxButton();
m_prevButton->Create(this, wxID_BUTTONPREV, "|<");
m_prevButton->SetToolTip("Previous");
m_playButton->Create(this, wxID_BUTTONPLAY, ">");
m_playButton->SetToolTip("Play");
m_stopButton->Create(this, wxID_BUTTONSTOP, "[]");
m_stopButton->SetToolTip("Stop");
m_nextButton->Create(this, wxID_BUTTONNEXT, ">|");
m_nextButton->SetToolTip("Next");
m_vdButton->Create(this, wxID_BUTTONVD, "((");
m_vdButton->SetToolTip("Volume down");
m_vuButton->Create(this, wxID_BUTTONVU, "))");
m_vuButton->SetToolTip("Volume up");
vertsizer->Add(m_prevButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
vertsizer->Add(m_playButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
vertsizer->Add(m_stopButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
vertsizer->Add(m_nextButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
vertsizer->Add(m_vdButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
vertsizer->Add(m_vuButton, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
horsizer1->Add(vertsizer, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);
sizer->Add(horsizer1, 0, wxALIGN_CENTER_VERTICAL|wxALIGN_CENTER_HORIZONTAL|wxALL, 5);
//
// Create our slider
//
m_slider = new wxSlider(this, wxID_SLIDER, 0, // init
0, // start
1, // end, dummy but must be greater than start
wxDefaultPosition, wxDefaultSize,
wxSL_HORIZONTAL );
sizer->Add(m_slider, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND , 5);
//
// Create the gauge
//
m_gauge = new wxGauge();
m_gauge->Create(this, wxID_GAUGE, 0, wxDefaultPosition, wxDefaultSize,
wxGA_HORIZONTAL | wxGA_SMOOTH);
sizer->Add(m_gauge, 0, wxALIGN_CENTER_HORIZONTAL|wxALL|wxEXPAND , 5);
//
// Create the speed/volume sliders
//
wxBoxSizer* horsizer3 = new wxBoxSizer(wxHORIZONTAL);
m_volSlider = new wxSlider(this, wxID_VOLSLIDER, 100, // init
0, // start
100, // end
wxDefaultPosition, wxSize(250,20),
wxSL_HORIZONTAL );
horsizer3->Add(m_volSlider, 1, wxALL, 5);
m_pbSlider = new wxSlider(this, wxID_PBSLIDER, 4, // init
1, // start
16, // end
wxDefaultPosition, wxSize(250,20),
wxSL_HORIZONTAL );
horsizer3->Add(m_pbSlider, 1, wxALL, 5);
sizer->Add(horsizer3, 1, wxCENTRE | wxALL, 5);
// Now that we have all our rows make some of them growable
sizer->AddGrowableRow(0);
//
// ListCtrl events
//
Bind(wxEVT_LIST_ITEM_ACTIVATED, &wxMediaPlayerFrame::OnChangeSong, parentFrame,
wxID_LISTCTRL);
//
// Slider events
//
Bind(wxEVT_SCROLL_THUMBTRACK, &wxMediaPlayerNotebookPage::OnBeginSeek, this,
wxID_SLIDER);
Bind(wxEVT_SCROLL_THUMBRELEASE, &wxMediaPlayerNotebookPage::OnEndSeek, this,
wxID_SLIDER);
Bind(wxEVT_SCROLL_THUMBRELEASE, &wxMediaPlayerNotebookPage::OnPBChange, this,
wxID_PBSLIDER);
Bind(wxEVT_SCROLL_THUMBRELEASE, &wxMediaPlayerNotebookPage::OnVolChange, this,
wxID_VOLSLIDER);
//
// Media Control events
//
Bind(wxEVT_MEDIA_PLAY, &wxMediaPlayerNotebookPage::OnMediaPlay, this,
wxID_MEDIACTRL);
Bind(wxEVT_MEDIA_PAUSE, &wxMediaPlayerNotebookPage::OnMediaPause, this,
wxID_MEDIACTRL);
Bind(wxEVT_MEDIA_STOP, &wxMediaPlayerNotebookPage::OnMediaStop, this,
wxID_MEDIACTRL);
Bind(wxEVT_MEDIA_FINISHED, &wxMediaPlayerNotebookPage::OnMediaFinished, this,
wxID_MEDIACTRL);
Bind(wxEVT_MEDIA_LOADED, &wxMediaPlayerFrame::OnMediaLoaded, parentFrame,
wxID_MEDIACTRL);
//
// Button events
//
Bind(wxEVT_BUTTON, &wxMediaPlayerFrame::OnPrev, parentFrame,
wxID_BUTTONPREV);
Bind(wxEVT_BUTTON, &wxMediaPlayerFrame::OnPlay, parentFrame,
wxID_BUTTONPLAY);
Bind(wxEVT_BUTTON, &wxMediaPlayerFrame::OnStop, parentFrame,
wxID_BUTTONSTOP);
Bind(wxEVT_BUTTON, &wxMediaPlayerFrame::OnNext, parentFrame,
wxID_BUTTONNEXT);
Bind(wxEVT_BUTTON, &wxMediaPlayerFrame::OnVolumeDown, parentFrame,
wxID_BUTTONVD);
Bind(wxEVT_BUTTON, &wxMediaPlayerFrame::OnVolumeUp, parentFrame,
wxID_BUTTONVU);
}
// ----------------------------------------------------------------------------
// MyNotebook::OnBeginSeek
//
// Sets m_bIsBeingDragged to true to stop the timer from changing the position
// of our slider
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnBeginSeek(wxScrollEvent& WXUNUSED(event))
{
m_bIsBeingDragged = true;
}
// ----------------------------------------------------------------------------
// MyNotebook::OnEndSeek
//
// Called from file->seek.
// Called when the user moves the slider -
// seeks to a position within the media
// then sets m_bIsBeingDragged to false to ok the timer to change the position
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnEndSeek(wxScrollEvent& WXUNUSED(event))
{
if( m_mediactrl->Seek(
m_slider->GetValue() * 1000
) == wxInvalidOffset )
wxMessageBox("Couldn't seek in movie!");
m_bIsBeingDragged = false;
}
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage::IsBeingDragged
//
// Returns true if the user is dragging the slider
// ----------------------------------------------------------------------------
bool wxMediaPlayerNotebookPage::IsBeingDragged()
{
return m_bIsBeingDragged;
}
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage::OnVolChange
//
// Called when the user is done dragging the volume-changing slider
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnVolChange(wxScrollEvent& WXUNUSED(event))
{
if( m_mediactrl->SetVolume(
m_volSlider->GetValue() / 100.0
) == false )
wxMessageBox("Couldn't set volume!");
}
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage::OnPBChange
//
// Called when the user is done dragging the speed-changing slider
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnPBChange(wxScrollEvent& WXUNUSED(event))
{
if( m_mediactrl->SetPlaybackRate(
m_pbSlider->GetValue() * .25
) == false )
wxMessageBox("Couldn't set playbackrate!");
}
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage::OnMediaPlay
//
// Called when the media plays.
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnMediaPlay(wxMediaEvent& WXUNUSED(event))
{
m_playlist->SetItem(m_nLastFileId, 0, ">");
}
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage::OnMediaPause
//
// Called when the media is paused.
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnMediaPause(wxMediaEvent& WXUNUSED(event))
{
m_playlist->SetItem(m_nLastFileId, 0, "||");
}
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage::OnMediaStop
//
// Called when the media stops.
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnMediaStop(wxMediaEvent& WXUNUSED(event))
{
m_playlist->SetItem(m_nLastFileId, 0, "[]");
}
// ----------------------------------------------------------------------------
// wxMediaPlayerNotebookPage::OnMediaFinished
//
// Called when the media finishes playing.
// Here we loop it if the user wants to (has been selected from file menu)
// ----------------------------------------------------------------------------
void wxMediaPlayerNotebookPage::OnMediaFinished(wxMediaEvent& WXUNUSED(event))
{
if(m_bLoop)
{
if ( !m_mediactrl->Play() )
{
wxMessageBox("Couldn't loop movie!");
m_playlist->SetItem(m_nLastFileId, 0, "E");
}
else
++m_nLoops;
}
else
{
m_playlist->SetItem(m_nLastFileId, 0, "[]");
}
}
//
// End of MediaPlayer sample
//
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.