text
stringlengths 1
1.05M
|
|---|
declare function _default(directory: any): string[];
export default _default;
|
#! /bin/sh
set -e
# Smoke-test wt2447_join_main_table as part of running "make check".
if [ -n "$1" ]
then
# If the test binary is passed in manually.
test_bin=$1
else
# If $binary_dir isn't set, default to using the build directory
# this script resides under. Our CMake build will sync a copy of this
# script to the build directory. Note this assumes we are executing a
# copy of the script that lives under the build directory. Otherwise
# passing the binary path is required.
binary_dir=${binary_dir:-`dirname $0`}
test_bin=$binary_dir/test_wt2447_join_main_table
fi
$TEST_WRAPPER $test_bin -t r
$TEST_WRAPPER $test_bin -t c
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-147
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.01.26 at 02:04:22 PM MST
//
package net.opengis.wfs._110;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import net.opengis.ows._100.KeywordsType;
/**
*
* An element of this type that describes a GML object in an
* application namespace shall have an xml xmlns specifier,
* e.g. xmlns:bo="http://www.BlueOx.org/BlueOx"
*
*
* <p>Java class for GMLObjectTypeType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GMLObjectTypeType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Name" type="{http://www.w3.org/2001/XMLSchema}QName"/>
* <element name="Title" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Abstract" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{http://www.opengis.net/ows}Keywords" maxOccurs="unbounded" minOccurs="0"/>
* <element name="OutputFormats" type="{http://www.opengis.net/wfs}OutputFormatListType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GMLObjectTypeType", propOrder = {
"name",
"title",
"_abstract",
"keywords",
"outputFormats"
})
public class GMLObjectTypeType {
@XmlElement(name = "Name", required = true)
protected QName name;
@XmlElement(name = "Title")
protected String title;
@XmlElement(name = "Abstract")
protected String _abstract;
@XmlElement(name = "Keywords", namespace = "http://www.opengis.net/ows")
protected List<KeywordsType> keywords;
@XmlElement(name = "OutputFormats")
protected OutputFormatListType outputFormats;
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link QName }
*
*/
public QName getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link QName }
*
*/
public void setName(QName value) {
this.name = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the abstract property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAbstract() {
return _abstract;
}
/**
* Sets the value of the abstract property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAbstract(String value) {
this._abstract = value;
}
/**
* Gets the value of the keywords property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the keywords property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getKeywords().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link KeywordsType }
*
*
*/
public List<KeywordsType> getKeywords() {
if (keywords == null) {
keywords = new ArrayList<KeywordsType>();
}
return this.keywords;
}
/**
* Gets the value of the outputFormats property.
*
* @return
* possible object is
* {@link OutputFormatListType }
*
*/
public OutputFormatListType getOutputFormats() {
return outputFormats;
}
/**
* Sets the value of the outputFormats property.
*
* @param value
* allowed object is
* {@link OutputFormatListType }
*
*/
public void setOutputFormats(OutputFormatListType value) {
this.outputFormats = value;
}
}
|
/**
* Classe de gestion de la page FAQ
*
* <pre>
* Elias 08/03/15 Création
* </pre>
* @author Elias
* @version 1.0
* @package default
*/
function Faq()
{
// ==== Constructeur ====
} // Faq
Faq.prototype = {
/**
* Traitements lancés en fin de chargement de la page
*/
ready: function()
{
$(document).on('click', '.RBZ_faqQuestion', function() {
$(this).children('div').toggle();
$(this).children('.RBZ_faq_down').toggleClass('selected');
if ($(this).children('.RBZ_faq_down').hasClass('selected')) {
$(this).children('.RBZ_faq_down').html(' ˄');
} else {
$(this).children('.RBZ_faq_down').html(' ˅');
}
return false;
});
$(document).on('click', '#div_RBZ_faqMenu ul li', function() {
// ==== Réinitialisation ====
$('#div_RBZ_faqMenu ul li').css('border-left', 'none');
// ---- Effet active ----
$(this).css('border-left', '3px solid #f04f61');
});
}, // ready
/**
* Token de fin
*/
_endPrototype: null
}; // Global.prototype
//==== Définition de l'objet Global goGlobal ====
var goFaq = new Faq();
goFaq.ready();
|
def normalize_dataset(data):
"""
Normalize dataset by subtracting mean and dividing by standard deviation
:param data: input dataset
:return: normalized dataset
"""
mean = np.mean(data, 0)
std = np.std(data, 0)
data_norm = (data - mean) / std
return data_norm
|
#!/bin/bash
mkdir --mode=700 -p ~/.ssh ~/.gnupg
|
#! /usr/bin/env nix-shell
#! nix-shell -i bash -p nix coreutils buildkite-agent
set -euo pipefail
cd `dirname $0`/..
echo "--- Build"
nix build .#benchmarks.cardano-wallet.latency -o bench-latency-shelley
# Note: the tracing will not work if program output is piped
# to another process (e.g. "tee").
# It says "Error: Switchboard's queue full, dropping log items!"
echo "+++ Run benchmark - shelley"
( cd lib/shelley && ../../bench-latency-shelley/bin/latency )
|
<filename>curry.js
/**
* Converts an n-ary function
* f :: (t_1, t_2, ..., t_n) -> r
* To its equivalent curried form
* f :: t_1 -> t_2 -> ... -> t_n -> r
*/
const curry = (fn, ...args) => {
return (...rest) => {
return fn(...args, ...rest);
};
};
export { curry };
|
import dayjs from 'dayjs';
import dayjsDuration from 'dayjs/plugin/duration';
import React, { useEffect, useState } from 'react';
import { apis } from '../apis';
import { Button, LinkButton } from '../components/button';
import { CheckBox } from '../components/checkbox';
import { FOCUS_END_CLASS, FOCUS_START_CLASS } from '../components/constants';
import {
Dialog,
DialogBody,
DialogFooter,
DialogHeader,
DialogProps,
DialogTitle,
} from '../components/dialog';
import { Indent } from '../components/indent';
import { ControlLabel, Label, LabelWrapper, SubLabel } from '../components/label';
import { List, ListItem } from '../components/list';
import { Portal } from '../components/portal';
import { Row, RowItem } from '../components/row';
import {
Section,
SectionBody,
SectionHeader,
SectionItem,
SectionTitle,
} from '../components/section';
import { Text } from '../components/text';
import { TextArea } from '../components/textarea';
import { usePrevious } from '../components/utilities';
import { ALT_FLOW_REDIRECT_URL } from '../constants';
import '../dayjs-locales';
import { translate } from '../locales';
import { addMessageListeners, sendMessage } from '../messages';
import { supportedClouds } from '../supported-clouds';
import { CloudId } from '../types';
import { AltURL, isErrorResult, stringEntries } from '../utilities';
import { FromNow } from './from-now';
import { useOptionsContext } from './options-context';
import { Select, SelectOption } from './select';
import { SetBooleanItem } from './set-boolean-item';
import { SetIntervalItem } from './set-interval-item';
dayjs.extend(dayjsDuration);
const TurnOnSyncDialog: React.VFC<
{ setSyncCloudId: React.Dispatch<React.SetStateAction<CloudId | false | null>> } & DialogProps
> = ({ close, open, setSyncCloudId }) => {
const {
platformInfo: { os },
} = useOptionsContext();
const [state, setState] = useState({
phase: 'none' as 'none' | 'auth' | 'auth-alt' | 'conn' | 'conn-alt',
selectedCloudId: 'googleDrive' as CloudId,
useAltFlow: false,
authCode: '',
});
const prevOpen = usePrevious(open);
if (open && !prevOpen) {
state.phase = 'none';
state.selectedCloudId = 'googleDrive';
state.useAltFlow = false;
state.authCode = '';
}
const forceAltFlow = supportedClouds[state.selectedCloudId].shouldUseAltFlow(os);
return (
<Dialog aria-labelledby="turnOnSyncDialogTitle" close={close} open={open}>
<DialogHeader>
<DialogTitle id="turnOnSyncDialogTitle">
{translate('options_turnOnSyncDialog_title')}
</DialogTitle>
</DialogHeader>
<DialogBody>
<Row>
<RowItem>
<Select
className={state.phase === 'none' ? FOCUS_START_CLASS : ''}
disabled={state.phase !== 'none'}
value={state.selectedCloudId}
onChange={e =>
setState(s => ({ ...s, selectedCloudId: e.currentTarget.value as CloudId }))
}
>
{stringEntries(supportedClouds).map(([id, cloud]) => (
<SelectOption key={id} value={id}>
{translate(cloud.messageNames.sync)}
</SelectOption>
))}
</Select>
</RowItem>
</Row>
<Row>
<RowItem expanded>
<Text>
{translate(supportedClouds[state.selectedCloudId].messageNames.syncDescription)}
</Text>
</RowItem>
</Row>
<Row>
<RowItem>
<Indent>
<CheckBox
checked={forceAltFlow || state.useAltFlow}
disabled={state.phase !== 'none' || forceAltFlow}
id="useAltFlow"
onChange={e => setState(s => ({ ...s, useAltFlow: e.currentTarget.checked }))}
/>
</Indent>
</RowItem>
<RowItem expanded>
<LabelWrapper disabled={state.phase !== 'none' || forceAltFlow}>
<ControlLabel for="useAltFlow">
{translate('options_turnOnSyncDialog_useAltFlow')}
</ControlLabel>
</LabelWrapper>
</RowItem>
</Row>
{(forceAltFlow || state.useAltFlow) && (
<Row>
<RowItem expanded>
<Text>
{translate(
'options_turnOnSyncDialog_altFlowDescription',
new AltURL(ALT_FLOW_REDIRECT_URL).host,
)}
</Text>
</RowItem>
</Row>
)}
{state.phase === 'auth-alt' || state.phase === 'conn-alt' ? (
<Row>
<RowItem expanded>
<LabelWrapper fullWidth>
<ControlLabel for="authCode">
{translate('options_turnOnSyncDialog_altFlowAuthCodeLabel')}
</ControlLabel>
</LabelWrapper>
<TextArea
breakAll
className={state.phase === 'auth-alt' ? FOCUS_START_CLASS : ''}
disabled={state.phase !== 'auth-alt'}
id="authCode"
rows={2}
value={state.authCode}
onChange={e => {
setState(s => ({ ...s, authCode: e.currentTarget.value }));
}}
/>
</RowItem>
</Row>
) : null}
</DialogBody>
<DialogFooter>
<Row right>
<RowItem>
<Button
className={
state.phase === 'auth' || state.phase === 'conn' || state.phase === 'conn-alt'
? `${FOCUS_START_CLASS} ${FOCUS_END_CLASS}`
: state.phase === 'auth-alt' && !state.authCode
? FOCUS_END_CLASS
: ''
}
onClick={close}
>
{translate('cancelButton')}
</Button>
</RowItem>
<RowItem>
<Button
className={
state.phase === 'none' || (state.phase === 'auth-alt' && state.authCode)
? FOCUS_END_CLASS
: ''
}
disabled={!(state.phase === 'none' || (state.phase === 'auth-alt' && state.authCode))}
primary
onClick={() => {
void (async () => {
let useAltFlow: boolean;
let authCode: string;
if (state.phase === 'auth-alt') {
useAltFlow = true;
authCode = state.authCode;
} else {
const cloud = supportedClouds[state.selectedCloudId];
useAltFlow = forceAltFlow || state.useAltFlow;
setState(s => ({ ...s, phase: useAltFlow ? 'auth-alt' : 'auth' }));
try {
const granted = await apis.permissions.request({
origins: [
...cloud.hostPermissions,
...(useAltFlow ? [ALT_FLOW_REDIRECT_URL] : []),
],
});
if (!granted) {
throw new Error('Not granted');
}
authCode = (await cloud.authorize(useAltFlow)).authorizationCode;
} catch {
setState(s => ({ ...s, phase: 'none' }));
return;
}
}
setState(s => ({ ...s, phase: useAltFlow ? 'conn-alt' : 'conn' }));
try {
const connected = await sendMessage(
'connect-to-cloud',
state.selectedCloudId,
authCode,
useAltFlow,
);
if (!connected) {
throw new Error('Not connected');
}
} catch {
return;
} finally {
setState(s => ({ ...s, phase: 'none' }));
}
setSyncCloudId(state.selectedCloudId);
close();
})();
}}
>
{translate('options_turnOnSyncDialog_turnOnSyncButton')}
</Button>
</RowItem>
</Row>
</DialogFooter>
</Dialog>
);
};
const TurnOnSync: React.VFC<{
syncCloudId: CloudId | false | null;
setSyncCloudId: React.Dispatch<React.SetStateAction<CloudId | false | null>>;
}> = ({ syncCloudId, setSyncCloudId }) => {
const [turnOnSyncDialogOpen, setTurnOnSyncDialogOpen] = useState(false);
return (
<SectionItem>
<Row>
<RowItem expanded>
{syncCloudId ? (
<LabelWrapper>
<Label>{translate(supportedClouds[syncCloudId].messageNames.syncTurnedOn)}</Label>
</LabelWrapper>
) : (
<LabelWrapper>
<Label>{translate('options_syncFeature')}</Label>
<SubLabel>{translate('options_syncFeatureDescription')}</SubLabel>
</LabelWrapper>
)}
</RowItem>
<RowItem>
{syncCloudId ? (
<Button
onClick={() => {
void sendMessage('disconnect-from-cloud');
setSyncCloudId(false);
}}
>
{translate('options_turnOffSync')}
</Button>
) : (
<Button
primary
onClick={() => {
setTurnOnSyncDialogOpen(true);
}}
>
{translate('options_turnOnSync')}
</Button>
)}
</RowItem>
</Row>
<Portal id="turnOnSyncDialogPortal">
<TurnOnSyncDialog
close={() => setTurnOnSyncDialogOpen(false)}
open={turnOnSyncDialogOpen}
setSyncCloudId={setSyncCloudId}
/>
</Portal>
</SectionItem>
);
};
const SyncNow: React.VFC<{ syncCloudId: CloudId | false | null }> = props => {
const {
initialItems: { syncResult: initialSyncResult },
} = useOptionsContext();
const [syncResult, setSyncResult] = useState(initialSyncResult);
const [updated, setUpdated] = useState(false);
const [syncing, setSyncing] = useState(false);
useEffect(
() =>
addMessageListeners({
syncing: () => {
setUpdated(false);
setSyncing(true);
},
synced: (result, updated) => {
setSyncResult(result);
setUpdated(updated);
setSyncing(false);
},
}),
[],
);
return (
<SectionItem>
<Row>
<RowItem expanded>
<LabelWrapper>
<Label>{translate('options_syncResult')}</Label>
<SubLabel>
{syncing ? (
translate('options_syncRunning')
) : !props.syncCloudId || !syncResult ? (
translate('options_syncNever')
) : isErrorResult(syncResult) ? (
translate('error', syncResult.message)
) : (
<FromNow time={dayjs(syncResult.timestamp)} />
)}
{updated ? (
<>
{' '}
<LinkButton
onClick={() => {
window.location.reload();
}}
>
{translate('options_syncReloadButton')}
</LinkButton>
</>
) : null}
</SubLabel>
</LabelWrapper>
</RowItem>
<RowItem>
<Button
disabled={syncing || !props.syncCloudId}
onClick={() => {
void sendMessage('sync');
}}
>
{translate('options_syncNowButton')}
</Button>
</RowItem>
</Row>
</SectionItem>
);
};
const SyncCategories: React.VFC<{ disabled: boolean }> = ({ disabled }) => (
<SectionItem>
<Row>
<RowItem expanded>
<LabelWrapper>
<Label>{translate('options_syncCategories')}</Label>
</LabelWrapper>
</RowItem>
</Row>
<Row>
<RowItem>
<Indent />
</RowItem>
<RowItem expanded>
<List>
<ListItem>
<SetBooleanItem
disabled={disabled}
itemKey="syncBlocklist"
label={translate('options_syncBlocklist')}
/>
</ListItem>
<ListItem>
<SetBooleanItem
disabled={disabled}
itemKey="syncGeneral"
label={translate('options_syncGeneral')}
/>
</ListItem>
<ListItem>
<SetBooleanItem
disabled={disabled}
itemKey="syncAppearance"
label={translate('options_syncAppearance')}
/>
</ListItem>
<ListItem>
<SetBooleanItem
disabled={disabled}
itemKey="syncSubscriptions"
label={translate('options_syncSubscriptions')}
/>
</ListItem>
</List>
</RowItem>
</Row>
</SectionItem>
);
export const SyncSection: React.VFC = () => {
const {
initialItems: { syncCloudId: initialSyncCloudId },
/* #if FIREFOX
platformInfo: { os },
*/
// #endif
} = useOptionsContext();
const [syncCloudId, setSyncCloudId] = useState(initialSyncCloudId);
/* #if FIREFOX
if (os === 'android') {
return null;
}
*/
// #endif
return (
<Section aria-labelledby="syncSectionTitle" id="sync">
<SectionHeader>
<SectionTitle id="syncSectionTitle">{translate('options_syncTitle')}</SectionTitle>
</SectionHeader>
<SectionBody>
<TurnOnSync setSyncCloudId={setSyncCloudId} syncCloudId={syncCloudId} />
<SyncNow syncCloudId={syncCloudId} />
<SyncCategories disabled={!syncCloudId} />
<SectionItem>
<SetIntervalItem
disabled={!syncCloudId}
itemKey="syncInterval"
label={translate('options_syncInterval')}
valueOptions={[5, 15, 30, 60, 120, 300]}
/>
</SectionItem>
</SectionBody>
</Section>
);
};
|
#include <iostream>
#include <stack>
using namespace std;
int evaluatePostfix(string exp)
{
stack<int> s;
for (int i = 0; i < exp.length(); i++) {
if (isdigit(exp[i]))
s.push(exp[i] - '0');
else {
int val1 = s.top();
s.pop();
int val2 = s.top();
s.pop();
switch (exp[i]) {
case '+':
s.push(val2 + val1);
break;
case '-':
s.push(val2 - val1);
break;
case '*':
s.push(val2 * val1);
break;
case '/':
s.push(val2/val1);
break;
}
}
}
return s.top();
}
int main()
{
string exp = "2 3 + 5 *";
cout << evaluatePostfix(exp) << endl;
}
|
mylist = [1, 2, 3, 4, 5]
for item in mylist:
print(item)
|
#!/bin/sh
home-manager switch
~/.emacs.d/bin/doom sync
|
import Layout from '@/views/layout/Layout';
const rolesRouter = {
path: '/roles',
component: Layout,
name: 'Roles',
redirect: '/roles/list',
meta: {
title: 'roles',
icon: 'lock',
permission: 'role.view'
},
children: [
{
path: 'create',
component: () => import('@/views/role/create'),
name: 'CreateRole',
meta: { title: 'createRole', icon: 'edit', permission: 'role.manage' },
hidden: true
},
{
path: 'edit/:id(\\d+)',
component: () => import('@/views/role/edit'),
name: 'EditRole',
meta: { title: 'editRole', noCache: true, permission: 'role.manage' },
hidden: true
},
{
path: 'view/:id(\\d+)',
component: () => import('@/views/role/components/RoleView'),
name: 'ViewRole',
meta: { title: 'viewRole', noCache: true, permission: 'role.view' },
hidden: true
},
{
path: 'list',
component: () => import('@/views/role/list'),
name: 'RoleList',
meta: { title: 'roleList', icon: 'lock', permission: 'role.view' }
}
]
};
export default rolesRouter;
|
const schema = {
"image": "",
"uploadDate": "",
"name": "",
"title": "",
"des": ""
}
const extend = {
createdAt: 'createdTs',
updateAt: 'updateTs'
}
const name = 'collage-image'
module.exports = {
schema,
extend,
name
}
|
#!/bin/bash
# set -e
DEBUG=0
VERSION=1.0.0
# SDK_INSTALLATION = -1 = None
# SDK_INSTALLATION = 0 = Basic
# SDK_INSTALLATION = 1 = Full
# SDK_UPDATE = 0 = Force Installtion if exists and not --none
# SDK_UPDATE = 1 = Update if SDK exists
# NO_JAVA = 0 = With Java Installation
# NO_JAVA = 1 = Skip Java Installation
# NO_APT = 0 = With APT Update
# NO_APT = 1 = Skip APT Update
SDK_INSTALLATION=0
SDK_UPDATE=1
NO_JAVA=0
NO_APT=0
ANDROID_SDK_EXISTS=0
[[ -d "$ANDROID_SDK_DIR" ]] && ANDROID_SDK_EXISTS=1
ANDROID_SDK_DIR=$HOME/android-sdk
ANDROID_LINUX_SDK_URL="https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip"
fullPackages=("add-ons;addon-google_apis-google-15"
"add-ons;addon-google_apis-google-16"
"add-ons;addon-google_apis-google-17"
"add-ons;addon-google_apis-google-18"
"add-ons;addon-google_apis-google-19"
"add-ons;addon-google_apis-google-21"
"add-ons;addon-google_apis-google-22"
"add-ons;addon-google_apis-google-23"
"add-ons;addon-google_apis-google-24"
"add-ons;addon-google_gdk-google-19"
"build-tools;19.1.0"
"build-tools;20.0.0"
"build-tools;21.1.2"
"build-tools;22.0.1"
"build-tools;23.0.1"
"build-tools;23.0.2"
"build-tools;23.0.3"
"build-tools;24.0.0"
"build-tools;24.0.1"
"build-tools;24.0.2"
"build-tools;24.0.3"
"build-tools;25.0.0"
"build-tools;25.0.1"
"build-tools;25.0.2"
"build-tools;25.0.3"
"build-tools;26.0.0"
"build-tools;28.0.3"
"cmake;3.6.3155560"
"extras;android;gapid;1"
"extras;android;gapid;3"
"extras;android;m2repository"
"extras;google;auto"
"extras;google;google_play_services"
"extras;google;instantapps"
"extras;google;m2repository"
"extras;google;market_apk_expansion"
"extras;google;market_licensing"
"extras;google;play_billing"
"extras;google;simulators"
"extras;google;webdriver"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha2"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha3"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha4"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha5"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha6"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha7"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha8"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-alpha9"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-beta1"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-beta2"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-beta3"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-beta4"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.0-beta5"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.1"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.2"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha2"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha3"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha4"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha5"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha6"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha7"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha8"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-alpha9"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-beta1"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-beta2"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-beta3ver;1.0.0-beta3"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-beta4"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.0-beta5"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.1"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.2"
"lldb;2.0"
"lldb;2.1"
"lldb;2.2"
"lldb;2.3"
"patcher;v4"
"platforms;android-26")
basicPackages=("add-ons;addon-google_apis-google-24"
"add-ons;addon-google_gdk-google-19"
"build-tools;26.0.0"
"build-tools;28.0.3"
"cmake;3.6.3155560"
"extras;android;gapid;3"
"extras;android;m2repository"
"extras;google;auto"
"extras;google;google_play_services"
"extras;google;instantapps"
"extras;google;m2repository"
"extras;google;market_apk_expansion"
"extras;google;market_licensing"
"extras;google;play_billing"
"extras;google;simulators"
"extras;google;webdriver"
"extras;m2repository;com;android;support;constraint;constraint-layout-solver;1.0.2"
"extras;m2repository;com;android;support;constraint;constraint-layout;1.0.2"
"lldb;2.3"
"patcher;v4"
"platforms;android-26"
"ndk-bundle"
"tools"
"platform-tools")
function printAndSleep() {
((counter++))
echo "
###### $1 ######
"
sleep 1
}
# Prints script version
function printVersion() {
echo "
Android SDK Setup for Linux
Version $VERSION
"
exit 0
}
# Updates machine APT
function updateApt() {
printAndSleep "Updating apt"
apt-get -y update
}
# Installs Java-8 (OpenJdk-8)
function installJava() {
JAVA_VER=$(java -version 2>&1 | sed -n ';s/.* version "\(.*\)\.\(.*\)\..*"/\1\2/p;')
if [ "$JAVA_VER" -ge 18 ]; then
printAndSleep "Java $JAVA_VER Found"
else
printAndSleep "Installing OpenJdk 8"
apt-get -y install openjdk-8-jdk
fi
}
#Installs unzip tool
function installUnzip() {
if ! type "unzip" &>/dev/null; then
printAndSleep "Installing Unzip tool"
apt-get -y install unzip
fi
}
function updateAndroidHomeVar() {
printAndSleep "Adding ANDROID_HOME to environmental variables"
echo "" >>~/.bashrc
echo "export ANDROID_HOME=\"$ANDROID_SDK_DIR\"" >>~/.bashrc
echo "" >>~/.bashrc
echo "export PATH=\"${PATH}:${ANDROID_SDK_DIR}/tools/:${ANDROID_SDK_DIR}/platform-tools/\"" >>~/.bashrc
}
#Accept Android SDK Licenses
function acceptAndroidSdkLicenses() {
# navigate into our directory
cd $ANDROID_SDK_DIR
printAndSleep "Accepting Android SDK licenses"
mkdir -p licenses/
echo -e "\n8933bad161af4178b1185d1a37fbf41ea5269c55" >"licenses/android-sdk-license"
echo -e "\n84831b9409646a918e30573bab4c9c91346d8abd" >"licenses/android-sdk-preview-license"
echo -e "\n152e8995e4332c0dc80bc63bf01fe3bbccb0804a
d975f751698a77b662f1254ddbeed3901e976f5a" >"licenses/intel-android-extra-license"
}
# Updates already installed Android SDK packages
function updateAndroidSdkPackages() {
printAndSleep "Checking for Android SdkManager updates..."
cd $ANDROID_SDK_DIR/tools/bin
./sdkmanager --update
}
# Updates installed Android SDK
function updateAndroidSdk() {
[ $ANDROID_SDK_EXISTS == 0 ] && echo "Android SDK not found, please install --basic or --full" && exit 1
printAndSleep "Updating Android SDK"
acceptAndroidSdkLicenses
updateAndroidSdkPackages
}
#Downloads Android Linux SDK tools to the $home directory
function downloadLinuxAndroidSdk() {
printAndSleep "Downloading linux android sdk tools"
wget -nc -O $HOME/sdk-tools-linux.zip $ANDROID_LINUX_SDK_URL
}
#1- Create sdk directory
#2- Unzip android linux sdk tools
function unzipAndroidLinuxSdk() {
mkdir -p $ANDROID_SDK_DIR
printAndSleep "unzipping linux android sdk tools"
unzip -o $HOME/sdk-tools-linux.zip -d $ANDROID_SDK_DIR
}
function installAndroidSdkPackages() {
printAndSleep "Installing Android SDK Packages"
packages=("$@")
cd $ANDROID_SDK_DIR/tools/bin
for package in "${packages[@]}"; do
printAndSleep "Installing $package"
./sdkmanager "$package"
done
}
function addMissingRepositoriesFile() {
[ ! -f $HOME/.android/repositories.cfg ] && echo "### User Sources for Android SDK Manager" >>$HOME/.android/repositories.cfg && echo "count=0" >>$HOME/.android/repositories.cfg
}
function installAndroidSdk() {
installUnzip
if [ $ANDROID_SDK_EXISTS == 0 ]; then
downloadLinuxAndroidSdk
unzipAndroidLinuxSdk
updateAndroidHomeVar
fi
acceptAndroidSdkLicenses
addMissingRepositoriesFile
packages=("$@")
installAndroidSdkPackages "${packages[@]}"
du -hs $ANDROID_SDK_DIR
}
# Install basic most common android sdk packages
function installBasicAndroidSdk() {
printAndSleep "Installing Basic Android SDK"
installAndroidSdk "${basicPackages[@]}"
}
# Install basic full android sdk packages
function installFullAndroidSdk() {
printAndSleep "Installing Full Android SDK"
installAndroidSdk "${fullPackages[@]}"
}
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-n | --none)
SDK_INSTALLATION=-1
;;
-b | --basic)
SDK_INSTALLATION=0
;;
-f | --full)
SDK_INSTALLATION=1
;;
-u | --update)
SDK_UPDATE=1
;;
-j | --no-java)
NO_JAVA=1
;;
-a | --no-apt)
NO_APT=1
;;
-v | --version)
printVersion
;;
*) ;; # unknown option
esac
shift # past argument or value
done
if [ $DEBUG == 1 ]; then
SDK_INSTALLATION=1
SDK_UPDATE=1
NO_JAVA=0
NO_APT=0
fi
echo SDK_INSTALLATION = "${SDK_INSTALLATION}"
echo NO_JAVA = "${NO_JAVA}"
echo NO_APT = "${NO_APT}"
echo ANDROID_SDK_EXISTS = "${ANDROID_SDK_EXISTS}"
echo SDK_UPDATE = "${SDK_UPDATE}"
[ $NO_APT == 0 ] && updateApt
[ $NO_JAVA == 0 ] && installJava
if [ $ANDROID_SDK_EXISTS == 1 ] && [ $SDK_UPDATE == 1 ] && [ $SDK_INSTALLATION -gt -1 ]; then
updateAndroidSdk
elif [ $SDK_UPDATE == 1 ] && [ $SDK_INSTALLATION == -1 ]; then
updateAndroidSdk
else
if [ $SDK_INSTALLATION == -1 ]; then
printAndSleep "Skipping Android SDK Installation"
elif [ $SDK_INSTALLATION == 0 ]; then
installBasicAndroidSdk
updateAndroidSdk
elif [ $SDK_INSTALLATION == 1 ]; then
installFullAndroidSdk
updateAndroidSdk
fi
fi
|
#!/bin/bash
. ./common.sh
kubectl patch configmap config-logging -n karpenter --patch '{"data":{"loglevel.controller":"debug"}}'
kubectl patch configmap config-logging -n karpenter --patch '{"data":{"loglevel.webhook":"debug"}}'
|
<gh_stars>10-100
'use strict';
/**
* A module for the router of the desktop application
*/
define("router", [
'angular',
'angularRoute',
'angularResource',
'angularTouch',
'app/home/view',
'app/events/eventsView',
'app/venues/venuesView',
'app/eventDetail/eventDetailView',
'app/venueDetail/venueDetailView',
'app/booking/view',
'app/monitor/monitor'
],function (angular) {
return angular.module('ticketMonster', ['ngRoute',
'ngResource',
'ngTouch',
'ticketMonster.api',
'ticketMonster.homeView',
'ticketMonster.eventsView',
'ticketMonster.venuesView',
'ticketMonster.eventDetailView',
'ticketMonster.venueDetailView',
'ticketMonster.bookingView',
'ticketMonster.monitorView'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.otherwise({redirectTo: '/'});
}]);
});
|
import * as NS from '../../namespace';
import { TwoFAType } from 'shared/types/models';
export function setRetriesAmount(amount: number): NS.ISetRetriesAmount {
return { type: 'PROTECTOR:SET_RETRIES_AMOUNT', payload: amount };
}
export function setProvider(payload: TwoFAType): NS.ISetProvider {
return { type: 'PROTECTOR:SET_PROVIDER', payload };
}
|
#!/bin/bash
stage=0
train=true # set to false to disable the training-related scripts
# note: you probably only want to set --train false if you
# are using at least --stage 1.
decode=true # set to false to disable the decoding-related scripts.
. ./cmd.sh ## You'll want to change cmd.sh to something that will work on your system.
## This relates to the queue.
. utils/parse_options.sh # e.g. this parses the --stage option if supplied.
# This is a shell script, but it's recommended that you run the commands one by
# one by copying and pasting into the shell.
#wsj0=/ais/gobi2/speech/WSJ/csr_?_senn_d?
#wsj1=/ais/gobi2/speech/WSJ/csr_senn_d?
#wsj0=/mnt/matylda2/data/WSJ0
#wsj1=/mnt/matylda2/data/WSJ1
#wsj0=/data/corpora0/LDC93S6B
#wsj1=/data/corpora0/LDC94S13B
wsj0=/export/corpora5/LDC/LDC93S6B
wsj1=/export/corpora5/LDC/LDC94S13B
if [ $stage -le 0 ]; then
# data preparation.
local/wsj_data_prep.sh $wsj0/??-{?,??}.? $wsj1/??-{?,??}.? || exit 1;
# Sometimes, we have seen WSJ distributions that do not have subdirectories
# like '11-13.1', but instead have 'doc', 'si_et_05', etc. directly under the
# wsj0 or wsj1 directories. In such cases, try the following:
#
# corpus=/exports/work/inf_hcrc_cstr_general/corpora/wsj
# local/cstr_wsj_data_prep.sh $corpus
# rm data/local/dict/lexiconp.txt
# $corpus must contain a 'wsj0' and a 'wsj1' subdirectory for this to work.
#
# "nosp" refers to the dictionary before silence probabilities and pronunciation
# probabilities are added.
local/wsj_prepare_dict.sh --dict-suffix "_nosp" || exit 1;
utils/prepare_lang.sh data/local/dict_nosp \
"<SPOKEN_NOISE>" data/local/lang_tmp_nosp data/lang_nosp || exit 1;
local/wsj_format_data.sh --lang-suffix "_nosp" || exit 1;
# We suggest to run the next three commands in the background,
# as they are not a precondition for the system building and
# most of the tests: these commands build a dictionary
# containing many of the OOVs in the WSJ LM training data,
# and an LM trained directly on that data (i.e. not just
# copying the arpa files from the disks from LDC).
# Caution: the commands below will only work if $decode_cmd
# is setup to use qsub. Else, just remove the --cmd option.
# NOTE: If you have a setup corresponding to the older cstr_wsj_data_prep.sh style,
# use local/cstr_wsj_extend_dict.sh --dict-suffix "_nosp" $corpus/wsj1/doc/ instead.
(
local/wsj_extend_dict.sh --dict-suffix "_nosp" $wsj1/13-32.1 && \
utils/prepare_lang.sh data/local/dict_nosp_larger \
"<SPOKEN_NOISE>" data/local/lang_tmp_nosp_larger data/lang_nosp_bd && \
local/wsj_train_lms.sh --dict-suffix "_nosp" &&
local/wsj_format_local_lms.sh --lang-suffix "_nosp" # &&
) &
# Now make MFCC features.
# mfccdir should be some place with a largish disk where you
# want to store MFCC features.
for x in test_eval92 test_eval93 test_dev93 train_si284; do
steps/make_mfcc.sh --cmd "$train_cmd" --nj 20 data/$x || exit 1;
steps/compute_cmvn_stats.sh data/$x || exit 1;
done
utils/subset_data_dir.sh --first data/train_si284 7138 data/train_si84 || exit 1
# Now make subset with the shortest 2k utterances from si-84.
utils/subset_data_dir.sh --shortest data/train_si84 2000 data/train_si84_2kshort || exit 1;
# Now make subset with half of the data from si-84.
utils/subset_data_dir.sh data/train_si84 3500 data/train_si84_half || exit 1;
fi
if [ $stage -le 1 ]; then
# monophone
# Note: the --boost-silence option should probably be omitted by default
# for normal setups. It doesn't always help. [it's to discourage non-silence
# models from modeling silence.]
if $train; then
steps/train_mono.sh --boost-silence 1.25 --nj 10 --cmd "$train_cmd" \
data/train_si84_2kshort data/lang_nosp exp/mono0a || exit 1;
fi
if $decode; then
utils/mkgraph.sh data/lang_nosp_test_tgpr exp/mono0a exp/mono0a/graph_nosp_tgpr && \
steps/decode.sh --nj 10 --cmd "$decode_cmd" exp/mono0a/graph_nosp_tgpr \
data/test_dev93 exp/mono0a/decode_nosp_tgpr_dev93 && \
steps/decode.sh --nj 8 --cmd "$decode_cmd" exp/mono0a/graph_nosp_tgpr \
data/test_eval92 exp/mono0a/decode_nosp_tgpr_eval92
fi
fi
if [ $stage -le 2 ]; then
# tri1
if $train; then
steps/align_si.sh --boost-silence 1.25 --nj 10 --cmd "$train_cmd" \
data/train_si84_half data/lang_nosp exp/mono0a exp/mono0a_ali || exit 1;
steps/train_deltas.sh --boost-silence 1.25 --cmd "$train_cmd" 2000 10000 \
data/train_si84_half data/lang_nosp exp/mono0a_ali exp/tri1 || exit 1;
fi
if $decode; then
utils/mkgraph.sh data/lang_nosp_test_tgpr \
exp/tri1 exp/tri1/graph_nosp_tgpr || exit 1;
for data in dev93 eval92; do
nspk=$(wc -l <data/test_${data}/spk2utt)
steps/decode.sh --nj $nspk --cmd "$decode_cmd" exp/tri1/graph_nosp_tgpr \
data/test_${data} exp/tri1/decode_nosp_tgpr_${data} || exit 1;
# test various modes of LM rescoring (4 is the default one).
# This is just confirming they're equivalent.
for mode in 1 2 3 4; do
steps/lmrescore.sh --mode $mode --cmd "$decode_cmd" \
data/lang_nosp_test_{tgpr,tg} data/test_${data} \
exp/tri1/decode_nosp_tgpr_${data} \
exp/tri1/decode_nosp_tgpr_${data}_tg$mode || exit 1;
done
# later on we'll demonstrate const-arpa LM rescoring, which is now
# the recommended method.
done
## the following command demonstrates how to get lattices that are
## "word-aligned" (arcs coincide with words, with boundaries in the right
## place).
#sil_label=`grep '!SIL' data/lang_nosp_test_tgpr/words.txt | awk '{print $2}'`
#steps/word_align_lattices.sh --cmd "$train_cmd" --silence-label $sil_label \
# data/lang_nosp_test_tgpr exp/tri1/decode_nosp_tgpr_dev93 \
# exp/tri1/decode_nosp_tgpr_dev93_aligned || exit 1;
fi
fi
if [ $stage -le 3 ]; then
# tri2b. there is no special meaning in the "b"-- it's historical.
if $train; then
steps/align_si.sh --nj 10 --cmd "$train_cmd" \
data/train_si84 data/lang_nosp exp/tri1 exp/tri1_ali_si84 || exit 1;
steps/train_lda_mllt.sh --cmd "$train_cmd" \
--splice-opts "--left-context=3 --right-context=3" 2500 15000 \
data/train_si84 data/lang_nosp exp/tri1_ali_si84 exp/tri2b || exit 1;
fi
if $decode; then
utils/mkgraph.sh data/lang_nosp_test_tgpr \
exp/tri2b exp/tri2b/graph_nosp_tgpr || exit 1;
for data in dev93 eval92; do
nspk=$(wc -l <data/test_${data}/spk2utt)
steps/decode.sh --nj ${nspk} --cmd "$decode_cmd" exp/tri2b/graph_nosp_tgpr \
data/test_${data} exp/tri2b/decode_nosp_tgpr_${data} || exit 1;
# compare lattice rescoring with biglm decoding, going from tgpr to tg.
steps/decode_biglm.sh --nj ${nspk} --cmd "$decode_cmd" \
exp/tri2b/graph_nosp_tgpr data/lang_nosp_test_{tgpr,tg}/G.fst \
data/test_${data} exp/tri2b/decode_nosp_tgpr_${data}_tg_biglm
# baseline via LM rescoring of lattices.
steps/lmrescore.sh --cmd "$decode_cmd" \
data/lang_nosp_test_tgpr/ data/lang_nosp_test_tg/ \
data/test_${data} exp/tri2b/decode_nosp_tgpr_${data} \
exp/tri2b/decode_nosp_tgpr_${data}_tg || exit 1;
# Demonstrating Minimum Bayes Risk decoding (like Confusion Network decoding):
mkdir exp/tri2b/decode_nosp_tgpr_${data}_tg_mbr
cp exp/tri2b/decode_nosp_tgpr_${data}_tg/lat.*.gz \
exp/tri2b/decode_nosp_tgpr_${data}_tg_mbr;
local/score_mbr.sh --cmd "$decode_cmd" \
data/test_${data}/ data/lang_nosp_test_tgpr/ \
exp/tri2b/decode_nosp_tgpr_${data}_tg_mbr
done
fi
# At this point, you could run the example scripts that show how VTLN works.
# We haven't included this in the default recipes.
# local/run_vtln.sh --lang-suffix "_nosp"
# local/run_vtln2.sh --lang-suffix "_nosp"
fi
# local/run_delas.sh trains a delta+delta-delta system. It's not really recommended or
# necessary, but it does contain a demonstration of the decode_fromlats.sh
# script which isn't used elsewhere.
# local/run_deltas.sh
if [ $stage -le 4 ]; then
# From 2b system, train 3b which is LDA + MLLT + SAT.
# Align tri2b system with all the si284 data.
if $train; then
steps/align_si.sh --nj 10 --cmd "$train_cmd" \
data/train_si284 data/lang_nosp exp/tri2b exp/tri2b_ali_si284 || exit 1;
steps/train_sat.sh --cmd "$train_cmd" 4200 40000 \
data/train_si284 data/lang_nosp exp/tri2b_ali_si284 exp/tri3b || exit 1;
fi
if $decode; then
utils/mkgraph.sh data/lang_nosp_test_tgpr \
exp/tri3b exp/tri3b/graph_nosp_tgpr || exit 1;
# the larger dictionary ("big-dict"/bd) + locally produced LM.
utils/mkgraph.sh data/lang_nosp_test_bd_tgpr \
exp/tri3b exp/tri3b/graph_nosp_bd_tgpr || exit 1;
# At this point you could run the command below; this gets
# results that demonstrate the basis-fMLLR adaptation (adaptation
# on small amounts of adaptation data).
# local/run_basis_fmllr.sh --lang-suffix "_nosp"
for data in dev93 eval92; do
nspk=$(wc -l <data/test_${data}/spk2utt)
steps/decode_fmllr.sh --nj ${nspk} --cmd "$decode_cmd" \
exp/tri3b/graph_nosp_tgpr data/test_${data} \
exp/tri3b/decode_nosp_tgpr_${data} || exit 1;
steps/lmrescore.sh --cmd "$decode_cmd" \
data/lang_nosp_test_tgpr data/lang_nosp_test_tg \
data/test_${data} exp/tri3b/decode_nosp_{tgpr,tg}_${data} || exit 1
# decode with big dictionary.
steps/decode_fmllr.sh --cmd "$decode_cmd" --nj 8 \
exp/tri3b/graph_nosp_bd_tgpr data/test_${data} \
exp/tri3b/decode_nosp_bd_tgpr_${data} || exit 1;
# Example of rescoring with ConstArpaLm.
steps/lmrescore_const_arpa.sh \
--cmd "$decode_cmd" data/lang_nosp_test_bd_{tgpr,fgconst} \
data/test_${data} exp/tri3b/decode_nosp_bd_tgpr_${data}{,_fg} || exit 1;
done
fi
fi
if [ $stage -le 5 ]; then
# Estimate pronunciation and silence probabilities.
# Silprob for normal lexicon.
steps/get_prons.sh --cmd "$train_cmd" \
data/train_si284 data/lang_nosp exp/tri3b || exit 1;
utils/dict_dir_add_pronprobs.sh --max-normalize true \
data/local/dict_nosp \
exp/tri3b/pron_counts_nowb.txt exp/tri3b/sil_counts_nowb.txt \
exp/tri3b/pron_bigram_counts_nowb.txt data/local/dict || exit 1
utils/prepare_lang.sh data/local/dict \
"<SPOKEN_NOISE>" data/local/lang_tmp data/lang || exit 1;
for lm_suffix in bg bg_5k tg tg_5k tgpr tgpr_5k; do
mkdir -p data/lang_test_${lm_suffix}
cp -r data/lang/* data/lang_test_${lm_suffix}/ || exit 1;
rm -rf data/lang_test_${lm_suffix}/tmp
cp data/lang_nosp_test_${lm_suffix}/G.* data/lang_test_${lm_suffix}/
done
# Silprob for larger ("bd") lexicon.
utils/dict_dir_add_pronprobs.sh --max-normalize true \
data/local/dict_nosp_larger \
exp/tri3b/pron_counts_nowb.txt exp/tri3b/sil_counts_nowb.txt \
exp/tri3b/pron_bigram_counts_nowb.txt data/local/dict_larger || exit 1
utils/prepare_lang.sh data/local/dict_larger \
"<SPOKEN_NOISE>" data/local/lang_tmp_larger data/lang_bd || exit 1;
for lm_suffix in tgpr tgconst tg fgpr fgconst fg; do
mkdir -p data/lang_test_bd_${lm_suffix}
cp -r data/lang_bd/* data/lang_test_bd_${lm_suffix}/ || exit 1;
rm -rf data/lang_test_bd_${lm_suffix}/tmp
cp data/lang_nosp_test_bd_${lm_suffix}/G.* data/lang_test_bd_${lm_suffix}/
done
fi
if [ $stage -le 6 ]; then
# From 3b system, now using data/lang as the lang directory (we have now added
# pronunciation and silence probabilities), train another SAT system (tri4b).
if $train; then
steps/train_sat.sh --cmd "$train_cmd" 4200 40000 \
data/train_si284 data/lang exp/tri3b exp/tri4b || exit 1;
fi
if $decode; then
utils/mkgraph.sh data/lang_test_tgpr \
exp/tri4b exp/tri4b/graph_tgpr || exit 1;
utils/mkgraph.sh data/lang_test_bd_tgpr \
exp/tri4b exp/tri4b/graph_bd_tgpr || exit 1;
for data in dev93 eval92; do
nspk=$(wc -l <data/test_${data}/spk2utt)
steps/decode_fmllr.sh --nj ${nspk} --cmd "$decode_cmd" \
exp/tri4b/graph_tgpr data/test_${data} \
exp/tri4b/decode_tgpr_${data} || exit 1;
steps/lmrescore.sh --cmd "$decode_cmd" \
data/lang_test_tgpr data/lang_test_tg \
data/test_${data} exp/tri4b/decode_{tgpr,tg}_${data} || exit 1
steps/decode_fmllr.sh --nj ${nspk} --cmd "$decode_cmd" \
exp/tri4b/graph_bd_tgpr data/test_${data} \
exp/tri4b/decode_bd_tgpr_${data} || exit 1;
steps/lmrescore_const_arpa.sh \
--cmd "$decode_cmd" data/lang_test_bd_{tgpr,fgconst} \
data/test_${data} exp/tri4b/decode_bd_tgpr_${data}{,_fg} || exit 1;
done
fi
fi
exit 0;
### Caution: the parts of the script below this statement are not run by default.
###
# Train and test MMI, and boosted MMI, on tri4b (LDA+MLLT+SAT on
# all the data). Use 30 jobs.
steps/align_fmllr.sh --nj 30 --cmd "$train_cmd" \
data/train_si284 data/lang exp/tri4b exp/tri4b_ali_si284 || exit 1;
local/run_mmi_tri4b.sh
# These demonstrate how to build a sytem usable for online-decoding with the nnet2 setup.
# (see local/run_nnet2.sh for other, non-online nnet2 setups).
local/online/run_nnet2.sh
local/online/run_nnet2_baseline.sh
local/online/run_nnet2_discriminative.sh
# Demonstration of RNNLM rescoring on TDNN models. We comment this out by
# default.
# local/run_rnnlms.sh
#local/run_nnet2.sh
# You probably want to run the sgmm2 recipe as it's generally a bit better:
local/run_sgmm2.sh
# We demonstrate MAP adaptation of GMMs to gender-dependent systems here. This also serves
# as a generic way to demonstrate MAP adaptation to different domains.
# local/run_gender_dep.sh
# You probably want to run the hybrid recipe as it is complementary:
local/nnet/run_dnn.sh
# The following demonstrate how to re-segment long audios.
# local/run_segmentation_long_utts.sh
# The next two commands show how to train a bottleneck network based on the nnet2 setup,
# and build an SGMM system on top of it.
#local/run_bnf.sh
#local/run_bnf_sgmm.sh
# Getting results [see RESULTS file]
# for x in exp/*/decode*; do [ -d $x ] && grep WER $x/wer_* | utils/best_wer.sh; done
# KWS setup. We leave it commented out by default
# $duration is the length of the search collection, in seconds
#duration=`feat-to-len scp:data/test_eval92/feats.scp ark,t:- | awk '{x+=$2} END{print x/100;}'`
#local/generate_example_kws.sh data/test_eval92/ data/kws/
#local/kws_data_prep.sh data/lang_test_bd_tgpr/ data/test_eval92/ data/kws/
#
#steps/make_index.sh --cmd "$decode_cmd" --acwt 0.1 \
# data/kws/ data/lang_test_bd_tgpr/ \
# exp/tri4b/decode_bd_tgpr_eval92/ \
# exp/tri4b/decode_bd_tgpr_eval92/kws
#
#steps/search_index.sh --cmd "$decode_cmd" \
# data/kws \
# exp/tri4b/decode_bd_tgpr_eval92/kws
#
# If you want to provide the start time for each utterance, you can use the --segments
# option. In WSJ each file is an utterance, so we don't have to set the start time.
#cat exp/tri4b/decode_bd_tgpr_eval92/kws/result.* | \
# utils/write_kwslist.pl --flen=0.01 --duration=$duration \
# --normalize=true --map-utter=data/kws/utter_map \
# - exp/tri4b/decode_bd_tgpr_eval92/kws/kwslist.xml
# # A couple of nnet3 recipes:
# local/nnet3/run_tdnn_baseline.sh # designed for exact comparison with nnet2 recipe
# local/nnet3/run_tdnn.sh # better absolute results
# local/nnet3/run_lstm.sh # lstm recipe
# bidirectional lstm recipe
# local/nnet3/run_lstm.sh --affix bidirectional \
# --lstm-delay " [-1,1] [-2,2] [-3,3] " \
# --label-delay 0 \
# --cell-dim 640 \
# --recurrent-projection-dim 128 \
# --non-recurrent-projection-dim 128 \
# --chunk-left-context 40 \
# --chunk-right-context 40
|
#!/bin/sh
set -e
cd $1
git init
git config user.email "CI@example.com"
git config user.name "CI"
echo test0 > file0
git add .
git commit -am file0
echo test1 > file1
git add .
git commit -am file1
|
import { SET_PROJECTS } from '../actions/types';
const initialState = {};
export default function (state = initialState, action: any) {
const { type, payload } = action;
switch (type) {
case SET_PROJECTS:
return { projects: payload };
default:
return state;
}
}
|
#!/usr/bin/env bash
echo "==> Consul (server)"
if [ ${enterprise} == 0 ]
then
echo "--> Fetching OSS binaries"
install_from_url "consul" "${consul_url}"
else
echo "--> Fetching enterprise binaries"
install_from_url "consul" "${consul_ent_url}"
fi
echo "--> Writing configuration"
sudo mkdir -p /mnt/consul
sudo mkdir -p /etc/consul.d
sudo tee /etc/consul.d/config.json > /dev/null <<EOF
{
"datacenter": "${region}",
"primary_datacenter": "${primary_datacenter}",
"bootstrap_expect": ${consul_servers},
"advertise_addr": "$(private_ip)",
"advertise_addr_wan": "$(public_ip)",
"bind_addr": "0.0.0.0",
"client_addr": "0.0.0.0",
"data_dir": "/mnt/consul",
"encrypt": "${consul_gossip_key}",
"leave_on_terminate": true,
"node_name": "${node_name}",
"retry_join": ["provider=aws tag_key=${consul_join_tag_key} tag_value=${consul_join_tag_value}"],
"server": true,
"ports": {
"http": 8500,
"https": 8501,
"grpc": 8502
},
"connect":{
"enabled": true
},
"ui": true,
"enable_central_service_config":true,
"autopilot": {
"cleanup_dead_servers": true,
"last_contact_threshold": "200ms",
"max_trailing_logs": 250,
"server_stabilization_time": "10s",
"disable_upgrade_migration": false
},
"telemetry": {
"disable_hostname": true,
"prometheus_retention_time": "30s"
}
}
EOF
echo "--> Writing profile"
sudo tee /etc/profile.d/consul.sh > /dev/null <<"EOF"
alias conslu="consul"
alias ocnsul="consul"
EOF
source /etc/profile.d/consul.sh
echo "--> Generating systemd configuration"
sudo tee /etc/systemd/system/consul.service > /dev/null <<"EOF"
[Unit]
Description=Consul
Documentation=https://www.consul.io/docs/
Requires=network-online.target
After=network-online.target
[Service]
Restart=on-failure
ExecStart=/usr/local/bin/consul agent -config-dir="/etc/consul.d"
ExecReload=/bin/kill -HUP $MAINPID
KillSignal=SIGINT
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl enable consul
sudo systemctl restart consul
echo "--> Installing dnsmasq"
ssh-apt install dnsmasq
sudo tee /etc/dnsmasq.d/10-consul > /dev/null <<"EOF"
server=/consul/127.0.0.1#8600
no-poll
server=8.8.8.8
server=8.8.4.4
cache-size=0
EOF
sudo systemctl enable dnsmasq
sudo systemctl restart dnsmasq
echo "--> Waiting for all Consul servers"
while [ "$(consul members 2>&1 | grep "server" | grep "alive" | wc -l)" -lt "${consul_servers}" ]; do
sleep 3
done
echo "--> Waiting for Consul leader"
while [ -z "$(curl -s http://127.0.0.1:8500/v1/status/leader)" ]; do
sleep 3
done
if [ ${enterprise} == 1 ]
then
echo "--> apply Consul License"
sudo consul license put "${consullicense}" > /tmp/consullicense.out
fi
echo "--> Denying anonymous access to vault/ and tmp/"
curl -so /dev/null -X PUT http://127.0.0.1:8500/v1/acl/update \
-H "X-Consul-Token: ${consul_master_token}" \
-d @- <<BODY
{
"ID": "anonymous",
"Rules": "key \"vault\" { policy = \"deny\" }\n\nkey \"tmp\" { policy = \"deny\" }"
}
BODY
echo "--> writting default gateway configs for Mesh Gateways"
sudo tee /tmp/proxy-defaults.json > /dev/null <<"EOF"
Kind = "proxy-defaults"
Name = "global"
MeshGateway {
Mode = "local"
}
EOF
consul config write /tmp/proxy-defaults.json
echo "==> Consul is done!"
|
#!/bin/bash
INLINING="-light-inline"
#INLINING="-inline-all -unroll"
# ACE bitslice
./usubac $INLINING -gen-bench -bits-per-reg 32 -B -no-sched -o nist/ace/usuba/bench/ace_ua_bitslice.c -arch std -no-share nist/ace/usuba/ua/ace_bitslice.ua
# ACE vslice
./usubac $INLINING -gen-bench -V -no-sched -o nist/ace/usuba/bench/ace_ua_vslice.c -arch std -no-share nist/ace/usuba/ua/ace.ua
# Ascon bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -B -no-sched -o nist/ascon/usuba/bench/ascon_ua_bitslice.c -arch std -no-share nist/ascon/usuba/ua/ascon.ua
# Ascon vslice
./usubac -gen-bench $INLINING -V -no-sched -o nist/ascon/usuba/bench/ascon_ua_vslice.c -arch std -no-share nist/ascon/usuba/ua/ascon.ua
# GIFT bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -B -no-sched -o nist/gift/usuba/bench/gift_ua_bitslice.c -arch std -no-share nist/gift/usuba/ua/gift_bitslice.ua
# GIFT bitslice
./usubac -gen-bench $INLINING -V -no-sched -o nist/gift/usuba/bench/gift_ua_vslice.c -arch std -no-share nist/gift/usuba/ua/gift.ua
# Gimli bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -no-sched -B -o nist/gimli/usuba/bench/gimli_ua_bitslice.c nist/gimli/usuba/ua/gimli_bitslice.ua
# Gimli vslice
./usubac -gen-bench $INLINING -no-sched -V -o nist/gimli/usuba/bench/gimli_ua_vslice.c nist/gimli/usuba/ua/gimli.ua
# Photon bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -B -no-sched -o nist/photon/usuba/bench/photon_ua_bitslice.c -arch std -no-share nist/photon/usuba/ua/photon_bitslice.ua
# Photon vslice (uses tables)
./usubac -gen-bench $INLINING -V -keep-tables -no-sched -o nist/photon/usuba/bench/photon_ua_vslice.c -arch std -no-share nist/photon/usuba/ua/photon_vslice.ua
# Pyjamask bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -no-sched -B -o nist/pyjamask/usuba/bench/pyjamask_ua_bitslice.c -arch std -no-share nist/pyjamask/usuba/ua/pyjamask_bitslice.ua
# Pyjamask vslice
./usubac -gen-bench $INLINING -no-sched -V -o nist/pyjamask/usuba/bench/pyjamask_ua_vslice.c -arch std -no-share nist/pyjamask/usuba/ua/pyjamask_vslice.ua
# Skinny bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -B -no-sched -o nist/skinny/usuba/bench/skinny_ua_bitslice.c -arch std -no-share nist/skinny/usuba/ua/skinny_bitslice.ua
# Skinny vslice (uses tables)
./usubac -gen-bench $INLINING -keep-tables -V -no-sched -o nist/skinny/usuba/bench/skinny_ua_vslice.c -arch std -no-share nist/skinny/usuba/ua/skinny_vslice.ua
# Clyde (spook) bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -no-sched -B -o nist/clyde/usuba/bench/clyde_ua_bitslice.c nist/clyde/usuba/ua/clyde_bitslice.ua
# Clyde (spook) vslice
./usubac -gen-bench $INLINING -no-sched -V -o nist/clyde/usuba/bench/clyde_ua_vslice.c nist/clyde/usuba/ua/clyde.ua
# Spongent bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -check-tbl -B -no-sched -o nist/spongent/usuba/bench/spongent_ua_bitslice.c -arch std -no-share nist/spongent/usuba/ua/spongent.ua
# Subterranean bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -no-sched -B -o nist/subterranean/usuba/bench/subterranean_ua_bitslice.c nist/subterranean/usuba/ua/subterranean.ua
# Xoodoo bitslice
./usubac -gen-bench $INLINING -bits-per-reg 32 -no-sched -B -o nist/xoodoo/usuba/bench/xoodoo_ua_bitslice.c nist/xoodoo/usuba/ua/xoodoo.ua
# Xoodoo vslice
./usubac -gen-bench $INLINING -no-sched -V -o nist/xoodoo/usuba/bench/xoodoo_ua_vslice.c nist/xoodoo/usuba/ua/xoodoo.ua
|
<gh_stars>1-10
package com.flockinger.poppynotes.gateway.util;
import java.util.Base64;
import org.apache.commons.lang.ArrayUtils;
public class EncryptionUtils {
public static String encodeBase64(byte[] messageBytes) {
return Base64.getEncoder().encodeToString(messageBytes);
}
public static byte[] decodeBase64(String message){
return Base64.getDecoder().decode(message);
}
public static byte[] concatenateByteArrays(byte[] first, byte[] second){
byte[] keyBytes = ArrayUtils.subarray(first, 0, first.length - second.length);
return ArrayUtils.addAll(keyBytes, second);
}
}
|
#!/bin/bash
# we can update table delete route and add new ones
aws ec2 delete-route --route-table-id rtb-11111111 --destination-cidr-block 10.0.0.0/16
aws ec2 create-route --route-table-id rtb-11111111 --destination-cidr-block 10.0.0.0/16 --vpc-peering-connection-id pcx-22222222
|
package com.alzhahir.cscapp;
import java.util.ArrayList;
public class FlightManager {
private String flightID;
private String flightDate;
private String flightTime;
private String flightDestination;
private String flightPrice;
private double totalPrice;
private String[] chosenFlight;
private String[] column = {"Number","Flight Number", "Flight Date", "Flight Time", "Destination", "Price"};
FlightManager(){
}
FlightManager(int flightIndex){
this.chosenFlight = new String[6];
this.chosenFlight = getFlightInfo(flightIndex);
System.out.println("Setting Flight...");
setFlightInfo(this.chosenFlight);
this.totalPrice = calculateTotalPrice();
System.out.println("Done Setting Flight.");
}
FlightManager(String flightID, String flightDate, String flightTime, String flightDestination, String flightPrice){
this.flightID = flightID;
this.flightDate = flightDate;
this.flightTime = flightTime;
this.flightDestination = flightDestination;
this.flightPrice = flightPrice;
}
String[][] getAllFlightInfo(){
IOManager io = new IOManager("/flights.txt", "/bookings.txt");
ArrayList<ArrayList> flightImportData = io.inputData();
ArrayList flightID = flightImportData.get(0);
ArrayList flightDate = flightImportData.get(1);
ArrayList flightTime = flightImportData.get(2);
ArrayList flightDestination = flightImportData.get(3);
ArrayList flightPrice = flightImportData.get(4);
String[][] flightData = new String[flightID.size()][column.length];
for(int i = 0; i < flightID.size(); i++){
flightData[i][0] = String.valueOf(i+1);
flightData[i][1] = String.valueOf(flightID.get(i));
flightData[i][2] = String.valueOf(flightDate.get(i));
flightData[i][3] = String.valueOf(flightTime.get(i));
flightData[i][4] = String.valueOf(flightDestination.get(i));
flightData[i][5] = String.valueOf(flightPrice.get(i));
}
return flightData;
}
String[] getFlightInfo(int flightIndex){
String[][] allFlights = getAllFlightInfo();
String[] chosenFlight = new String[column.length];
for(int i = 0; i < column.length; i++){
chosenFlight[i] = allFlights[flightIndex][i].toString();
}
return chosenFlight;
}
String[] getColumnInfo(){
return column;
}
void setFlightInfo(String[] chosenFlight){
this.flightID = chosenFlight[1];
this.flightDate = chosenFlight[2];
this.flightTime = chosenFlight[3];
this.flightDestination = chosenFlight[4];
this.flightPrice = chosenFlight[5];
System.out.println(this.flightID);
System.out.println(this.flightDate);
System.out.println(this.flightTime);
System.out.println(this.flightDestination);
System.out.println(this.flightPrice);
}
String getFlightID(){
return flightID;
}
String getFlightDate(){
return flightDate;
}
String getFlightTime(){
return flightTime;
}
String getFlightDestination(){
return flightDestination;
}
double getFlightPrice(){
return Double.parseDouble(this.flightPrice);
}
double getTotalPrice(){
return totalPrice;
}
double calculateTotalPrice(){
System.out.println(this.flightPrice);
double flightPriceParsed = Double.parseDouble(this.flightPrice);
double tax = 0.06;
return flightPriceParsed + flightPriceParsed * tax;
}
}
|
function fetchRandomSymbol() {
const apiEndpoint = 'https://api.iextrading.com/1.0/ref-data/symbols';
const symbolRequest = fetch(apiEndpoint)
.then(response => response.json())
.then((symbols) => {
return symbols[Math.floor(Math.random() * symbols.length)].symbol;
});
return symbolRequest;
}
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
public class Crane {
public static void main(String[] args) {
}
int[][] board;
List<Integer> cranePointer;
Stack<Integer> dollStack;
int count;
Crane(int[][] board) {
this.board = board;
cranePointer = new ArrayList<>();
dollStack = new Stack<>();
count = 0;
}
private void generateCranePoint() {
int[][] board = this.board;
for (int i = 0; i < board[0].length; i++) {
for (int j = 0; j < board.length; i++) {
int temp = board[j][i];
if(temp != 0) {
cranePointer.add(j);
break;
}
}
}
}
private void dollCatch(int index) {
int position = cranePointer.get(index);
cranePointer.set(index,position+1);
int target = board[position][index];
if(dollStack.isEmpty() || dollStack.peek() != target) {
dollStack.add(target);
return;
}
dollStack.pop();
count += 2;
board[position][index] = 0;
}
}
|
<reponame>SpoonX/aurelia-view
export * from './aurelia-view-manager';
|
<filename>spec/services/carry_over_application_spec.rb
require 'rails_helper'
require 'services/duplicate_application_shared_examples'
RSpec.describe CarryOverApplication do
def original_application_form
@original_application_form ||= Timecop.travel(-1.day) do
application_form = create(
:completed_application_form,
:with_gcses,
application_choices_count: 1,
work_experiences_count: 1,
volunteering_experiences_count: 1,
full_work_history: true,
)
create(:reference, feedback_status: :feedback_provided, application_form: application_form)
create(:reference, feedback_status: :not_requested_yet, application_form: application_form)
create(:reference, feedback_status: :feedback_refused, application_form: application_form)
application_form
end
end
context 'when original application is from an earlier recruitment cycle' do
around do |example|
Timecop.freeze(Time.zone.local(2020, 10, 15, 12, 0, 0)) do
example.run
end
end
before do
Timecop.travel(-1.day) { original_application_form.update(recruitment_cycle_year: 2020) }
end
it_behaves_like 'duplicates application form', 'apply_1', 2021
end
context 'when original application is from the current recruitment cycle but that cycle has now closed' do
around do |example|
Timecop.freeze(Time.zone.local(2020, 9, 19, 12, 0, 0)) do
example.run
end
end
it_behaves_like 'duplicates application form', 'apply_1', 2021
end
context 'when the application_form has references has an application_reference in the cancelled_at_end_of_cycle state' do
around do |example|
Timecop.freeze(Time.zone.local(2020, 9, 19, 12, 0, 0)) do
example.run
end
end
let(:application_form) { create(:completed_application_form) }
it 'sets the reference to the not_requested state' do
create(:reference, feedback_status: :feedback_provided, application_form: application_form)
create(:reference, feedback_status: :cancelled_at_end_of_cycle, application_form: application_form)
create(:reference, feedback_status: :feedback_refused, application_form: application_form)
described_class.new(application_form).call
expect(ApplicationForm.count).to eq 2
expect(ApplicationForm.last.application_references.count).to eq 2
expect(ApplicationForm.last.application_references.map(&:feedback_status)).to eq %w[feedback_provided not_requested_yet]
end
it 'does not carry over references whose feedback is overdue' do
create(:reference, feedback_status: :cancelled_at_end_of_cycle, application_form: application_form, requested_at: 1.month.ago)
create(:reference, feedback_status: :cancelled_at_end_of_cycle, application_form: application_form, requested_at: 1.month.ago)
create(:reference, feedback_status: :cancelled_at_end_of_cycle, application_form: application_form, requested_at: 2.days.ago, name: '<NAME>')
create(:reference, feedback_status: :cancelled_at_end_of_cycle, application_form: application_form, requested_at: 1.day.ago, name: 'Nixt Cycle')
described_class.new(application_form).call
expect(ApplicationForm.last.application_references.count).to eq 2
expect(ApplicationForm.last.application_references.map(&:name)).to eq ['<NAME>', 'Nixt Cycle']
end
end
end
|
<filename>src/main/java/org/olat/instantMessaging/manager/ChatLogHelper.java
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.instantMessaging.manager;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.annotation.PostConstruct;
import org.apache.logging.log4j.Logger;
import org.olat.basesecurity.IdentityImpl;
import org.olat.core.gui.media.MediaResource;
import org.olat.core.gui.translator.Translator;
import org.olat.core.id.OLATResourceable;
import org.olat.core.logging.Tracing;
import org.olat.core.util.Formatter;
import org.olat.core.util.Util;
import org.olat.core.util.openxml.OpenXMLWorkbook;
import org.olat.core.util.openxml.OpenXMLWorkbookResource;
import org.olat.core.util.openxml.OpenXMLWorksheet;
import org.olat.core.util.openxml.OpenXMLWorksheet.Row;
import org.olat.core.util.xml.XStreamHelper;
import org.olat.instantMessaging.InstantMessage;
import org.olat.instantMessaging.model.InstantMessageImpl;
import org.olat.instantMessaging.ui.ChatController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.thoughtworks.xstream.XStream;
/**
*
* Initial date: 10.12.2012<br>
* @author srosse, <EMAIL>, http://www.frentix.com
*
*/
@Service
public class ChatLogHelper {
private static final Logger log = Tracing.createLoggerFor(ChatLogHelper.class);
private XStream logXStream;
private static final int BATCH_SIZE = 100;
@Autowired
private InstantMessageDAO imDao;
@PostConstruct
public void init() {
logXStream = XStreamHelper.createXStreamInstance();
XStreamHelper.allowDefaultPackage(logXStream);
logXStream.alias("message", InstantMessageImpl.class);
logXStream.alias("identity", IdentityImpl.class);
logXStream.omitField(IdentityImpl.class, "user");
}
public void archive(OLATResourceable ores, File exportDirectory) {
File file = new File(exportDirectory, "chat.xml");
try(Writer writer = new FileWriter(file);
ObjectOutputStream out = logXStream.createObjectOutputStream(writer)) {
int counter = 0;
List<InstantMessage> messages;
do {
messages = imDao.getMessages(ores, null, counter, BATCH_SIZE);
for(InstantMessage message:messages) {
out.writeObject(message);
}
counter += messages.size();
} while(messages.size() == BATCH_SIZE);
} catch (IOException e) {
log.error("", e);
}
}
public MediaResource logMediaResource(OLATResourceable ores, Locale locale) {
Translator translator = Util.createPackageTranslator(ChatController.class, locale);
String tableExportTitle = translator.translate("logChat.export.title");
String label = tableExportTitle
+ Formatter.formatDatetimeFilesystemSave(new Date(System.currentTimeMillis()))
+ ".xlsx";
return new OpenXMLWorkbookResource(label) {
@Override
protected void generate(OutputStream out) {
try(OpenXMLWorkbook workbook = new OpenXMLWorkbook(out, 1)) {
//headers
OpenXMLWorksheet exportSheet = workbook.nextWorksheet();
Row headerRow = exportSheet.newRow();
headerRow.addCell(0, "User", workbook.getStyles().getHeaderStyle());
headerRow.addCell(1, "Date", workbook.getStyles().getHeaderStyle());
headerRow.addCell(2, "Content", workbook.getStyles().getHeaderStyle());
//content
List<InstantMessage> messages = imDao.getMessages(ores, null, 0, -1);
for(InstantMessage message:messages) {
Row dataRow = exportSheet.newRow();
dataRow.addCell(0, message.getFromNickName(), null);
dataRow.addCell(1, message.getCreationDate(), workbook.getStyles().getDateStyle());
dataRow.addCell(2, message.getBody(), null);
}
} catch (IOException e) {
log.error("", e);
}
}
};
}
}
|
#!/bin/bash -e
PORT=5000
# Simulates
curl \
"http://localhost:${PORT}/health-check" \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--compressed
echo ""
|
json.array!(@variants) do |variant|
json.extract! variant, :id, :size, :pattern_id, :44, :54, :60, :bust, :waist, :hips
json.url variant_url(variant, format: :json)
end
|
var searchData=
[
['unittesthelper',['UnitTestHelper',['../class_smol_dock_1_1_molecule.html#a3cb039460aae8734c10a3588e1d670a2',1,'SmolDock::Molecule']]],
['unknown',['unknown',['../class_smol_dock_1_1_amino_acid.html#a08692b12e7f53812c5258bd8b805875daad921d60486366258809553a3db49a4a',1,'SmolDock::AminoAcid::unknown()'],['../class_smol_dock_1_1_atom.html#a57e9a532fd04e1846c0d83edebb9fd41aad921d60486366258809553a3db49a4a',1,'SmolDock::Atom::unknown()']]],
['updateatompositionsfromiconformer',['updateAtomPositionsFromiConformer',['../class_smol_dock_1_1_molecule.html#af6263934134836e9ce66d2254b6b6801',1,'SmolDock::Molecule']]],
['updatedconformerid',['updatedConformerID',['../class_smol_dock_1_1_molecule.html#ab5d560b5e32304a9056bbecc3f0bebee',1,'SmolDock::Molecule']]]
];
|
<gh_stars>1-10
const soma = ((a, b) => {
return a + b;
});
const multiplicacao = ((a, b) => {
return a * b;
});
module.exports = {soma, multiplicacao};
|
class Tree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def max_depth(self):
if self is None:
return 0
else:
left_depth = self.left.max_depth() if self.left else 0
right_depth = self.right.max_depth() if self.right else 0
return max(left_depth, right_depth) + 1
|
<filename>src/icons/legacy/FrownO.tsx
// Generated by script, don't edit it please.
import createSvgIcon from '../../createSvgIcon';
import FrownOSvg from '@rsuite/icon-font/lib/legacy/FrownO';
const FrownO = createSvgIcon({
as: FrownOSvg,
ariaLabel: 'frown o',
category: 'legacy',
displayName: 'FrownO'
});
export default FrownO;
|
<gh_stars>0
#! /usr/bin/env python
# -*- coding:UTF-8 -*-
a = 37
def foo():
print("I'm foo and a is %s"% a)
def bar():
print("I'm bar and I'm calling foo")
foo()
class Spam(object):
def grok(self):
print("I'm Spam.grok")
|
using System;
using System.Collections.Generic;
using System.Linq;
public class MedianStars
{
public static int FindMedianStars(List<int> stars)
{
stars.Sort();
int n = stars.Count;
if (n % 2 == 0)
{
return (stars[n / 2 - 1] + stars[n / 2]) / 2;
}
else
{
return stars[n / 2];
}
}
public static void Main(string[] args)
{
List<int> input = new List<int> { 10, 5, 8, 12, 15, 6, 20 };
Console.WriteLine(FindMedianStars(input)); // Output: 10
}
}
|
#!/bin/bash
echo "THIS SCRIPT IS OBSOLETE AND INCLUDED BECAUSE OF AN ONGOING EXPERIMENT"
if [ "z${MAXNOISE}" = "z" ] ; then
MAXNOISE=3
echo Lacking environment variable MAXNOISE, using default value "${MAXNOISE} (percent)"
fi
# Perflock is preferred
PERFLOCK=`which perflock`
if [ "z${PERFLOCK}" = "z" -a `uname` = "Linux" ] ; then
echo "You can get cleaner benchmark results on Linux with perflock: go get github.com/aclements/perflock/..."
fi
BENCH=compile
BENCH_INLINES="${BENCH}.inlines"
BENCH_TRIALS="${BENCH}.trials"
BENCH_STAT="${BENCH}.laststat"
BENCH_LOG="${BENCH}.log"
# These ought to be okay.
THRESHOLD=67
COUNT=100000
SEED0=1
# For compiler testing, goal is to figure out which inlines really matter, and if any hurt;
# there's some suspicion that there are inlines in the 20-80 range that are bad for performance.
# CANNOT export the GO_INL versions of these, else it might perturb the benchmark itself.
MAXBUDGET=640
BIGMAXBUDGET=160
RECORDSIZE=20
# Begin one after the last trial run
if [ -e "${BENCH_TRIALS}" ] ; then
SEED=`tail -1 "${BENCH_TRIALS}" | awk -F , '{print 0+$2}'`
SEED0=$((SEED + 1))
echo "Resuming at seed=${SEED0}"
fi
# Create the record of all the inlines if none exists
if [ ! -e "${BENCH_INLINES}" ] ; then
echo "Creating list of all inline sites in ${BENCH_INLINES}"
mkdir -p testbin
GO_INLMAXBUDGET=${MAXBUDGET} GO_INLBIGMAXBUDGET=${BIGMAXBUDGET} GO_INLRECORDSIZE=${RECORDSIZE} GO_INLRECORDS=_ go build -a cmd/compile >& "${BENCH_INLINES}".tmp
grep INLINE_SITE "${BENCH_INLINES}".tmp | sort -u > "${BENCH_INLINES}"
fi
SEEDN=$((SEED0 + COUNT))
# FYI `eval echo {${SEED0}..${SEEDN}}` does what you want.
for S in `eval echo {${SEED0}..${SEEDN}}` ; do
rm -rf goroots testbin
mkdir -p testbin
solve_inlines -seed ${S} -threshold ${THRESHOLD} "${BENCH_INLINES}" > inlines.txt
go clean -cache
GO_INLMAXBUDGET=${MAXBUDGET} GO_INLBIGMAXBUDGET=${BIGMAXBUDGET} GO_INLRECORDSIZE=${RECORDSIZE} GO_INLRECORDS=$PWD/inlines.txt go build -a cmd/compile
# GOMAXPROCS below assumes a machine with well more than that, goal is to stamp out variation everywhere.
# Compilebench runs the compiler single-threaded, but how does compilebench itself run?
while \
GOMAXPROCS=4 $PERFLOCK compilebench -compile ${PWD}/compile -count 25 -run BenchmarkCompile | sed -E -e 's?[0-9]+ ns/op ??' > testbin/compile.TEST.stdout
benchstat -geomean -csv testbin/*.TEST.stdout >& "${BENCH_STAT}"
tail -1 "${BENCH_STAT}" >> "${BENCH_LOG}"
# Noise depends on whether it is one benchmark or several
if grep -q "Geo mean" "${BENCH_STAT}" ; then
# Extract max noise from all the benchmarks.
# awk: using comma as field separator, match 3-field lines where last field ends in "%", compute maxnoise, print it at the end.
NOISE=`awk -F , 'NF == 3 && $3~/.*%/ { gsub(" ","",$3); noise = 0+$3; if (noise > maxnoise) maxnoise=noise;} END {print maxnoise;}' < "${BENCH_STAT}" `
else
NOISE=`tail -1 "${BENCH_STAT}" | awk -F , '{gsub(" ","",$3); print $3}' | sed -e '1,$s/%//'`
fi
# awk: strip spaces out of second comma-separated field and print it.
TIME=`tail -1 "${BENCH_STAT}" | awk -F , '{gsub(" ","",$2); print $2}' `
echo "Seed=${S}, Threshold=${THRESHOLD}, Time=${TIME}, Max noise=${NOISE}"
if test -z "${NOISE}" ; then
true
else
test ${NOISE} -gt ${MAXNOISE}
fi
do
echo "Too noisy (${NOISE}), repeating test"
done
echo "${THRESHOLD},${S},${TIME},${NOISE}" >> "${BENCH_TRIALS}"
done
|
#!/usr/bin/env bash
echo "collecting coverage now..."
lcov --directory . --capture --output-file coverage.info # capture coverage info
lcov --remove coverage.info '/usr/bin/*' --output-file coverage.info # filter out system
lcov --remove coverage.info '/usr/lib/*' --output-file coverage.info # filter out system
lcov --remove coverage.info '/usr/include/*' --output-file coverage.info # filter out system
lcov --remove coverage.info '/usr/sbin/*' --output-file coverage.info # filter out system
lcov --remove coverage.info '/usr/share/*' --output-file coverage.info # filter out system
lcov --remove coverage.info 'test/*' --output-file coverage.info # filter out test
lcov --remove coverage.info 'libraries/fc/*' --output-file coverage.info
lcov --remove coverage.info 'libraries/net/*' --output-file coverage.info
lcov --remove coverage.info 'libraries/utilities/*' --output-file coverage.info
lcov --remove coverage.info 'libraries/vendor/*' --output-file coverage.info
lcov --remove coverage.info 'programs/*' --output-file coverage.info
echo "coverage collected to coverage.info"
ls -al coverage.info
|
<gh_stars>1-10
import { SLIDES_SELECTOR } from '../utils/constants.js'
import { queryAll, createStyleSheet } from '../utils/util.js'
/**
* Setups up our presentation for printing/exporting to PDF.
*/
export default class Print {
constructor( Reveal ) {
this.Reveal = Reveal;
}
/**
* Configures the presentation for printing to a static
* PDF.
*/
setupPDF() {
let config = this.Reveal.getConfig();
let slideSize = this.Reveal.getComputedSlideSize( window.innerWidth, window.innerHeight );
// Dimensions of the PDF pages
let pageWidth = Math.floor( slideSize.width * ( 1 + config.margin ) ),
pageHeight = Math.floor( slideSize.height * ( 1 + config.margin ) );
// Dimensions of slides within the pages
let slideWidth = slideSize.width,
slideHeight = slideSize.height;
// Let the browser know what page size we want to print
createStyleSheet( '@page{size:'+ pageWidth +'px '+ pageHeight +'px; margin: 0px;}' );
// Limit the size of certain elements to the dimensions of the slide
createStyleSheet( '.reveal section>images, .reveal section>video, .reveal section>iframe{max-width: '+ slideWidth +'px; max-height:'+ slideHeight +'px}' );
document.documentElement.classList.add( 'print-pdf' );
document.body.style.width = pageWidth + 'px';
document.body.style.height = pageHeight + 'px';
// Make sure stretch elements fit on slide
this.Reveal.layoutSlideContents( slideWidth, slideHeight );
// Compute slide numbers now, before we start duplicating slides
let doingSlideNumbers = config.slideNumber && /all|print/i.test( config.showSlideNumber );
queryAll( this.Reveal.getRevealElement(), SLIDES_SELECTOR ).forEach( function( slide ) {
slide.setAttribute( 'data-slide-number', this.Reveal.slideNumber.getSlideNumber( slide ) );
}, this );
// Slide and slide background layout
queryAll( this.Reveal.getRevealElement(), SLIDES_SELECTOR ).forEach( function( slide ) {
// Vertical stacks are not centred since their section
// children will be
if( slide.classList.contains( 'stack' ) === false ) {
// Center the slide inside of the page, giving the slide some margin
let left = ( pageWidth - slideWidth ) / 2,
top = ( pageHeight - slideHeight ) / 2;
let contentHeight = slide.scrollHeight;
let numberOfPages = Math.max( Math.ceil( contentHeight / pageHeight ), 1 );
// Adhere to configured pages per slide limit
numberOfPages = Math.min( numberOfPages, config.pdfMaxPagesPerSlide );
// Center slides vertically
if( numberOfPages === 1 && config.center || slide.classList.contains( 'center' ) ) {
top = Math.max( ( pageHeight - contentHeight ) / 2, 0 );
}
// Wrap the slide in a page element and hide its overflow
// so that no page ever flows onto another
let page = document.createElement( 'div' );
page.className = 'pdf-page';
page.style.height = ( ( pageHeight + config.pdfPageHeightOffset ) * numberOfPages ) + 'px';
slide.parentNode.insertBefore( page, slide );
page.appendChild( slide );
// Position the slide inside of the page
slide.style.left = left + 'px';
slide.style.top = top + 'px';
slide.style.width = slideWidth + 'px';
if( slide.slideBackgroundElement ) {
page.insertBefore( slide.slideBackgroundElement, slide );
}
// Inject notes if `showNotes` is enabled
if( config.showNotes ) {
// Are there notes for this slide?
let notes = this.Reveal.getSlideNotes( slide );
if( notes ) {
let notesSpacing = 8;
let notesLayout = typeof config.showNotes === 'string' ? config.showNotes : 'inline';
let notesElement = document.createElement( 'div' );
notesElement.classList.add( 'speaker-notes' );
notesElement.classList.add( 'speaker-notes-pdf' );
notesElement.setAttribute( 'data-layout', notesLayout );
notesElement.innerHTML = notes;
if( notesLayout === 'separate-page' ) {
page.parentNode.insertBefore( notesElement, page.nextSibling );
}
else {
notesElement.style.left = notesSpacing + 'px';
notesElement.style.bottom = notesSpacing + 'px';
notesElement.style.width = ( pageWidth - notesSpacing*2 ) + 'px';
page.appendChild( notesElement );
}
}
}
// Inject slide numbers if `slideNumbers` are enabled
if( doingSlideNumbers ) {
let numberElement = document.createElement( 'div' );
numberElement.classList.add( 'slide-number' );
numberElement.classList.add( 'slide-number-pdf' );
numberElement.innerHTML = slide.getAttribute( 'data-slide-number' );
page.appendChild( numberElement );
}
// Copy page and show fragments one after another
if( config.pdfSeparateFragments ) {
// Each fragment 'group' is an array containing one or more
// fragments. Multiple fragments that appear at the same time
// are part of the same group.
let fragmentGroups = this.Reveal.fragments.sort( page.querySelectorAll( '.fragment' ), true );
let previousFragmentStep;
let previousPage;
fragmentGroups.forEach( function( fragments ) {
// Remove 'current-fragment' from the previous group
if( previousFragmentStep ) {
previousFragmentStep.forEach( function( fragment ) {
fragment.classList.remove( 'current-fragment' );
} );
}
// Show the fragments for the current index
fragments.forEach( function( fragment ) {
fragment.classList.add( 'visible', 'current-fragment' );
}, this );
// Create a separate page for the current fragment state
let clonedPage = page.cloneNode( true );
page.parentNode.insertBefore( clonedPage, ( previousPage || page ).nextSibling );
previousFragmentStep = fragments;
previousPage = clonedPage;
}, this );
// Reset the first/original page so that all fragments are hidden
fragmentGroups.forEach( function( fragments ) {
fragments.forEach( function( fragment ) {
fragment.classList.remove( 'visible', 'current-fragment' );
} );
} );
}
// Show all fragments
else {
queryAll( page, '.fragment:not(.fade-out)' ).forEach( function( fragment ) {
fragment.classList.add( 'visible' );
} );
}
}
}, this );
// Notify subscribers that the PDF layout is good to go
this.Reveal.dispatchEvent({ type: 'pdf-ready' });
}
/**
* Checks if this instance is being used to print a PDF.
*/
isPrintingPDF() {
return ( /print-pdf/gi ).test( window.location.search );
}
}
|
#!/bin/bash
TEST_DIR="$(cd "$(dirname "${0}")" && pwd)"
source "${TEST_DIR}/lib.sh"
copy_deploy
run -r master -e "${TEST_DIR}/test-inside-gk-deploy.sh" "Test basic deployment"
run -r master "${TEST_DIR}/test-inside-gk-deploy.sh" "Test basic deployment idempotence"
|
#!/bin/bash
# Set environment variables
PATH2SCRIPTS="/path/to/scripts"
MDDESCRIPTORS="/path/to/md_descriptors"
BASH_HYDRATION_CODE="${PATH2SCRIPTS}/extract_hydration_maps.sh"
BASH_HYDRATION_CODE_GMX_SELECT="${PATH2SCRIPTS}/extract_hydration_maps_with_gmx_select.sh"
PATH_SUBMISSIONS="${PATH2SCRIPTS}/submission_scripts"
JOB_LIST="${PATH2SCRIPTS}/job_list.txt"
PYTHON_SCRIPTS_GRIDDING="${MDDESCRIPTORS}/surface/generate_wc_grid.py"
# Execute hydration map extraction scripts
echo "Executing hydration map extraction script: $BASH_HYDRATION_CODE"
bash $BASH_HYDRATION_CODE
echo "Executing hydration map extraction script with gmx select: $BASH_HYDRATION_CODE_GMX_SELECT"
bash $BASH_HYDRATION_CODE_GMX_SELECT
# Execute Python script for gridding
echo "Executing Python script for gridding: $PYTHON_SCRIPTS_GRIDDING"
python $PYTHON_SCRIPTS_GRIDDING
echo "Hydration map extraction and gridding completed successfully."
|
// Define the Transmitter interface
interface Transmitter {
boolean sendMessage(String message, String recipient);
String receiveMessage(String recipient);
}
// Implement the EmailTransmitter class
class EmailTransmitter implements Transmitter {
@Override
public boolean sendMessage(String message, String recipient) {
// Implement email sending logic
// Return true if the email was successfully sent, false otherwise
return true; // Placeholder for actual email sending logic
}
@Override
public String receiveMessage(String recipient) {
// Implement email receiving logic
// Return the latest email message received by the recipient
return "Latest email message for " + recipient; // Placeholder for actual email receiving logic
}
}
// Implement the SMStransmitter class
class SMStransmitter implements Transmitter {
@Override
public boolean sendMessage(String message, String recipient) {
// Implement SMS sending logic
// Return true if the SMS was successfully sent, false otherwise
return true; // Placeholder for actual SMS sending logic
}
@Override
public String receiveMessage(String recipient) {
// Implement SMS receiving logic
// Return the latest SMS message received by the recipient
return "Latest SMS message for " + recipient; // Placeholder for actual SMS receiving logic
}
}
|
import React, { useState } from 'react';
function App() {
const colors = ["red", "blue", "green", "purple", "pink"];
const [search, setSearch] = useState('');
const [filteredColors, setFilteredColors] = useState(colors);
const handleChange = event => {
setSearch(event.target.value);
const lowerCasedSearch = search.toLowerCase();
setFilteredColors(colors.filter(color =>
color.toLowerCase().includes(lowerCasedSearch)
));
};
return (
<div>
<input type="text" value={search} onChange={handleChange} />
<ul>
{filteredColors.map(color => (
<li key={color}>{color}</li>
))}
</ul>
</div>
);
}
export default App;
|
package cn.st.junit;
public class CalculatorTest {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(1, 3));
}
}
|
def even_odd_lists(list_input):
even_list = []
odd_list = []
for element in list_input:
if element % 2 == 0:
even_list.append(element)
else:
odd_list.append(element)
print("Even list:", even_list)
print("Odd list:", odd_list)
list_input = [1, 2, 3, 4, 5, 6, 7, 8]
even_odd_lists(list_input)
|
CLOCK_THEME_PROMPT_COLOR=124
CWD_THEME_PROMPT_COLOR=111
HOST_THEME_PROMPT_COLOR=99
SCM_THEME_PROMPT_CLEAN_COLOR=4
SCM_THEME_PROMPT_STAGED_COLOR=2563
SCM_THEME_PROMPT_DIRTY_COLOR=2561
SCM_THEME_PROMPT_UNSTAGED_COLOR=209
USER_INFO_THEME_PROMPT_COLOR=126
GO_THEME_PROMPT_COLOR=19
POWERLINE_GO_COLOR=33
NODE_THEME_PROMPT_COLOR=26
#CLOCK_THEME_PROMPT_COLOR=214
#CWD_THEME_PROMPT_COLOR=123
#HOST_THEME_PROMPT_COLOR=9
#RUBY_THEME_PROMPT_COLOR=202
#SCM_THEME_PROMPT_CLEAN_COLOR=560
#SCM_THEME_PROMPT_STAGED_COLOR=1251
#SCM_THEME_PROMPT_UNSTAGED_COLOR=209
#USER_INFO_THEME_PROMPT_COLOR=46
#GO_THEME_PROMPT_COLOR=33
#POWERLINE_GO_COLOR=33
|
<filename>webapp/model.py
import pandas as pd
from google.cloud import firestore
from google.cloud import bigquery
from datetime import datetime, timezone
def predicted_pointspread(teams):
try:
df = pd.DataFrame(teams, index=[0])
model = df['Model'][0]
client = bigquery.Client()
inputs = client.query('''
SELECT
input
FROM
ML.FEATURE_INFO(MODEL `nba.%s`)
''' % (model)).to_dataframe()
db = firestore.Client()
home_team_data = db.collection('team_model_data').document(df['HomeTeam'][0]).get().to_dict()
away_team_data = db.collection('team_model_data').document(df['AwayTeam'][0]).get().to_dict()
query = f'SELECT predicted_spread FROM ML.PREDICT(MODEL `nba.{model}`, (SELECT '
for column in inputs.input:
key = column[9:]
if column == 'is_home_team':
query = query + '1 as is_home_team,'
elif column == 'rest_days_difference':
home_rest = (datetime.now(timezone.utc) - home_team_data['game_date']).days
away_rest = (datetime.now(timezone.utc) - away_team_data['game_date']).days
rest_days_difference = home_rest - away_rest
query = query + f'{rest_days_difference} as {column},'
elif column == 'incoming_is_win_streak':
query = query + f'{home_team_data["streak_counter_is_win"]} as {column},'
elif (column == 'opponent_incoming_is_win_streak') | (column == 'incoming_is_win_streak_opponent'):
query = query + f'{away_team_data["streak_counter_is_win"]} as {column},'
elif column[:12] == 'incoming_wma':
if column.split('_')[3] == 'opponent':
query = query + f'{away_team_data[key]} as {column},'
else:
query = query + f'{away_team_data[key]} as {column},'
else:
return f'Error: Model input column {column} not in team data in firestore or not in logic in App Engine. Please try a different model'
bq_query = query[:-1] + '))'
game_bq = client.query('''
%s
''' % (bq_query))
game = game_bq.to_dataframe()
pointspread = round(game['predicted_spread'][0],1)
if pointspread > 0:
winner = df['HomeTeam'][0]
loser = df['AwayTeam'][0]
else:
winner = df['AwayTeam'][0]
loser = df['HomeTeam'][0]
return f'I predict the {winner} will beat the {loser} by {abs(pointspread)} points using the {model} model!'
except Exception as e:
raise ValueError('Sorry, there was a problem processing the data entered... Please try again with different teams') from e
|
<filename>service/frontend/src/components/select/index.tsx
import React, {
HTMLProps,
useState,
useRef,
useEffect,
MouseEvent,
KeyboardEvent,
} from "react";
import { Label } from "src/components/label";
import { useOutsideEventAwareness } from "src/hooks/use-outside-event-awareness";
import "./index.css";
const ID = {
s: "select",
id: 0,
next() {
return this.s + "-" + this.id++;
},
};
export type Option = {
k: string;
v: any;
};
type OptionProps = Option & {
handleClick: (_: { k: string; v: any }) => void;
};
function Option({ k, v, handleClick }: OptionProps) {
const classes = "select-options-suggestions__suggestion";
const clickHandler = (e: MouseEvent) => handleClick({ k, v });
const keyUpHandler = (e: KeyboardEvent) =>
e.key === "Enter" && handleClick({ k, v });
return (
<div
className={classes}
onMouseUp={clickHandler}
onKeyUp={keyUpHandler}
tabIndex={0}
>
{k}
</div>
);
}
export type HandleSelect = (_: any) => void;
type OptionsProps = {
options: Option[];
active: Option;
id: string;
handleSelect: HandleSelect;
};
function Options({ options, active, id, handleSelect }: OptionsProps) {
const [open, setOpen] = useState(false);
const [selected, setSelected] = useState(active);
const eventOutsideHandler = () => setOpen(false);
const ref = useRef(null);
useOutsideEventAwareness(
ref,
["mousedown", "touchstart"],
eventOutsideHandler
);
useEffect(() => setSelected(active), [active]);
const classes = {
options: "select__options",
selected: "select-options__selected",
suggestions:
"select-options__suggestions select-options__suggestions_" +
(open ? "open" : "close"),
};
const clickHandler = (pair: Option) => {
setSelected(pair);
setOpen(false);
handleSelect && handleSelect(pair);
};
return (
<div className={classes.options} ref={ref}>
<div
className={classes.selected}
onClick={() => setOpen(!open)}
onKeyUp={(e: KeyboardEvent) =>
e.key === "Enter" && setOpen(!open)
}
id={id}
tabIndex={0}
>
{selected.k}
</div>
<div className={classes.suggestions}>
{options
.filter(({ k }) => k !== selected.k)
.map((o, i: number) => (
<Option
{...o}
handleClick={clickHandler}
key={id + "-" + i}
/>
))}
</div>
</div>
);
}
export type SelectProps = {
options: Option[];
selected: Option;
label?: string;
handleSelect: HandleSelect;
};
export function Select({
options,
selected,
label,
handleSelect,
}: SelectProps) {
const id = ID.next();
return (
<div className="select">
{label && <Label text={label} id={id} />}
{options && (
<Options
options={options}
handleSelect={handleSelect}
active={selected}
id={id}
/>
)}
</div>
);
}
|
<reponame>raghav-deepsource/realm-java<gh_stars>1-10
/*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.entities.migration;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.migration.MigrationPrimaryKey;
// Class used for testing what happens if you modify fields defined before the primary key field
public class MigrationPriorIndexOnly extends RealmObject implements MigrationPrimaryKey {
public static String CLASS_NAME = "MigrationPriorIndexOnly";
public static long DEFAULT_FIELDS_COUNT = 3;
public static long DEFAULT_PRIMARY_INDEX = 2;
private Byte fieldFirst;
private Short fieldSecond;
@PrimaryKey
private String fieldPrimary;
public void setFieldFirst(Byte fieldFirst) {
this.fieldFirst = fieldFirst;
}
public Byte getFieldFirst() {
return this.fieldFirst;
}
public void setFieldSecond(Short fieldSecond) {
this.fieldSecond = fieldSecond;
}
public Short getFieldSecond() {
return this.fieldSecond;
}
public void setFieldPrimary(String fieldPrimary) {
this.fieldPrimary = fieldPrimary;
}
public String getFieldPrimary() {
return this.fieldPrimary;
}
}
|
#!/bin/bash
#
# Copyright 2021 The Kubeflow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Fail the entire script when any command fails.
set -ex
NAMESPACE="${NAMESPACE:-kubeflow}"
TEST_CLUSTER="${TEST_CLUSTER:-kfp-standalone-1}"
REGION="${REGION:-us-central1}"
PROJECT="${PROJECT:-kfp-ci}"
# The current directory is /home/prow/go/src/github.com/kubeflow/pipelines
# 1. install go in /home/prow/go1.15.10
cd /home/prow
mkdir go1.15.10
cd go1.15.10
curl -LO https://dl.google.com/go/go1.15.10.linux-amd64.tar.gz
tar -xf go1.15.10.linux-amd64.tar.gz
export PATH="/home/prow/go1.15.10/go/bin:${PATH}"
cd /home/prow/go/src/github.com/kubeflow/pipelines/backend/src/v2
# 2. Check go modules are tidy
# Reference: https://github.com/golang/go/issues/27005#issuecomment-564892876
go mod download
go mod tidy
git diff --exit-code -- go.mod go.sum || (echo "go modules are not tidy, run 'go mod tidy'." && exit 1)
# Note, for tests that use metadata grpc api, port-forward it locally in a separate terminal by:
if [[ ! -z "${GOOGLE_APPLICATION_CREDENTIALS}" ]]; then
gcloud auth activate-service-account --key-file="${GOOGLE_APPLICATION_CREDENTIALS}"
fi
gcloud container clusters get-credentials "$TEST_CLUSTER" --region "$REGION" --project "$PROJECT"
function cleanup() {
echo "killing kubectl port forward before exit"
kill "$PORT_FORWARD_PID"
}
trap cleanup EXIT
kubectl port-forward svc/metadata-grpc-service 8080:8080 -n "$NAMESPACE" & PORT_FORWARD_PID=$!
# wait for kubectl port forward
sleep 10
go test -v -cover ./...
# TODO(zijianjoy): re-enable license check for v2 images
# verify licenses are up-to-date, because all license updates must be reviewed by a human.
# ../hack/install-go-licenses.sh
# make license-launcher
# git diff --exit-code -- third_party/licenses/launcher.csv || (echo "v2/third_party/licenses/launcher.csv is outdated, refer to https://github.com/kubeflow/pipelines/tree/master/v2#update-licenses for update instructions.")
|
import sys
import signal, functools
import os
def timeout(seconds, error_message="Timeout Error: the cmd 30s have not finished."):
def decorated(func):
result = ""
def _handle_timeout(signum, frame):
global result
result = error_message
os._exit(error_message)
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
global result
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return result
return functools.wraps(func)(wrapper)
return decorated
@timeout(1) # 限定下面的slowfunc函数如果在5s内不返回就强制抛TimeoutError Exception结束
def slowfunc(sleep_time):
a = 1
while True:
pass
return a
# slowfunc(3) #sleep 3秒,正常返回 没有异常
print(slowfunc(11)) # 被终止
|
<filename>node_modules/spotify-web-api-node/examples/add-tracks-to-a-playlist.js
const SpotifyWebApi = require('../');
/**
* This example demonstrates adding tracks to a specified position in a playlist.
*
* Since authorization is required, this example retrieves an access token using the Authorization Code Grant flow,
* documented here: https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
*
* Codes are given for a set of scopes. For this example, the scopes are playlist-modify-public.
* Scopes are documented here:
* https://developer.spotify.com/documentation/general/guides/scopes/
*/
/* Obtain the `authorizationCode` below as described in the Authorization section of the README.
*/
const authorizationCode = '<insert authorization code>';
/**
* Get the credentials from Spotify's Dashboard page.
* https://developer.spotify.com/dashboard/applications
*/
const spotifyApi = new SpotifyWebApi({
clientId: '<insert client id>',
clientSecret: '<insert client secret>',
redirectUri: '<insert redirect URI>'
});
// First retrieve an access token
spotifyApi
.authorizationCodeGrant(authorizationCode)
.then(function(data) {
spotifyApi.setAccessToken(data.body['access_token']);
return spotifyApi.addTracksToPlaylist(
'5ieJqeLJjjI8iJWaxeBLuK',
[
'spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
'spotify:track:1301WleyT98MSxVHPZCA6M'
],
{
position: 10
}
);
})
.then(function(data) {
console.log('Added tracks to the playlist!');
})
.catch(function(err) {
console.log('Something went wrong:', err.message);
});
|
#!/usr/bin/env bash
cd "$(dirname "${BASH_SOURCE}")";
git pull origin master;
function setupZshUbuntu() {
# install ZSH if needed
if [ -z $(which zsh) ]; then
echo "Installing zsh";
sudo apt install -y zsh;
sudo chsh -s $(which zsh);
fi
# setup Oh-my-ZSH
if [ ! -d ~/.oh-my-zsh ]; then
echo "Installing oh-my-zsh";
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" "" --unattended
fi
# setup oh-my-zsh themes
# setup oh-my-zsh plugins
# autosuggestions
__folder=${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
if [ ! -d $__folder ]; then
git clone https://github.com/zsh-users/zsh-autosuggestions $__folder
fi
unset __folder;
}
function syncSettings() {
rsync --exclude ".git/" \
--exclude ".gitconfig" \
--exclude ".DS_Store" \
--exclude ".osx" \
--exclude "bootstrap.sh" \
--exclude "symlink-setup.sh" \
--exclude "README.md" \
--exclude "LICENSE-MIT.txt" \
-avh --no-perms . ~;
source ~/.bash_profile;
}
setupZshUbuntu;
if [ "$1" == "--force" -o "$1" == "-f" ]; then
syncSettings;
else
read -p "This may overwrite existing files in your home directory. Are you sure? (y/n) " -n 1;
echo "";
if [[ $REPLY =~ ^[Yy]$ ]]; then
syncSettings;
fi;
fi;
unset setupZsh;
unset syncSettings;
|
<reponame>Luukvdm/doodleguesser<filename>DoodleGuesser/SocketGameServer/src/main/java/socketgameserver/messaging/messagehandlers/AddPointToPathMessageHandler.java
package socketgameserver.messaging.messagehandlers;
import socketgameserver.model.IGame;
import socketgameshared.messaging.messages.AddPointToPathMessage;
import fontysmultipurposelibrary.communication.messaging.MessageHandlerBase;
public class AddPointToPathMessageHandler extends MessageHandlerBase<AddPointToPathMessage> {
private IGame game;
public AddPointToPathMessageHandler(IGame game) {
this.game = game;
}
@Override
public void handleMessageInternal(AddPointToPathMessage message, String sessionId) {
game.addPointToPath(sessionId, message.getX(), message.getY());
}
}
|
require "rails_helper"
RSpec.describe GlobalExportNotification, type: :mailer do
describe "notification_email" do
subject(:mail) { GlobalExportNotification.notification_email("<EMAIL>", "http://www.example.com/foo.csv") }
it "is sent from the no reply address" do
expect(mail.from).to eq ["<EMAIL>"]
end
it "is sent to the correct recipient" do
expect(mail.to).to eq ["<EMAIL>"]
end
it "contains the URL" do
expect(mail.body).to include "http://www.example.com/foo.csv"
end
end
end
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Set Hadoop-specific environment variables here.
# The only required environment variable is JAVA_HOME. All others are
# optional. When running a distributed configuration it is best to
# set JAVA_HOME in this file, so that it is correctly defined on
# remote nodes.
# The java implementation to use.
export JAVA_HOME=##JAVA_HOME##
# The jsvc implementation to use. Jsvc is required to run secure datanodes
# that bind to privileged ports to provide authentication of data transfer
# protocol. Jsvc is not required if SASL is configured for authentication of
# data transfer protocol using non-privileged ports.
#export JSVC_HOME=${JSVC_HOME}
export HADOOP_CONF_DIR=${HADOOP_CONF_DIR}
# Extra Java CLASSPATH elements. Automatically insert capacity-scheduler.
for f in $HADOOP_HOME/contrib/capacity-scheduler/*.jar; do
if [ "$HADOOP_CLASSPATH" ]; then
export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$f
else
export HADOOP_CLASSPATH=$f
fi
done
# The maximum amount of heap to use, in MB. Default is 1000.
#export HADOOP_HEAPSIZE=
#export HADOOP_NAMENODE_INIT_HEAPSIZE=""
# Extra Java runtime options. Empty by default.
export HADOOP_OPTS="$HADOOP_OPTS ##JAVA_XMX## -Djava.net.preferIPv4Stack=true"
# Command specific options appended to HADOOP_OPTS when specified
export HADOOP_NAMENODE_OPTS="-Dhadoop.security.logger=${HADOOP_SECURITY_LOGGER:-INFO,RFAS} -Dhdfs.audit.logger=${HDFS_AUDIT_LOGGER:-INFO,NullAppender} $HADOOP_NAMENODE_OPTS"
export HADOOP_DATANODE_OPTS="-Dhadoop.security.logger=ERROR,RFAS $HADOOP_DATANODE_OPTS"
export HADOOP_SECONDARYNAMENODE_OPTS="-Dhadoop.security.logger=${HADOOP_SECURITY_LOGGER:-INFO,RFAS} -Dhdfs.audit.logger=${HDFS_AUDIT_LOGGER:-INFO,NullAppender} $HADOOP_SECONDARYNAMENODE_OPTS"
export HADOOP_NFS3_OPTS="$HADOOP_NFS3_OPTS"
export HADOOP_PORTMAP_OPTS="-Xmx512m $HADOOP_PORTMAP_OPTS"
# The following applies to multiple commands (fs, dfs, fsck, distcp etc)
export HADOOP_CLIENT_OPTS="-Xmx512m $HADOOP_CLIENT_OPTS"
#HADOOP_JAVA_PLATFORM_OPTS="-XX:-UsePerfData $HADOOP_JAVA_PLATFORM_OPTS"
# On secure datanodes, user to run the datanode as after dropping privileges.
# This **MUST** be uncommented to enable secure HDFS if using privileged ports
# to provide authentication of data transfer protocol. This **MUST NOT** be
# defined if SASL is configured for authentication of data transfer protocol
# using non-privileged ports.
export HADOOP_SECURE_DN_USER=${HADOOP_SECURE_DN_USER}
# Where log files are stored. $HADOOP_HOME/logs by default.
export HADOOP_LOG_DIR=##LOG_DIR##
export YARN_LOG_DIR=##LOG_DIR##
# Where log files are stored in the secure data environment.
export HADOOP_SECURE_DN_LOG_DIR=${HADOOP_LOG_DIR}/${HADOOP_HDFS_USER}
###
# HDFS Mover specific parameters
###
# Specify the JVM options to be used when starting the HDFS Mover.
# These options will be appended to the options specified as HADOOP_OPTS
# and therefore may override any similar flags set in HADOOP_OPTS
#
# export HADOOP_MOVER_OPTS=""
###
# Advanced Users Only!
###
# The directory where pid files are stored. /tmp by default.
# NOTE: this should be set to a directory that can only be written to by
# the user that will run the hadoop daemons. Otherwise there is the
# potential for a symlink attack.
export HADOOP_PID_DIR=${HADOOP_PID_DIR}
export HADOOP_SECURE_DN_PID_DIR=${HADOOP_PID_DIR}
# A string representing this instance of hadoop. $USER by default.
export HADOOP_IDENT_STRING=$USER
|
<reponame>Annabelle1024/WYNewws
//
// UILabel+YJAddition.h
//
// Created by Annabelle on 16/5/28.
// Copyright © 2016年 annabelle. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UILabel (YJAddition)
/// 创建文本标签
///
/// @param text 文本
/// @param fontSize 字体大小
/// @param color 颜色
///
/// @return UILabel
+ (instancetype)yj_labelWithText:(NSString *)text fontSize:(CGFloat)fontSize color:(UIColor *)color;
@end
|
#!/bin/bash
eval `resize`
UBUNTUISO_BIONIC='http://archive.ubuntu.com/ubuntu/dists/bionic-updates/main/installer-amd64/current/images/netboot/mini.iso'
UBUNTUISO_XENIAL='http://archive.ubuntu.com/ubuntu/dists/xenial-updates/main/installer-amd64/current/images/netboot/mini.iso'
PROG_TITLE="AASAAM Ubuntu overssh installation"
URL_REGEX='(http)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]'
SIZE_X=$(( $LINES - 12 ))
SIZE_Y=$(( $COLUMNS - 8 ))
SIZE_LS=$(( $LINES - 24 ))
function to_int {
local -i num="10#${1}"
echo "${num}"
}
function port_is_ok {
local port="$1"
local -i port_num=$(to_int "${port}" 2>/dev/null)
if (( $port_num < 1 || $port_num > 65535 )) ; then
echo 'faild'
return
fi
echo 'ok'
}
function validate_ip() {
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
|
package io.flutter.plugins;
import android.app.Activity;
import android.content.Intent;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/**
* LocationPickerPlugin
*/
public class LocationPickerPlugin implements MethodCallHandler {
/**
* Plugin registration.
*/
static MethodCall call;
static Result result;
private Activity activity;
private LocationPickerPlugin(Activity activity)
{
this.activity = activity;
}
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "location_picker_plugin");
channel.setMethodCallHandler(new LocationPickerPlugin(registrar.activity()));
}
@Override
public void onMethodCall(MethodCall call, Result result) {
if (call.method.equals("locationPicker")) {
LocationPickerPlugin.call = call;
LocationPickerPlugin.result = result;
Intent intent = new Intent(activity, LocationPickerActivity.class);
activity.startActivity(intent);
} else {
result.notImplemented();
}
}
}
|
#!/bin/bash
# Wazuh Docker Copyright (C) 2020 Wazuh Inc. (License GPLv2)
set -e
el_url=${ELASTICSEARCH_URL}
if [[ ${ENABLED_XPACK} != "true" || "x${ELASTICSEARCH_USERNAME}" = "x" || "x${ELASTICSEARCH_PASSWORD}" = "x" ]]; then
auth=""
else
auth="--user ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD}"
fi
until curl ${auth} -XGET $el_url; do
>&2 echo "Elastic is unavailable - sleeping"
sleep 5
done
>&2 echo "Elastic is up - executing command"
if [ $ENABLE_CONFIGURE_S3 ]; then
#Wait for Elasticsearch to be ready to create the repository
sleep 10
IP_PORT="${ELASTICSEARCH_IP}:${ELASTICSEARCH_PORT}"
if [ "x$S3_PATH" != "x" ]; then
if [ "x$S3_ELASTIC_MAJOR" != "x" ]; then
./config/configure_s3.sh $IP_PORT $S3_BUCKET_NAME $S3_PATH $S3_REPOSITORY_NAME $S3_ELASTIC_MAJOR
else
./config/configure_s3.sh $IP_PORT $S3_BUCKET_NAME $S3_PATH $S3_REPOSITORY_NAME
fi
fi
fi
curl -XPUT "$el_url/_cluster/settings" ${auth} -H 'Content-Type: application/json' -d'
{
"persistent": {
"xpack.monitoring.collection.enabled": true
}
}
'
# Set cluster delayed timeout when node falls
curl -X PUT "$el_url/_all/_settings" -H 'Content-Type: application/json' -d'
{
"settings": {
"index.unassigned.node_left.delayed_timeout": "'"$CLUSTER_DELAYED_TIMEOUT"'"
}
}
'
echo "Elasticsearch is ready."
|
#pragma once
#include <flowi_core/config.h>
#include <flowi_core/error.h>
#include <flowi_core/layout.h>
#include "command_buffer.h"
#include "flowi.h"
#include "handles.h"
#include "layout_private.h"
#include "primitives.h"
#include "simd.h"
#include "string_allocator.h"
#include "vertex_allocator.h"
#if defined(FL_FONTLIB_FREETYPE)
#include <freetype/freetype.h>
#endif
#define FL_FONTS_MAX 32
#define FL_MAX_STYLES 128
#define FL_MAX_LAYOUTS 256
#define FL_STYLE_DEPTH 128
// TODO: Move
#define FL_RGB(r, g, b) (((u32)b) << 16 | (((u32)g) << 8) | ((u32)r))
#define FL_RGB_RED FL_RGB(255, 0, 0)
#define FL_RGB_WHITE FL_RGB(255, 255, 255)
#define FL_RGB_BLACK FL_RGB(0, 0, 0)
struct Font;
struct StyleInternal;
struct Atlas;
typedef u32 FlowiID;
typedef struct FlGlobalState {
#if defined(FL_FONTLIB_FREETYPE)
FT_Library ft_library;
#endif
FlAllocator* global_allocator;
// Handles
Handles image_handles;
Handles font_handles;
// Primitive commands
CommandBuffer primitive_commands;
// Render commands that is generated for the rendering backend
CommandBuffer render_commands;
// TODO: We may have to support more atlases, but right now we have three
// One for grayscale fonts, one for colored fonts and one for images.
struct Atlas* mono_fonts_atlas;
struct Atlas* color_fonts_atlas;
struct Atlas* images_atlas;
u16 texture_ids;
} FlGlobalState;
// These are for internal library wise functions. This header should never
// be included in the public headers!
#define ERROR_ADD(t, format, ...) Errors_add(t, __FILE__, __LINE__, format, __VA_ARGS__);
void Errors_add(FlError err, const char* filename, int line, const char* fmt, ...);
void Font_init(FlGlobalState* ctx);
typedef struct Rect {
float x, y, width, height;
} Rect;
typedef struct IntRect {
int x, y, width, height;
} IntRect;
typedef struct IntAABB {
int min_x, min_y, max_x, max_y;
} IntAABB;
// TODO: We can lilkey do this better
typedef struct ItemWithText {
char text[1024];
int len;
} ItemWithText;
// Used to determine what kind of navigation we are doing
typedef enum InputSource {
InputSource_None = 0,
InputSource_Mouse,
InputSource_Nav,
// Only used occasionally for storage, not tested/handled by most code
InputSource_NavKeyboard,
// Only used occasionally for storage, not tested/handled by most code
InputSource_NavGamepad,
ImGuiInputSource_COUNT
} InputSource;
#define MAX_MOUSE_BUTTONS 3
typedef struct MouseState {
// = 0.30f - Time for a double-click, in seconds.
f32 double_click_time;
// = 6.0f - Distance threshold to stay in to validate a double-click, in pixels.
f32 double_click_max_dist;
// Time of last click (used to figure out double-click)
f64 clicked_time[MAX_MOUSE_BUTTONS];
// Current mouse position
FlVec2 pos;
// Previous mouse position (note that Delta is not necessary == Pos-PosPrev, in case either position is invalid)
FlVec2 pos_prev;
// Delta direction of the mouse
FlVec2 delta;
// Position at time of clicking
FlVec2 clicked_pos[MAX_MOUSE_BUTTONS];
// Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
FlVec2 drag_max_distance_abs[MAX_MOUSE_BUTTONS];
// Duration the mouse button has been down (0.0f == just clicked)
f32 down_duration[MAX_MOUSE_BUTTONS];
// Previous time the mouse button has been down
f32 down_duration_prev[MAX_MOUSE_BUTTONS];
// Squared maximum distance of how much mouse has traveled from the clicking point
f32 drag_max_distance_sqr[MAX_MOUSE_BUTTONS];
// Updated by external code
bool down[MAX_MOUSE_BUTTONS];
// Mouse button went from !Down to Down
bool clicked[MAX_MOUSE_BUTTONS];
// Has mouse button been double-clicked?
bool double_clicked[MAX_MOUSE_BUTTONS];
// Mouse button went from Down to !Down
bool released[MAX_MOUSE_BUTTONS];
// Track if button down was a double-click
bool down_was_double_click[MAX_MOUSE_BUTTONS];
// TODO: Move?
bool nav_disable_hover;
} MouseState;
typedef struct FlContext {
// Current time
double time;
// Current delta time (usually 1.0f/60 at 60 fps update)
float delta_time;
// Tracks the mouse state for this frame
MouseState mouse;
// Temporary text input when CTRL+clicking on a slider, etc.
FlowiID temp_input_id;
// Hovered widget, filled during the frame
FlowiID hovered_id;
FlowiID hovered_id_previous_frame;
bool hovered_id_allow_overlap;
// Hovered widget will use mouse wheel. Blocks scrolling the underlying window.
bool hovered_id_using_mouse_wheel;
bool hovered_id_previous_frame_using_mouse_wheel;
// At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true
// even if HoveredId == 0.
bool hovered_id_disabled;
// Measure contiguous hovering time
float hovered_id_timer;
// Measure contiguous hovering time where the item has not been active
float hovered_id_not_active_timer;
// Data for tracking the active id
// Active widget
FlowiID active_id;
// Active widget has been seen this frame (we can't use a bool as the active_id may change within the frame)
FlowiID active_id_is_alive;
float active_id_timer;
// Store the last non-zero active_id, useful for animation.
FlowiID last_active_id;
// Store the last non-zero active_id timer since the beginning of activation, useful for animation.
float last_active_id_timer;
// Active widget will want to read those nav move requests (e.g. can activate a button and move away from it)
u32 active_id_using_nav_dir_mask;
// Active widget will want to read those nav inputs.
u32 active_id_using_nav_input_mask;
// Active widget will want to read those key inputs. When we grow the ImGuiKey enum we'll need to either to order
// the enum to make useful keys come first, either redesign this into e.g. a small array.
u32 active_id_using_key_input_mask;
// Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)
FlVec2 active_id_click_offset;
// Activating with mouse or nav (gamepad/keyboard) //InputSource Source;
int active_id_mouse_button;
FlowiID active_id_previous_frame;
// Store the last non-zero active_id, useful for animation.
FlowiID active_id_last;
// Store the last non-zero active_id timer since the beginning of activation, useful for animation.
float active_id_last_Timer;
// Set at the time of activation for one frame
bool active_id_is_just_activated;
// Active widget allows another widget to steal active id (generally for overlapping widgets, but not always)
bool active_id_allow_overlap;
// Disable losing active id if the active id window gets unfocused.
bool active_id_no_clear_on_focus_loss;
// Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease
// without pressing twice). Used by range_select branch.
bool active_id_has_been_pressed_before;
// Was the value associated to the widget Edited over the course of the Active state.
bool active_id_has_been_edited_before;
bool active_id_has_been_edited_this_frame;
// Active widget will want to read mouse wheel. Blocks scrolling the underlying window.
bool active_id_using_mouse_wheel;
bool active_id_previous_frame_is_alive;
bool active_id_previous_frame_has_been_edited_before;
// ActiveId active_id;
// hash of the full context. Use for to skip rendering if nothing has changed
// XXH3_state_t context_hash;
// Previous frames hash. We can check against this to see if anything has changed
// XXH3_state_t prev_frame_hash;
FlVec2 cursor;
// id from the previous frame
u32 prev_active_item;
// current id
u32 active_item;
// TODO: Likely need block allocator here instead
vec128* positions;
// TODO: Likely need block allocator here instead
vec128* colors;
// TODO: Likely need block allocator here instead
u32* widget_ids;
struct Font* current_font;
// count of all widgets
int widget_count;
// Times with text (push button, labels, etc)
int items_with_text_count;
ItemWithText* items_with_text;
// Active fade actions
int fade_actions;
FlGlobalState* global;
// Used for building vertex / index output
VertexAllocator vertex_allocator;
LinearAllocator layout_allocator;
LayoutAreaPrivate* current_layout;
FlLayoutAreaId default_layout;
FlLayoutAreaId active_layout;
FlLayoutMode layout_mode;
LinearAllocator frame_allocator;
StringAllocator string_allocator;
struct StyleInternal* styles[FL_MAX_STYLES]; // TODO: Dynamic array instead of hard-coded max style
struct StyleInternal* style_stack[FL_STYLE_DEPTH]; // Having 128 max styles should be enough
int current_font_size;
int frame_count;
int style_count;
int layout_count;
int style_stack_depth;
int layout_ids;
} FlContext;
enum ButtonFlags {
// React on left mouse button (default)
ButtonFlags_MouseButtonLeft = 1 << 0,
// React on right mouse button
ButtonFlags_MouseButtonRight = 1 << 1,
// React on center mouse button
ButtonFlags_MouseButtonMiddle = 1 << 2,
// return true on click (mouse down event)
ButtonFlags_PressedOnClick = 1 << 4,
// [Default] return true on click + release on same item <-- this is what the majority of Button are using
ButtonFlags_PressedOnClickRelease = 1 << 5,
// return true on click + release even if the release event is not done while hovering the item
ButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6,
// return true on release (default requires click+release)
ButtonFlags_PressedOnRelease = 1 << 7,
// return true on double-click (default requires click+release)
ButtonFlags_PressedOnDoubleClick = 1 << 8,
// return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing
// headers)
ButtonFlags_PressedOnDragDropHold = 1 << 9,
// hold to repeat
ButtonFlags_Repeat = 1 << 10,
// [Internal]
ButtonFlags_MouseButtonMask =
ButtonFlags_MouseButtonLeft | ButtonFlags_MouseButtonRight | ButtonFlags_MouseButtonMiddle,
ButtonFlags_MouseButtonDefault,
};
// TODO: Use custom io functions
// TODO: Custom allocator
u8* Io_load_file_to_memory_null_term(FlContext* ctx, const char* filename, u32* out_size);
u8* Io_load_file_to_memory(FlContext* ctx, const char* filename, u32* out_size);
u8* Io_load_file_to_memory_flstring(FlContext* ctx, FlString name, u32* out_size);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: Move
FL_INLINE FlVec2 vec2_sub(FlVec2 a, FlVec2 b) {
return (FlVec2){a.x - b.x, a.y - b.y};
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FL_INLINE FlVec2 vec2_zero() {
return (FlVec2){0.0f, 0.0f};
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FL_INLINE float vec2_length_sqr(FlVec2 v) {
return (v.x * v.x) + (v.y * v.y);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FL_INLINE f32 f32_abs(f32 v) {
return v < 0.0f ? -v : v;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FL_INLINE FlVec2 vec2_floor(FlVec2 v) {
return (FlVec2){(float)(int)v.x, (float)(int)v.y};
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FL_INLINE f32 f32_max(f32 v0, f32 v1) {
return v0 > v1 ? v0 : v1;
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.deskclock.actionbarmenu;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import com.google.android.deskclock.R;
import static android.view.Menu.FIRST;
import static android.view.Menu.NONE;
/**
* {@link MenuItemController} for search menu.
*/
public final class SearchMenuItemController implements MenuItemController {
private static final String KEY_SEARCH_QUERY = "search_query";
private static final String KEY_SEARCH_MODE = "search_mode";
private static final int SEARCH_MENU_RES_ID = R.id.menu_item_search;
private final Context mContext;
private final SearchView.OnQueryTextListener mQueryListener;
private final SearchModeChangeListener mSearchModeChangeListener;
private String mQuery = "";
private boolean mSearchMode;
public SearchMenuItemController(Context context, OnQueryTextListener queryListener,
Bundle savedState) {
mContext = context;
mSearchModeChangeListener = new SearchModeChangeListener();
mQueryListener = queryListener;
if (savedState != null) {
mSearchMode = savedState.getBoolean(KEY_SEARCH_MODE, false);
mQuery = savedState.getString(KEY_SEARCH_QUERY, "");
}
}
public void saveInstance(Bundle outState) {
outState.putString(KEY_SEARCH_QUERY, mQuery);
outState.putBoolean(KEY_SEARCH_MODE, mSearchMode);
}
@Override
public int getId() {
return SEARCH_MENU_RES_ID;
}
@Override
public void onCreateOptionsItem(Menu menu) {
final SearchView searchView = new SearchView(mContext);
searchView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
searchView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
searchView.setQuery(mQuery, false);
searchView.setOnCloseListener(mSearchModeChangeListener);
searchView.setOnSearchClickListener(mSearchModeChangeListener);
searchView.setOnQueryTextListener(mQueryListener);
menu.add(NONE, SEARCH_MENU_RES_ID, FIRST, android.R.string.search_go)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
if (mSearchMode) {
searchView.requestFocus();
searchView.setIconified(false);
}
}
@Override
public void onPrepareOptionsItem(MenuItem item) {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The search view is handled by {@link #mSearchListener}. Skip handling here.
return false;
}
public String getQueryText() {
return mQuery;
}
public void setQueryText(String query) {
mQuery = query;
}
/**
* Listener for user actions on search view.
*/
private final class SearchModeChangeListener implements View.OnClickListener,
SearchView.OnCloseListener {
@Override
public void onClick(View v) {
mSearchMode = true;
}
@Override
public boolean onClose() {
mSearchMode = false;
return false;
}
}
}
|
# -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Tests for MS object.
"""
import pytest
import os
import shutil
import numpy as np
from pyuvdata import UVData
from pyuvdata.uvdata.ms import MS
from pyuvdata.data import DATA_PATH
import pyuvdata.tests as uvtest
from ..uvfits import UVFITS
pytest.importorskip("casacore")
allowed_failures = "filename"
@pytest.fixture(scope="session")
def nrao_uv_main():
uvobj = UVData()
testfile = os.path.join(DATA_PATH, "day2_TDEM0003_10s_norx_1src_1spw.ms")
uvobj.read(testfile)
yield uvobj
del uvobj
@pytest.fixture(scope="function")
def nrao_uv(nrao_uv_main):
"""Make function level NRAO ms object."""
nrao_ms = nrao_uv_main.copy()
yield nrao_ms
# clean up when done
del nrao_ms
return
@pytest.fixture(scope="session")
def mir_uv_main():
mir_uv = UVData()
testfile = os.path.join(DATA_PATH, "sma_test.mir")
mir_uv.read(testfile)
yield mir_uv
@pytest.fixture(scope="function")
def mir_uv(mir_uv_main):
"""Make a function level copy of a MIR data object"""
mir_uv = mir_uv_main.copy()
yield mir_uv
@pytest.mark.filterwarnings("ignore:ITRF coordinate frame detected,")
@pytest.mark.filterwarnings("ignore:UVW orientation appears to be flipped,")
@pytest.mark.filterwarnings("ignore:telescope_location is not set")
def test_cotter_ms():
"""Test reading in an ms made from MWA data with cotter (no dysco compression)"""
uvobj = UVData()
testfile = os.path.join(DATA_PATH, "1102865728_small.ms/")
uvobj.read(testfile)
# check that a select on read works
uvobj2 = UVData()
with uvtest.check_warnings(
UserWarning,
match=[
"Warning: select on read keyword set",
"telescope_location is not set. Using known values for MWA.",
"UVW orientation appears to be flipped,",
],
):
uvobj2.read(testfile, freq_chans=np.arange(2))
uvobj.select(freq_chans=np.arange(2))
assert uvobj == uvobj2
del uvobj
@pytest.mark.filterwarnings("ignore:ITRF coordinate frame detected,")
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
def test_read_nrao_loopback(tmp_path, nrao_uv):
"""Test reading in a CASA tutorial ms file and looping it through write_ms."""
uvobj = nrao_uv
expected_extra_keywords = ["DATA_COL", "observer"]
assert sorted(expected_extra_keywords) == sorted(uvobj.extra_keywords.keys())
testfile = os.path.join(tmp_path, "ms_testfile.ms")
uvobj.write_ms(testfile)
uvobj2 = UVData()
uvobj2.read_ms(testfile)
# also update filenames
assert uvobj.filename == ["day2_TDEM0003_10s_norx_1src_1spw.ms"]
assert uvobj2.filename == ["ms_testfile.ms"]
uvobj.filename = uvobj2.filename
# Test that the scan numbers are equal
assert (uvobj.scan_number_array == uvobj2.scan_number_array).all()
assert uvobj == uvobj2
@pytest.mark.filterwarnings("ignore:ITRF coordinate frame detected,")
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
def test_read_lwa(tmp_path):
"""Test reading in an LWA ms file."""
uvobj = UVData()
testfile = os.path.join(DATA_PATH, "lwasv_cor_58342_05_00_14.ms.tar.gz")
expected_extra_keywords = ["DATA_COL", "observer"]
import tarfile
with tarfile.open(testfile) as tf:
new_filename = os.path.join(tmp_path, tf.getnames()[0])
tf.extractall(path=tmp_path)
uvobj.read(new_filename, file_type="ms")
assert sorted(expected_extra_keywords) == sorted(uvobj.extra_keywords.keys())
assert uvobj.history == uvobj.pyuvdata_version_str
# delete the untarred folder
shutil.rmtree(new_filename)
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
@pytest.mark.filterwarnings("ignore:telescope_location is not set")
def test_no_spw():
"""Test reading in a PAPER ms converted by CASA from a uvfits with no spw axis."""
uvobj = UVData()
testfile_no_spw = os.path.join(DATA_PATH, "zen.2456865.60537.xy.uvcRREAAM.ms")
uvobj.read(testfile_no_spw)
del uvobj
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
def test_spwsupported():
"""Test reading in an ms file with multiple spws."""
uvobj = UVData()
testfile = os.path.join(DATA_PATH, "day2_TDEM0003_10s_norx_1scan.ms")
uvobj.read(testfile)
assert uvobj.Nspws == 2
@pytest.mark.filterwarnings("ignore:Coordinate reference frame not detected,")
@pytest.mark.filterwarnings("ignore:UVW orientation appears to be flipped,")
@pytest.mark.filterwarnings("ignore:telescope_location is not set")
def test_extra_pol_setup(tmp_path):
"""Test reading in an ms file with extra polarization setups (not used in data)."""
uvobj = UVData()
testfile = os.path.join(
DATA_PATH, "X5707_1spw_1scan_10chan_1time_1bl_noatm.ms.tar.gz"
)
import tarfile
with tarfile.open(testfile) as tf:
new_filename = os.path.join(tmp_path, tf.getnames()[0])
tf.extractall(path=tmp_path)
uvobj.read(new_filename, file_type="ms")
# delete the untarred folder
shutil.rmtree(new_filename)
@pytest.mark.filterwarnings("ignore:Telescope EVLA is not in known_telescopes.")
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
def test_read_ms_read_uvfits(nrao_uv, casa_uvfits):
"""
Test that a uvdata object instantiated from an ms file created with CASA's
importuvfits is equal to a uvdata object instantiated from the original
uvfits file (tests equivalence with importuvfits in uvdata up to issues around the
direction of the uvw array).
Since the history is missing from the ms file, this test sets both uvdata
histories to identical empty strings before comparing them.
"""
ms_uv = nrao_uv.copy()
uvfits_uv = casa_uvfits.copy()
# set histories to identical blank strings since we do not expect
# them to be the same anyways.
ms_uv.history = ""
uvfits_uv.history = ""
# the objects won't be equal because uvfits adds some optional parameters
# and the ms sets default antenna diameters even though the uvfits file
# doesn't have them
assert uvfits_uv != ms_uv
uvfits_uv.integration_time = ms_uv.integration_time
# they are equal if only required parameters are checked:
# scan numbers only defined for the MS
assert uvfits_uv.__eq__(ms_uv, check_extra=False, allowed_failures=allowed_failures)
# set those parameters to none to check that the rest of the objects match
ms_uv.antenna_diameters = None
for p in uvfits_uv.extra():
fits_param = getattr(uvfits_uv, p)
ms_param = getattr(ms_uv, p)
if fits_param.name in UVFITS.uvfits_required_extra and ms_param.value is None:
fits_param.value = None
setattr(uvfits_uv, p, fits_param)
# extra keywords are also different, set both to empty dicts
uvfits_uv.extra_keywords = {}
ms_uv.extra_keywords = {}
# also update filenames
assert uvfits_uv.filename == ["day2_TDEM0003_10s_norx_1src_1spw.uvfits"]
assert ms_uv.filename == ["day2_TDEM0003_10s_norx_1src_1spw.ms"]
uvfits_uv.filename = ms_uv.filename
# propagate scan numbers to the uvfits, ONLY for comparison
uvfits_uv.scan_number_array = ms_uv.scan_number_array
assert uvfits_uv == ms_uv
@pytest.mark.filterwarnings("ignore:Telescope EVLA is not in known_telescopes.")
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
def test_read_ms_write_uvfits(nrao_uv, tmp_path):
"""
read ms, write uvfits test.
Read in ms file, write out as uvfits, read back in and check for
object equality.
"""
ms_uv = nrao_uv
uvfits_uv = UVData()
testfile = os.path.join(tmp_path, "outtest.uvfits")
ms_uv.write_uvfits(testfile, spoof_nonessential=True)
uvfits_uv.read(testfile)
# make sure filenames are what we expect
assert uvfits_uv.filename == ["outtest.uvfits"]
assert ms_uv.filename == ["day2_TDEM0003_10s_norx_1src_1spw.ms"]
uvfits_uv.filename = ms_uv.filename
# propagate scan numbers to the uvfits, ONLY for comparison
uvfits_uv.scan_number_array = ms_uv.scan_number_array
assert uvfits_uv == ms_uv
del ms_uv
del uvfits_uv
@pytest.mark.filterwarnings("ignore:Telescope EVLA is not in known_telescopes.")
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
def test_read_ms_write_miriad(nrao_uv, tmp_path):
"""
read ms, write miriad test.
Read in ms file, write out as miriad, read back in and check for
object equality.
"""
pytest.importorskip("pyuvdata._miriad")
ms_uv = nrao_uv
miriad_uv = UVData()
testfile = os.path.join(tmp_path, "outtest_miriad")
ms_uv.write_miriad(testfile, clobber=True)
miriad_uv.read(testfile)
# make sure filenames are what we expect
assert miriad_uv.filename == ["outtest_miriad"]
assert ms_uv.filename == ["day2_TDEM0003_10s_norx_1src_1spw.ms"]
miriad_uv.filename = ms_uv.filename
# propagate scan numbers to the miriad uvdata, ONLY for comparison
miriad_uv.scan_number_array = ms_uv.scan_number_array
assert miriad_uv == ms_uv
@pytest.mark.filterwarnings("ignore:Telescope EVLA is not in known_telescopes.")
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
@pytest.mark.parametrize("axis", [None, "freq"])
def test_multi_files(casa_uvfits, axis):
"""
Reading multiple files at once.
"""
uv_full = casa_uvfits.copy()
# Ensure the scan numbers are defined for the comparison
uv_full._set_scan_numbers()
uv_multi = UVData()
testfile1 = os.path.join(DATA_PATH, "multi_1.ms")
testfile2 = os.path.join(DATA_PATH, "multi_2.ms")
# It seems that these two files were made using the CASA importuvfits task, but the
# history tables are missing, so we can't infer that from the history. This means
# that the uvws are not flipped/data is not conjugated as they should be. Fix that.
filesread = [testfile1, testfile2]
# test once as list and once as an array
if axis is None:
filesread = np.array(filesread)
uv_multi.read(filesread, axis=axis)
# histories are different because of combining along freq. axis
# replace the history
uv_multi.history = uv_full.history
# the objects won't be equal because uvfits adds some optional parameters
# and the ms sets default antenna diameters even though the uvfits file
# doesn't have them
assert uv_multi != uv_full
# they are equal if only required parameters are checked:
assert uv_multi.__eq__(uv_full, check_extra=False)
# set those parameters to none to check that the rest of the objects match
uv_multi.antenna_diameters = None
for p in uv_full.extra():
fits_param = getattr(uv_full, p)
ms_param = getattr(uv_multi, p)
if fits_param.name in UVFITS.uvfits_required_extra and ms_param.value is None:
fits_param.value = None
setattr(uv_full, p, fits_param)
# extra keywords are also different, set both to empty dicts
uv_full.extra_keywords = {}
uv_multi.extra_keywords = {}
# make sure filenames are what we expect
assert set(uv_multi.filename) == {"multi_1.ms", "multi_2.ms"}
assert uv_full.filename == ["day2_TDEM0003_10s_norx_1src_1spw.uvfits"]
uv_multi.filename = uv_full.filename
uv_multi._filename.form = (1,)
assert uv_multi.__eq__(uv_full, allowed_failures=allowed_failures)
del uv_full
del uv_multi
def test_bad_col_name():
"""
Test error with invalid column name.
"""
uvobj = UVData()
testfile = os.path.join(DATA_PATH, "day2_TDEM0003_10s_norx_1src_1spw.ms")
with pytest.raises(ValueError, match="Invalid data_column value supplied"):
uvobj.read_ms(testfile, data_column="FOO")
@pytest.mark.parametrize("check_warning", [True, False])
@pytest.mark.parametrize(
"frame,errtype,msg",
(
["JNAT", NotImplementedError, "Support for the JNAT frame is not yet"],
["AZEL", NotImplementedError, "Support for the AZEL frame is not yet"],
["GALACTIC", NotImplementedError, "Support for the GALACTIC frame is not yet"],
["ABC", ValueError, "The coordinate frame ABC is not one of the supported"],
["123", ValueError, "The coordinate frame 123 is not one of the supported"],
),
)
def test_parse_casa_frame_ref_errors(check_warning, frame, errtype, msg):
"""
Test errors with matching CASA frames to astropy frame/epochs
"""
uvobj = MS()
if check_warning:
with uvtest.check_warnings(UserWarning, match=msg):
uvobj._parse_casa_frame_ref(frame, raise_error=False)
else:
with pytest.raises(errtype) as cm:
uvobj._parse_casa_frame_ref(frame)
assert str(cm.value).startswith(msg)
@pytest.mark.parametrize("check_warning", [True, False])
@pytest.mark.parametrize(
"frame,epoch,msg",
(
["fk5", 1991.1, "Frame fk5 (epoch 1991.1) does not have a corresponding match"],
["fk4", 1991.1, "Frame fk4 (epoch 1991.1) does not have a corresponding match"],
["icrs", 2021.0, "Frame icrs (epoch 2021) does not have a corresponding"],
),
)
def test_parse_pyuvdata_frame_ref_errors(check_warning, frame, epoch, msg):
"""
Test errors with matching CASA frames to astropy frame/epochs
"""
uvobj = MS()
if check_warning:
with uvtest.check_warnings(UserWarning, match=msg):
uvobj._parse_pyuvdata_frame_ref(frame, epoch, raise_error=False)
else:
with pytest.raises(ValueError) as cm:
uvobj._parse_pyuvdata_frame_ref(frame, epoch)
assert str(cm.value).startswith(msg)
def test_ms_history_lesson(mir_uv, tmp_path):
"""
Test that the MS reader/writer can parse complex history
"""
from casacore import tables
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_history_lesson.ms")
mir_uv.history = (
"Line 1.\nBegin measurement set history\nAPP_PARAMS;CLI_COMMAND;"
"APPLICATION;MESSAGE;OBJECT_ID;OBSERVATION_ID;ORIGIN;PRIORITY;TIME\n"
"End measurement set history.\nLine 2.\n"
)
mir_uv.write_ms(testfile, clobber=True)
tb_hist = tables.table(testfile + "/HISTORY", readonly=False, ack=False)
tb_hist.addrows()
for col in tb_hist.colnames():
tb_hist.putcell(col, tb_hist.nrows() - 1, tb_hist.getcell(col, 0))
tb_hist.putcell("ORIGIN", 1, "DUMMY")
tb_hist.putcell("APPLICATION", 1, "DUMMY")
tb_hist.putcell("TIME", 1, 0.0)
tb_hist.putcell("MESSAGE", 2, "Line 3.")
tb_hist.close()
ms_uv.read(testfile)
assert ms_uv.history.startswith(
"Line 1.\nBegin measurement set history\nAPP_PARAMS;CLI_COMMAND;APPLICATION;"
"MESSAGE;OBJECT_ID;OBSERVATION_ID;ORIGIN;PRIORITY;TIME\n;;DUMMY;Line 2.;0;-1;"
"DUMMY;INFO;0.0\nEnd measurement set history.\nLine 3.\n Read/written with "
"pyuvdata version:"
)
tb_hist = tables.table(os.path.join(testfile, "HISTORY"), ack=False, readonly=False)
tb_hist.rename(os.path.join(testfile, "FORGOTTEN"))
tb_hist.close()
ms_uv.read(testfile)
assert ms_uv.history.startswith(" Read/written with pyuvdata version:")
def test_ms_no_ref_dir_source(mir_uv, tmp_path):
"""
Test that the MS writer/reader appropriately reads in a single-source data set
as non-multi-phase if it can be, even if the original data set was.
"""
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_no_ref_dir_source.ms")
mir_uv.phase_center_frame = "fk5"
mir_uv._set_app_coords_helper()
mir_uv.write_ms(testfile, clobber=True)
ms_uv.read(testfile)
assert ms_uv.multi_phase_center is False
ms_uv._set_multi_phase_center(preserve_phase_center_info=True)
ms_uv._update_phase_center_id("3c84", 1)
ms_uv.phase_center_catalog["3c84"]["info_source"] = "file"
assert ms_uv.phase_center_catalog == mir_uv.phase_center_catalog
def test_ms_multi_spw_data_variation(mir_uv, tmp_path):
"""
Test that the MS writer/reader appropriately reads in a single-source data set
as non-multi-phase if it can be, even if the original data set was.
"""
from casacore import tables
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_multi_spw_data_variation.ms")
mir_uv.write_ms(testfile, clobber=True)
tb_main = tables.table(testfile, readonly=False, ack=False)
tb_main.putcol("EXPOSURE", np.arange(mir_uv.Nblts * mir_uv.Nspws) + 1.0)
tb_main.close()
with pytest.raises(ValueError) as cm:
ms_uv.read_ms(testfile)
assert str(cm.value).startswith("Column EXPOSURE appears to vary on between")
with uvtest.check_warnings(
UserWarning, match="Column EXPOSURE appears to vary on between windows, ",
):
ms_uv.read_ms(testfile, raise_error=False)
# Check that the values do indeed match the first entry in the catalog
assert np.all(ms_uv.integration_time == np.array([1.0]))
@pytest.mark.filterwarnings("ignore:The uvw_array does not match the expected values")
def test_ms_phasing(mir_uv, tmp_path):
"""
Test that the MS writer can appropriately handle unphased data sets.
"""
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_phasing.ms")
mir_uv.unphase_to_drift()
with pytest.raises(ValueError) as cm:
mir_uv.write_ms(testfile, clobber=True)
assert str(cm.value).startswith("The data are in drift mode.")
mir_uv.write_ms(testfile, clobber=True, force_phase=True)
ms_uv.read(testfile)
assert np.allclose(ms_uv.phase_center_app_ra, ms_uv.lst_array)
assert np.allclose(
ms_uv.phase_center_app_dec, ms_uv.telescope_location_lat_lon_alt[0]
)
def test_ms_single_chan(mir_uv, tmp_path):
"""
Make sure that single channel writing/reading work as expected
"""
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_single_chan.ms")
mir_uv.select(freq_chans=0)
mir_uv.write_ms(testfile, clobber=True)
mir_uv.set_lsts_from_time_array()
mir_uv._set_app_coords_helper()
with pytest.raises(ValueError) as cm:
ms_uv.read_ms(testfile)
assert str(cm.value).startswith("No valid data available in the MS file.")
ms_uv.read_ms(testfile, ignore_single_chan=False, read_weights=False)
# Easiest way to check that everything worked is to just check for equality, but
# the MS file is single-spw, single-field, so we have a few things we need to fix
# First, make the date multi-phase-ctr
ms_uv._set_multi_phase_center(preserve_phase_center_info=True)
ms_uv._update_phase_center_id("3c84", 1)
# Next, turn on flex-spw
ms_uv._set_flex_spw()
ms_uv.channel_width = np.array([ms_uv.channel_width])
ms_uv.flex_spw_id_array = ms_uv.spw_array.copy()
# Finally, take care of the odds and ends
ms_uv.extra_keywords = {}
ms_uv.history = mir_uv.history
ms_uv.filename = mir_uv.filename
ms_uv.instrument = mir_uv.instrument
ms_uv.reorder_blts()
# propagate scan numbers to the uvfits, ONLY for comparison
mir_uv.scan_number_array = ms_uv.scan_number_array
assert ms_uv == mir_uv
def test_ms_scannumber_multiphasecenter(tmp_path):
"""
Make sure that single channel writing/reading work as expected
"""
carma_file = os.path.join(DATA_PATH, "carma_miriad")
testfile = os.path.join(tmp_path, "carma_out.ms")
miriad_uv = UVData()
# Copied in from test_miriad.py::test_read_carma_miriad_write_ms
with uvtest.check_warnings(
UserWarning,
[
"Altitude is not present in Miriad file, "
"using known location values for SZA.",
"The uvw_array does not match the expected values given the antenna "
"positions.",
"pamatten in extra_keywords is a list, array or dict",
"psys in extra_keywords is a list, array or dict",
"psysattn in extra_keywords is a list, array or dict",
"ambpsys in extra_keywords is a list, array or dict",
"bfmask in extra_keywords is a list, array or dict",
"Cannot fix the phases of multi phase center datasets, as they were not "
"supported when the old phasing method was used, and thus, there "
"is no need to correct the data.",
],
):
miriad_uv.read(carma_file, fix_old_proj=True)
# MIRIAD is missing these in the file, so we'll fill it in here.
miriad_uv.antenna_diameters = np.zeros(miriad_uv.Nants_telescope)
miriad_uv.antenna_diameters[:6] = 10.0
miriad_uv.antenna_diameters[15:] = 3.5
# We need to recalculate app coords here for one source ("NOISE"), which was
# not actually correctly calculated in the online CARMA system (long story). Since
# the MS format requires recalculating apparent coords after read in, we'll
# calculate them here just to verify that everything matches.
miriad_uv._set_app_coords_helper()
miriad_uv.write_ms(testfile, clobber=True)
# Check on the scan number grouping based on consecutive integrations per phase
# center
# Double-check multi-phase center is True.
assert miriad_uv.multi_phase_center
# Read back in as MS. Should have 3 scan numbers defined.
ms_uv = UVData()
ms_uv.read(testfile)
assert np.unique(ms_uv.scan_number_array).size == 3
assert (np.unique(ms_uv.scan_number_array) == np.array([1, 2, 3])).all()
# The scan numbers should match the phase center IDs, offset by 1
# so that the scan numbers start with 1, not 0.
assert ((miriad_uv.phase_center_id_array == (ms_uv.scan_number_array - 1))).all()
def test_ms_extra_data_descrip(mir_uv, tmp_path):
"""
Make sure that data sets can be read even if the main table doesn't have data
for a particular listed spectral window in the DATA_DESCRIPTION table.
"""
from casacore import tables
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_extra_data_descrip.ms")
mir_uv.write_ms(testfile, clobber=True)
tb_dd = tables.table(
os.path.join(testfile, "DATA_DESCRIPTION"), ack=False, readonly=False
)
tb_dd.addrows()
for col in tb_dd.colnames():
tb_dd.putcell(col, tb_dd.nrows() - 1, tb_dd.getcell(col, 0))
tb_dd.close()
ms_uv.read_ms(testfile, ignore_single_chan=False, read_weights=False)
# There are some minor differences between the values stored by MIR and that
# calculated by UVData. Since MS format requires these to be calculated on the fly,
# we calculate them here just to verify that everything is looking okay.
mir_uv.set_lsts_from_time_array()
mir_uv._set_app_coords_helper()
# These reorderings just make sure that data from the two formats are lined up
# correctly.
mir_uv.reorder_freqs(spw_order="number")
ms_uv.reorder_blts()
# Fix the remaining differences between the two objects, all of which are expected
mir_uv.instrument = mir_uv.telescope_name
ms_uv.history = mir_uv.history
mir_uv.extra_keywords = ms_uv.extra_keywords
mir_uv.filename = ms_uv.filename = None
# propagate scan numbers to the miriad uvdata, ONLY for comparison
mir_uv.scan_number_array = ms_uv.scan_number_array
# Finally, with all exceptions handled, check for equality.
assert ms_uv == mir_uv
def test_ms_weights(mir_uv, tmp_path):
"""
Test that the MS writer/reader appropriately handles data when the
WEIGHT_SPECTRUM column is missing or bypassed.
"""
from casacore import tables
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_weights.ms")
mir_uv.nsample_array[0, 0, :, 0] = np.tile(
np.arange(mir_uv.Nfreqs / mir_uv.Nspws), mir_uv.Nspws,
)
mir_uv.write_ms(testfile, clobber=True)
tb_main = tables.table(testfile, readonly=False, ack=False)
tb_main.removecols("WEIGHT_SPECTRUM")
tb_main.close()
ms_uv.read_ms(testfile)
# Check that the values do indeed match expected (median) value
assert np.all(ms_uv.nsample_array == np.median(mir_uv.nsample_array))
ms_uv.read_ms(testfile, read_weights=False)
# Check that the values do indeed match expected (median) value
assert np.all(ms_uv.nsample_array == 1.0)
@pytest.mark.parametrize(
"badcol,badval,errtype,msg",
(
[None, None, IOError, "Thisisnofile.ms not found"],
["DATA_DESC_ID", [1000] * 8, ValueError, "No valid data available in the MS"],
["ARRAY_ID", np.arange(8), ValueError, "This file appears to have multiple"],
["DATA_COL", None, ValueError, "Invalid data_column value supplied."],
["TEL_LOC", None, ValueError, "Telescope frame is not ITRF and telescope is"],
),
)
def test_ms_reader_errs(mir_uv, tmp_path, badcol, badval, errtype, msg):
"""
Test whether the reader throws an appripropriate errors on read.
"""
from casacore import tables
ms_uv = UVData()
testfile = os.path.join(tmp_path, "out_ms_reader_errs.ms")
mir_uv.write_ms(testfile, clobber=True)
data_col = "DATA"
if badcol is None:
testfile = "Thisisnofile.ms"
elif badcol == "DATA_COL":
data_col = badval
elif badcol == "TEL_LOC":
tb_obs = tables.table(
os.path.join(testfile, "OBSERVATION"), ack=False, readonly=False
)
tb_obs.removecols("TELESCOPE_LOCATION")
tb_obs.putcol("TELESCOPE_NAME", "ABC")
tb_obs.close()
tb_ant = tables.table(
os.path.join(testfile, "ANTENNA"), ack=False, readonly=False
)
tb_ant.putcolkeyword("POSITION", "MEASINFO", {"type": "position", "Ref": "ABC"})
tb_ant.close()
else:
tb_main = tables.table(testfile, ack=False, readonly=False)
tb_main.putcol(badcol, badval)
tb_main.close()
with pytest.raises(errtype) as cm:
ms_uv.read_ms(testfile, data_column=data_col)
assert str(cm.value).startswith(msg)
def test_antenna_diameter_handling(hera_uvh5, tmp_path):
uv_obj = hera_uvh5
uv_obj.antenna_diameters = np.asarray(uv_obj.antenna_diameters, dtype=">f4")
test_file = os.path.join(tmp_path, "dish_diameter_out.ms")
uv_obj.write_ms(test_file, force_phase=True)
uv_obj2 = UVData.from_file(test_file)
# MS write/read adds some stuff to history & extra keywords
uv_obj2.history = uv_obj.history
uv_obj2.extra_keywords = uv_obj.extra_keywords
# Uh oh, we're losing x_orientation in the ms write/read round trip.
# That's a problem. Documented in issue #1083.
assert uv_obj.x_orientation is not None
assert uv_obj2.x_orientation is None
uv_obj2.x_orientation = uv_obj.x_orientation
assert uv_obj2.__eq__(uv_obj, allowed_failures=allowed_failures)
|
<filename>M7-Algorithms/01-swap-case/Unsolved/swap-case.js
// Write code to create a function takes a string and returns the string with all of the letter cases swapped
var swapCase = function(str) {
// turn string into array of letters
var newArr = str.split("")
// console.log(newArr)
// for loop to change each character to opposite letter case
for (var i = 0; i < newArr.length; i ++) {
var compare = newArr[i]
var small = compare.toLowerCase()
var big = compare.toUpperCase()
if (newArr[i] === big) {
newArr[i] = newArr[i].toLowerCase()
// console.log(newArr[i])
}
else if (newArr[i] === small) {
// console.log("upperCase")
newArr[i] = newArr[i].toUpperCase()
// console.log(newArr[i])
}
}
console.log(newArr)
return newArr.join("")
};
// commands & notes
// to change a portion of an array, set it to equal(=) to something
// .split() - splits strings into array
// .join - join array into a string
|
#!/usr/heirloom/bin/sh
cd "`dirname "$0"`" || exit 1
_bashaspec_test_file="`pwd`/`basename "$0"`"
before_all() {
echo 'inside before_all'
false
}
after_all() {
echo 'inside after_all'
true
}
before_each() {
echo 'inside before_each'
true
}
after_each() {
echo 'inside after_each'
true
}
test_1() {
echo 'inside test_1'
true
}
test_2() {
echo 'inside test_2'
true
}
test_3() {
echo 'inside test_3'
true
}
. ../alternate-old-versions/bashaspec-ancient.sh
|
<filename>dailymotion-sdk-api/src/main/java/fr/zebasto/dailymotion/sdk/api/dto/Video.java
package fr.zebasto.dailymotion.sdk.api.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import fr.zebasto.dailymotion.sdk.api.Entity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.security.Timestamp;
import java.util.Date;
import java.util.List;
/**
* Created by Bastien on 04/01/2014.
*/
public class Video implements Entity {
/**
* A boolean indicating that the video is in 3D format (true) or not (false).
* No access_token required for reading.
* Returns boolean.
*/
@JsonProperty(value = "3D")
private boolean threeD;
/**
* An error message explaining why the access to the video can’t be granted.
* No access_token required for reading.
* Returns dict, min size: 1, max size: 150.
*/
@JsonProperty(value = "access_error")
private String accessError;
/**
* Defines is video accepts associated ads
* No access_token required for reading.
* Returns boolean.
*/
private boolean ads;
/**
* If true, allows comments to be posted on this video.
* No access_token required for reading. This field is writable.
* Returns boolean.
*/
@JsonProperty(value = "allow_comments")
private boolean allowComments;
/**
* Tell if the video can be embeded outside of Dailymotion
* No access_token required for reading.
* Returns boolean.
*/
@JsonProperty(value = "allow_embed")
private boolean allowEmbed;
/**
* is it possible to add this video to groups
* No access_token required for reading. This field is writable.
* Returns boolean.
*/
@JsonProperty(value = "allowed_in_groups")
private boolean allowedInGroups;
/**
* is it possible to add this video to playlists
* No access_token required for reading. This field is writable.
* Returns boolean.
*/
@JsonProperty(value = "allowed_in_playlists")
private boolean allowedInPlaylists;
/**
* The aspect ratio of the video frame (i.e.: 1.33333 for 4/3, 1.77777 for 16/9...).
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "aspect_ratio")
private double aspectRatio;
/**
* The current audience for a live event from the audience meter. Null if audience shouldn’t be accounted.
* No access_token required for reading.
* Returns number, min value: 0.
*/
private int audience;
/**
* The video available formats
* No access_token required for reading.
* Returns array, min size: 1, max size: 150.
*/
@JsonProperty(value = "available_formats")
private List<Double> availableFormats;
/**
* The total number of times a video has been added to users’ favorites.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "bookmarks_total")
private int bookmarksTotal;
/**
* True if the live is privately available.
* No access_token required for reading. This field is writable.
* Returns boolean.
*/
private boolean broadcasting;
/**
* The short channel name of the video.
* This field can be used as filter. No access_token required for reading. This field is writable.
* Return a channel. You can request sub-fields by using channel.<sub-field> notation.
*/
@JsonProperty(value = "channel.*")
private Channel channel;
/**
* The total number of comments on the video.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "comments_total")
private int commentsTotal;
/**
* The country of the video (declarative, may be null).
* This field can be used as filter. No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
private String country;
/**
* Limit the result set to videos created after a specific timestamp
* This field can be used as filter but can’t be read nor written.
* Returns date.
*/
@JsonProperty(value = "created_after")
private Timestamp createdAfter;
/**
* Limit the result set to videos created before a specific timestamp
* This field can be used as filter but can’t be read nor written.
* Returns date.
*/
@JsonProperty(value = "created_before")
private Timestamp createdBefore;
/**
* The date the video was uploaded to the site.
* No access_token required for reading.
* Returns date.
*/
@JsonProperty(value = "created_time")
private Date createdTime;
/**
* The description of the video.
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 2000.
*/
private String description;
/**
* The duration of the video in seconds.
* No access_token required for reading.
* Returns number, min value: 0.
*/
private int duration;
/**
* The HTML embed code.
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "embed_html")
private String embedHtml;
/**
* The URL to embed the video.
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "embed_url")
private String embedUrl;
/**
* When the video status is processing, this parameter indicates a number between 0 and 100 corresponding to the percentage of encoding already completed. For other statuses this parameter is -1.
* No access_token required for reading.
* Returns number, min value: -1, max value: 100.
*/
@JsonProperty(value = "encoding_progress")
private int encodingProgress;
/**
* the end date of the stream
* No access_token required for reading. This field is writable.
* Returns date.
*/
@JsonProperty(value = "end_time")
private Date endTime;
/**
* The name of pushd event sent on video deletion
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "event_delete")
private String eventDelete;
/**
* The name of pushd event sent on video deletion
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "event_live_offair")
private String eventLiveOffair;
/**
* The name of pushd event sent on video modification
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "event_live_onair")
private String eventLiveOnair;
/**
* The name of pushd event sent on video modification
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "event_modify")
private String eventModify;
/**
* True if the video is explicit.
* No access_token required for reading. This field is writable.
* Returns boolean.
*/
private boolean explicit;
/**
* returns sprite url of snapshot of the video if it exists
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "filmstrip_small_url")
private String filmstripSmallUrl;
/**
* A list of filters available to reduce the result set.
* This field can be used as filter but can’t be read nor written.
* Returns array, allowed values: featured, hd, official, creative, creative-official, ugc, buzz, buzz-premium, 3d, live, all-live, live-upcoming, no-live, premium, premium-paidvideos, premium-offers, no-premium, quicklist, history, with-poster, without-poster, what-to-watch.
*/
private String filters;
/**
* genre extended data
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
private String genre;
/**
* A list of countries where the video is or isn’t accessible. The list of countries start with the “deny” or “allow” keyword to define if this is a black or a whitelist. Examples: [“fr”, “us”, “it”] or [“allow”, “fr”, “us”, “it”] will both allow the video to be accessed in France, US and Italy and deny all other countries. [“deny”, “us”] will deny the access to the video from the US and allow it everywhere else. An empty list or [“allow”] (the default) will allow it from everywhere.
* No access_token required for reading.
* Returns array, min size: 1, max size: 150.
*/
private List<String> geoblocking;
/**
* Geolocalization for the video. Result is an array with the longitude and latitude using point notation. Longitude range is from -180.0 (West) to 180.0 (East). Latitude range is from -90.0 (South) to 90.0 (North). Example: [-122.4006, 37.7821]
* No access_token required for reading. This field is writable.
* Returns array, min size: 1, max size: 150.
*/
private List<Double> geoloc;
/**
* The video object ID
* No access_token required for reading.
* Returns the object id.
*/
private String id;
/**
* Limit the result to a specified list of video ids.
* This field can be used as filter but can’t be read nor written.
* Returns array, min size: 1, max size: 150.
*/
private String ids;
/**
* The detected ISRC (International Standard Recording Code) of the soundtrack
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
private String isrc;
/**
* The language of the video (declarative).
* This field can be used as filter. No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
private String language;
/**
* True if the user can launch an ads break for this live stream
* manage_videos scope required for reading. manage_videos scope required for writing.
* Returns boolean.
*/
@JsonProperty(value = "live_ad_break")
private boolean liveAdBreak;
/**
* The URL to publish fragmented live stream on (current logged user need to own the video in order to retrieve this field)
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "live_frag_publish_url")
private String liveFragPublishUrl;
/**
* The URL to publish live source stream on (current logged user need to own the video in order to retrieve this field)
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "live_publish_url")
private String livePublishUrl;
/**
* The list of blocking rules per country and device to be applied on the video. Each rule has the following format : country/[country code]/media/[media id] Available country codes are : ar, at, br, ca, ch, cn, de, dk, es, fr, gb, gr, ie, in, it, js, jp, kr, mx, nl, pl, pr, pt, ro, ru, se, tr, us, other. Available medias id are : iptv, mobile, tvhz, web, other.
* No access_token required for reading.
* Returns array, min size: 1, max size: 150.
*/
private List<String> mediablocking;
/**
* actors playing in the movie
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_credit_actors")
private String metadataCreditActors;
/**
* director of the movie
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_credit_director")
private String metadataCreditDirector;
/**
* Genre of the video
* No access_token required for reading. This field is writable.
* Returns string, allowed values: drama, comedy, realitytelevision, animation, documentary, sitcom, gameshow, sciencefiction, talkshow, fantasy, action, anime, adventure, soapopera, miniseries, news, crimefiction, romance, sports, variety, thriller, music.
*/
@JsonProperty(value = "metadata_genre")
private String metadataGenre;
/**
* Original language (ISO 3166) of the video
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_original_language")
private String metadataOriginalLanguage;
/**
* Original title of the video
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_original_title")
private String metadataOriginalTitle;
/**
* Date (RFC 822) of release or production
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_released")
private String metadataReleased;
/**
* e
* show episode number/name
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_show_episod")
private String metadataShowEpisod;
/**
* show season number/name
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_show_season")
private String metadataShowSeason;
/**
* Visa number
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "metadata_visa")
private String metadataVisa;
/**
* The stream mode, can be vod, simulcast or live.
* No access_token required for reading. This field is writable.
* Returns string, allowed values: vod, simulcast, live.
*/
private String mode;
/**
* True if the live is moderated.
* No access_token required for reading.
* Returns boolean.
*/
private boolean moderated;
/**
* Limit the result set to videos modified after a specific timestamp
* This field can be used as filter but can’t be read nor written.
* Returns date.
*/
@JsonProperty(value = "modified_after")
private Timestamp modifiedAfter;
/**
* Limit the result set to videos modified before a specific timestamp
* This field can be used as filter but can’t be read nor written.
* Returns date.
*/
@JsonProperty(value = "modified_before")
private Timestamp modifiedBefore;
/**
* The date the video was last modified.
* No access_token required for reading.
* Returns date.
*/
@JsonProperty(value = "modified_time")
private Timestamp modifiedTime;
/**
* The detected MUYAP (Turkish Phonographic Industry Society Identifier) of the soundtrack
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
private String muyap;
/**
* True if the video is in mode live and currently airing.
* No access_token required for reading.
* Returns boolean.
*/
private boolean onair;
/**
* The id of the owner of the video (use owner.screenname to show the user name).
* This field can be used as filter. No access_token required for reading.
* Return a user. You can request sub-fields by using owner.<sub-field> notation.
*/
@JsonProperty(value = "owner.*")
private User owner;
/**
* True is the access to the video is subject to conditions
* No access_token required for reading.
* Returns boolean.
*/
private boolean paywall;
/**
* True if the video has a poster
* No access_token required for reading.
* Returns boolean.
*/
private boolean poster;
/**
* The URL of the video poster (135x180).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "poster_135x180_url")
private String poster135x180Url;
/**
* The URL of the video poster (180x240).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "poster_180x240_url")
private String poster180x240Url;
/**
* The URL of the video poster (270x360).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "poster_270x360_url")
private String poster270x360Url;
/**
* The URL of the video poster (360x480).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "poster_360x480_url")
private String poster360x480Url;
/**
* The URL of the video poster (45x60).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "poster_45x60_url")
private String poster45x60Url;
/**
* The URL of the video poster (95x120).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "poster_90x120_url")
private String poster90x120Url;
/**
* The URL of the video poster (540x720).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "poster_url")
private String posterUrl;
/**
* The price and duration for a tvod or svod video
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "price_details")
private String priceDetails;
/**
* True if the video is private.
* This field can be used as filter. No access_token required for reading. This field is writable.
* Returns boolean.
*/
@JsonProperty(value = "private")
private boolean pRivate;
/**
* True if the video is published (may still wait for encoding, see status field for more info).
* No access_token required for reading. This field is writable.
* Returns boolean.
*/
private boolean published;
/**
* The average number of stars the video has (float between 0 and 5).
* No access_token required for reading.
* Returns number, min value: 0, max value: 5.
*/
private float rating;
/**
* The number of users who voted for the video.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "ratings_total")
private int ratingsTotal;
/**
* The recurrence of the stream
* No access_token required for reading.
* Returns string, allowed values: once, daily, weekly.
*/
private String recurrence;
/**
* The standard rental duration of the video in hours. Will be null if the video is not behind a paywall
* No access_token required for reading. This field is writable.
* Returns string, allowed values: 3, 24, 48.
*/
@JsonProperty(value = "rental_duration")
private int rentalDuration;
/**
* The price as float in the current currency. Will be null if the video is not behind a paywall. See currency field of the /locale endpoint to get the current currency.
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "rental_price")
private float rentalPrice;
/**
* The price, formatted with currency according to the request localization. Will be null if the video is not behind a paywall
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
@JsonProperty(value = "rental_price_formatted")
private String rentalPriceFormatted;
/**
* Timelapse of video free preview, in seconds
* No access_token required for reading. This field is writable.
* Returns number, min value: 0.
*/
@JsonProperty(value = "rental_start_time")
private int rentalStartTime;
/**
* Full text search for videos
* This field can be used as filter but can’t be read nor written.
* Returns string, min size: 1, max size: 150.
*/
private String search;
/**
* urls to share content in social networks
* No access_token required for reading.
* Returns dict, min size: 1, max size: 150.
*/
@JsonProperty(value = "sharing_urls")
private String sharingUrls;
/**
* Change result ordering
* This field can be used as filter but can’t be read nor written.
* Returns string, allowed values: recent, visited, visited-hour, visited-today, visited-week, visited-month, commented, commented-hour, commented-today, commented-week, commented-month, rated, rated-hour, rated-today, rated-week, rated-month, relevance, random, ranking.
*/
private String sort;
/**
* Get available information about the soundtrack
* No access_token required for reading.
* Returns dict, min size: 1, max size: 150.
*/
@JsonProperty(value = "soundtrack_info")
private String soundtrackInfo;
/**
* The started time of the stream
* No access_token required for reading. This field is writable.
* Returns date.
*/
@JsonProperty(value = "start_time")
private Date startTime;
/**
* The state of the video. A video requires the published status to be watchable.
* No access_token required for reading.
* Returns string, allowed values: waiting, processing, ready, published, rejected, deleted, encoding_error.
*/
private String status;
/**
* The URL of the full HD format (1080p, 3Mbps).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_h264_hd1080_url")
private String streamH264Hd1080Url;
/**
* The URL of the high definition video (720p, 1.6Mbps).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_h264_hd_url")
private String streamH264HdUrl;
/**
* The URL of the high quality video (480p, 975kbps).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_h264_hq_url")
private String streamH264HqUrl;
/**
* The URL of the very low definition, low bandwidth video stream (144p, 60kbps).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_h264_l1_url")
private String streamH264L1Url;
/**
* The URL of the very low definition, higher bandwidth video stream (144p, 105kbps).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_h264_l2_url")
private String streamH264L2Url;
/**
* The URL of the low definition video stream (240p, 255kbps).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_h264_ld_url")
private String streamH264LdUrl;
/**
* The URL of the medium quality video (380p, 520kbps).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_h264_url")
private String streamH264Url;
/**
* The URL of the adaptative bitrate manifest using Apple HTTP Live Streaming protocol.
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_hls_url")
private String streamHlsUrl;
/**
* The URL of the live using HTTP Dynamic Streaming protocol.
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_live_hds_url")
private String streamLiveHdsUrl;
/**
* The URL of the live using HTTP Live Streaming protocol.
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_live_hls_url")
private String streamLiveHlsUrl;
/**
* The URL of the live using RTMP protocol.
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_live_rtmp_url")
private String streamLiveRtmpUrl;
/**
* The URL of the free preview of premium content
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_premium_preview_hls_url")
private String streamPremiumPreviewHlsUrl;
/**
* The URL of the free preview of premium content
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_premium_preview_mp4_url")
private String streamPremiumPreviewMp4Url;
/**
* The URL of the free preview of premium content
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_premium_preview_web_url")
private String streamPremiumPreviewWebUrl;
/**
* The URL of the video source
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "stream_source_url")
private String streamSourceUrl;
/**
* The list of strong tags for the video.
* This field can be used as filter. No access_token required for reading.
* Returns array, min size: 1, max size: 150.
*/
private List<Strongtag> strongtags;
/**
* True if the video is behind svod paywall
* No access_token required for reading.
* Returns boolean.
*/
private boolean svod;
/**
* The URL of the legacy SWF embed player (use this only to embed player into a flash movie, otherwise use ``embedUrl)
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "swf_url")
private String swfUrl;
/**
* syncAllowed
* No access_token required for reading.
* Returns boolean.
*/
@JsonProperty(value = "sync_allowed")
private boolean syncAllowed;
/**
* The list of tags for the video.
* This field can be used as filter. No access_token required for reading. This field is writable.
* Returns array, min size: 1, max size: 150.
*/
private List<String> tags;
/**
* The date the video was taken (declarative).
* No access_token required for reading. This field is writable.
* Returns date.
*/
@JsonProperty(value = "taken_time")
private Date takenTime;
/**
* The URL of the video thumbnail (120px height).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "thumbnail_120_url")
private String thumbnail120Url;
/**
* The URL of the video thumbnail (180px height).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "thumbnail_180_url")
private String thumbnail180Url;
/**
* The URL of the video thumbnail (240px height).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "thumbnail_240_url")
private String thumbnail240Url;
/**
* The URL of the video thumbnail (360px height).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "thumbnail_360_url")
private String thumbnail360Url;
/**
* The URL of the video thumbnail (480px height).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "thumbnail_480_url")
private String thumbnail480Url;
/**
* The URL of the video thumbnail (60px height).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "thumbnail_60_url")
private String thumbnail60Url;
/**
* The URL of the video thumbnail (720px height).
* No access_token required for reading.
* Returns url.
*/
@JsonProperty(value = "thumbnail_720_url")
private String thumbnail720Url;
/**
* The URL of the video raw thumbnail (full size respecting ratio). Some users have the right to change this value by providing an URL to a custom thumbnail. To extract the preview from a live stream, use extract: live
* No access_token required for reading. This field is writable.
* Returns url.
*/
@JsonProperty(value = "thumbnail_url")
private String thumbnailUrl;
/**
* The title of the video.
* No access_token required for reading. This field is writable.
* Returns string, min size: 1, max size: 255.
*/
private String title;
/**
* True if the video is begind tvod paywall
* No access_token required for reading.
* Returns boolean.
*/
private boolean tvod;
/**
* The content type of the video (can be official, creative or null).
* No access_token required for reading. This field is writable.
* Returns string, allowed values: ugc, creative, official.
*/
private String type;
/**
* The detected UPC (Universal Product Code) of the soundtrack
* No access_token required for reading.
* Returns string, min size: 1, max size: 150.
*/
private String upc;
/**
* The URL of the video on Dailymotion site. Writing this parameter defines where to download the video source. You may either use this parameter at video creation time or change this parameter later if you want to change the source video afterward. To change an existing video, the authenticated user may need some additional rights like motionmaker right. When replacing an existing source, the video will put offline for some minute during the re-encoding. You may use the GET /file/upload API ressource to upload a video file and create a URL to provide to this method or use an existing URL pointing to a video file. Writing to this parameter is subject to rate limiting.
* No access_token required for reading. This field is writable.
* Returns url.
*/
private String url;
/**
* The number of views in the last 24 sliding hours.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "views_last_day")
private int viewsLastDay;
/**
* The number of views in the last sliding hour.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "views_last_hour")
private int viewsLastHour;
/**
* The number of views in the last 30 sliding days.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "views_last_month")
private int viewsLastMonth;
/**
* The number of views in the last 7 sliding days.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "views_last_week")
private int viewsLastWeek;
/**
* The number of views on the video since its privateation.
* No access_token required for reading.
* Returns number, min value: 0.
*/
@JsonProperty(value = "views_total")
private int viewsTotal;
/**
* Returns the threeD
*
* @return the threeD
*/
public boolean isThreeD() {
return threeD;
}
/**
* Set the ThreeD
*
* @param threeD the ThreeD to set
*/
public void setThreeD(boolean threeD) {
this.threeD = threeD;
}
/**
* Returns the Access_error
*
* @return the Access_error
*/
public String getAccessError() {
return accessError;
}
/**
* Set the Access_error
*
* @param accessError the Access_error to set
*/
public void setAccessError(String accessError) {
this.accessError = accessError;
}
/**
* Returns the ads
*
* @return the ads
*/
public boolean isAds() {
return ads;
}
/**
* Set the Ads
*
* @param ads the Ads to set
*/
public void setAds(boolean ads) {
this.ads = ads;
}
/**
* Returns the allowComments
*
* @return the allowComments
*/
public boolean isAllowComments() {
return allowComments;
}
/**
* Set the Allow_comments
*
* @param allowComments the Allow_comments to set
*/
public void setAllowComments(boolean allowComments) {
this.allowComments = allowComments;
}
/**
* Returns the allowEmbed
*
* @return the allowEmbed
*/
public boolean isAllowEmbed() {
return allowEmbed;
}
/**
* Set the Allow_embed
*
* @param allowEmbed the Allow_embed to set
*/
public void setAllowEmbed(boolean allowEmbed) {
this.allowEmbed = allowEmbed;
}
/**
* Returns the allowedInGroups
*
* @return the allowedInGroups
*/
public boolean isAllowedInGroups() {
return allowedInGroups;
}
/**
* Set the Allowed_in_groups
*
* @param allowedInGroups the Allowed_in_groups to set
*/
public void setAllowedInGroups(boolean allowedInGroups) {
this.allowedInGroups = allowedInGroups;
}
/**
* Returns the allowedInPlaylists
*
* @return the allowedInPlaylists
*/
public boolean isAllowedInPlaylists() {
return allowedInPlaylists;
}
/**
* Set the Allowed_in_playlists
*
* @param allowedInPlaylists the Allowed_in_playlists to set
*/
public void setAllowedInPlaylists(boolean allowedInPlaylists) {
this.allowedInPlaylists = allowedInPlaylists;
}
/**
* Returns the Aspect_ratio
*
* @return the Aspect_ratio
*/
public double getAspectRatio() {
return aspectRatio;
}
/**
* Set the Aspect_ratio
*
* @param aspectRatio the Aspect_ratio to set
*/
public void setAspectRatio(double aspectRatio) {
this.aspectRatio = aspectRatio;
}
/**
* Returns the Audience
*
* @return the Audience
*/
public int getAudience() {
return audience;
}
/**
* Set the Audience
*
* @param audience the Audience to set
*/
public void setAudience(int audience) {
this.audience = audience;
}
/**
* Returns the Available_formats
*
* @return the Available_formats
*/
public List<Double> getAvailableFormats() {
return availableFormats;
}
/**
* Set the Available_formats
*
* @param availableFormats the Available_formats to set
*/
public void setAvailableFormats(List<Double> availableFormats) {
this.availableFormats = availableFormats;
}
/**
* Returns the Bookmarks_total
*
* @return the Bookmarks_total
*/
public int getBookmarksTotal() {
return bookmarksTotal;
}
/**
* Set the Bookmarks_total
*
* @param bookmarksTotal the Bookmarks_total to set
*/
public void setBookmarksTotal(int bookmarksTotal) {
this.bookmarksTotal = bookmarksTotal;
}
public boolean isBroadcasting() {
return broadcasting;
}
/**
* Set the Broadcasting
*
* @param broadcasting the Broadcasting to set
*/
public void setBroadcasting(boolean broadcasting) {
this.broadcasting = broadcasting;
}
/**
* Returns the Channel
*
* @return the Channel
*/
public Channel getChannel() {
return channel;
}
/**
* Set the Channel
*
* @param channel the Channel to set
*/
public void setChannel(Channel channel) {
this.channel = channel;
}
/**
* Returns the Comments_total
*
* @return the Comments_total
*/
public int getCommentsTotal() {
return commentsTotal;
}
/**
* Set the Comments_total
*
* @param commentsTotal the Comments_total to set
*/
public void setCommentsTotal(int commentsTotal) {
this.commentsTotal = commentsTotal;
}
/**
* Returns the Country
*
* @return the Country
*/
public String getCountry() {
return country;
}
/**
* Set the Country
*
* @param country the Country to set
*/
public void setCountry(String country) {
this.country = country;
}
/**
* Returns the Created_after
*
* @return the Created_after
*/
public Timestamp getCreatedAfter() {
return createdAfter;
}
/**
* Set the Created_after
*
* @param createdAfter the Created_after to set
*/
public void setCreatedAfter(Timestamp createdAfter) {
this.createdAfter = createdAfter;
}
/**
* Returns the Created_before
*
* @return the Created_before
*/
public Timestamp getCreatedBefore() {
return createdBefore;
}
/**
* Set the Created_before
*
* @param createdBefore the Created_before to set
*/
public void setCreatedBefore(Timestamp createdBefore) {
this.createdBefore = createdBefore;
}
/**
* Returns the Created_time
*
* @return the Created_time
*/
public Date getCreatedTime() {
return this.createdTime != null ? new Date(this.createdTime.getTime()) : null;
}
/**
* Set the Created_time
*
* @param createdTime the Created_time to set
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime != null ? new Date(createdTime.getTime()) : null;
}
/**
* Returns the Description
*
* @return the Description
*/
public String getDescription() {
return description;
}
/**
* Set the Description
*
* @param description the Description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Returns the Duration
*
* @return the Duration
*/
public int getDuration() {
return duration;
}
/**
* Set the Duration
*
* @param duration the Duration to set
*/
public void setDuration(int duration) {
this.duration = duration;
}
/**
* Returns the Embed_html
*
* @return the Embed_html
*/
public String getEmbedHtml() {
return embedHtml;
}
/**
* Set the Embed_html
*
* @param embedHtml the Embed_html to set
*/
public void setEmbedHtml(String embedHtml) {
this.embedHtml = embedHtml;
}
/**
* Returns the Embed_url
*
* @return the Embed_url
*/
public String getEmbedUrl() {
return embedUrl;
}
/**
* Set the Embed_url
*
* @param embedUrl the Embed_url to set
*/
public void setEmbedUrl(String embedUrl) {
this.embedUrl = embedUrl;
}
/**
* Returns the Encoding_progress
*
* @return the Encoding_progress
*/
public int getEncodingProgress() {
return encodingProgress;
}
/**
* Set the Encoding_progress
*
* @param encodingProgress the Encoding_progress to set
*/
public void setEncodingProgress(int encodingProgress) {
this.encodingProgress = encodingProgress;
}
/**
* Returns the End_time
*
* @return the End_time
*/
public Date getEndTime() {
return this.endTime != null ? new Date(this.endTime.getTime()) : null;
}
/**
* Set the End_time
*
* @param endTime the End_time to set
*/
public void setEndTime(Date endTime) {
this.endTime = endTime != null ? new Date(endTime.getTime()) : null;
}
/**
* Returns the Event_delete
*
* @return the Event_delete
*/
public String getEventDelete() {
return eventDelete;
}
/**
* Set the Event_delete
*
* @param eventDelete the Event_delete to set
*/
public void setEventDelete(String eventDelete) {
this.eventDelete = eventDelete;
}
/**
* Returns the Event_live_offair
*
* @return the Event_live_offair
*/
public String getEventLiveOffair() {
return eventLiveOffair;
}
/**
* Set the Event_live_offair
*
* @param eventLiveOffair the Event_live_offair to set
*/
public void setEventLiveOffair(String eventLiveOffair) {
this.eventLiveOffair = eventLiveOffair;
}
/**
* Returns the Event_live_onair
*
* @return the Event_live_onair
*/
public String getEventLiveOnair() {
return eventLiveOnair;
}
/**
* Set the Event_live_onair
*
* @param eventLiveOnair the Event_live_onair to set
*/
public void setEventLiveOnair(String eventLiveOnair) {
this.eventLiveOnair = eventLiveOnair;
}
/**
* Returns the Event_modify
*
* @return the Event_modify
*/
public String getEventModify() {
return eventModify;
}
/**
* Set the Event_modify
*
* @param eventModify the Event_modify to set
*/
public void setEventModify(String eventModify) {
this.eventModify = eventModify;
}
/**
* Returns the explicit
*
* @return the explicit
*/
public boolean isExplicit() {
return explicit;
}
/**
* Set the Explicit
*
* @param explicit the Explicit to set
*/
public void setExplicit(boolean explicit) {
this.explicit = explicit;
}
/**
* Returns the Filmstrip_small_url
*
* @return the Filmstrip_small_url
*/
public String getFilmstripSmallUrl() {
return filmstripSmallUrl;
}
/**
* Set the Filmstrip_small_url
*
* @param filmstripSmallUrl the Filmstrip_small_url to set
*/
public void setFilmstripSmallUrl(String filmstripSmallUrl) {
this.filmstripSmallUrl = filmstripSmallUrl;
}
/**
* Returns the Filters
*
* @return the Filters
*/
public String getFilters() {
return filters;
}
/**
* Set the Filters
*
* @param filters the Filters to set
*/
public void setFilters(String filters) {
this.filters = filters;
}
/**
* Returns the Genre
*
* @return the Genre
*/
public String getGenre() {
return genre;
}
/**
* Set the Genre
*
* @param genre the Genre to set
*/
public void setGenre(String genre) {
this.genre = genre;
}
/**
* Returns the Geoblocking
*
* @return the Geoblocking
*/
public List<String> getGeoblocking() {
return geoblocking;
}
/**
* Set the Geoblocking
*
* @param geoblocking the Geoblocking to set
*/
public void setGeoblocking(List<String> geoblocking) {
this.geoblocking = geoblocking;
}
/**
* Returns the Geoloc
*
* @return the Geoloc
*/
public List<Double> getGeoloc() {
return geoloc;
}
/**
* Set the Geoloc
*
* @param geoloc the Geoloc to set
*/
public void setGeoloc(List<Double> geoloc) {
this.geoloc = geoloc;
}
/**
* Returns the Id
*
* @return the Id
*/
public String getId() {
return id;
}
/**
* Set the Id
*
* @param id the Id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* Returns the Ids
*
* @return the Ids
*/
public String getIds() {
return ids;
}
/**
* Set the Ids
*
* @param ids the Ids to set
*/
public void setIds(String ids) {
this.ids = ids;
}
/**
* Returns the Isrc
*
* @return the Isrc
*/
public String getIsrc() {
return isrc;
}
/**
* Set the Isrc
*
* @param isrc the Isrc to set
*/
public void setIsrc(String isrc) {
this.isrc = isrc;
}
/**
* Returns the Language
*
* @return the Language
*/
public String getLanguage() {
return language;
}
/**
* Set the Language
*
* @param language the Language to set
*/
public void setLanguage(String language) {
this.language = language;
}
/**
* Returns the liveAdBreak
*
* @return the liveAdBreak
*/
public boolean isLiveAdBreak() {
return liveAdBreak;
}
/**
* Set the Live_ad_break
*
* @param liveAdBreak the Live_ad_break to set
*/
public void setLiveAdBreak(boolean liveAdBreak) {
this.liveAdBreak = liveAdBreak;
}
/**
* Returns the Live_frag_publish_url
*
* @return the Live_frag_publish_url
*/
public String getLiveFragPublishUrl() {
return liveFragPublishUrl;
}
/**
* Set the Live_frag_publish_url
*
* @param liveFragPublishUrl the Live_frag_publish_url to set
*/
public void setLiveFragPublishUrl(String liveFragPublishUrl) {
this.liveFragPublishUrl = liveFragPublishUrl;
}
/**
* Returns the Live_publish_url
*
* @return the Live_publish_url
*/
public String getLivePublishUrl() {
return livePublishUrl;
}
/**
* Set the Live_publish_url
*
* @param livePublishUrl the Live_publish_url to set
*/
public void setLivePublishUrl(String livePublishUrl) {
this.livePublishUrl = livePublishUrl;
}
/**
* Returns the Mediablocking
*
* @return the Mediablocking
*/
public List<String> getMediablocking() {
return mediablocking;
}
/**
* Set the Mediablocking
*
* @param mediablocking the Mediablocking to set
*/
public void setMediablocking(List<String> mediablocking) {
this.mediablocking = mediablocking;
}
/**
* Returns the Metadata_credit_actors
*
* @return the Metadata_credit_actors
*/
public String getMetadataCreditActors() {
return metadataCreditActors;
}
/**
* Set the Metadata_credit_actors
*
* @param metadataCreditActors the Metadata_credit_actors to set
*/
public void setMetadataCreditActors(String metadataCreditActors) {
this.metadataCreditActors = metadataCreditActors;
}
/**
* Returns the Metadata_credit_director
*
* @return the Metadata_credit_director
*/
public String getMetadataCreditDirector() {
return metadataCreditDirector;
}
/**
* Set the Metadata_credit_director
*
* @param metadataCreditDirector the Metadata_credit_director to set
*/
public void setMetadataCreditDirector(String metadataCreditDirector) {
this.metadataCreditDirector = metadataCreditDirector;
}
/**
* Returns the Metadata_genre
*
* @return the Metadata_genre
*/
public String getMetadataGenre() {
return metadataGenre;
}
/**
* Set the Metadata_genre
*
* @param metadataGenre the Metadata_genre to set
*/
public void setMetadataGenre(String metadataGenre) {
this.metadataGenre = metadataGenre;
}
/**
* Returns the Metadata_original_language
*
* @return the Metadata_original_language
*/
public String getMetadataOriginalLanguage() {
return metadataOriginalLanguage;
}
/**
* Set the Metadata_original_language
*
* @param metadataOriginalLanguage the Metadata_original_language to set
*/
public void setMetadataOriginalLanguage(String metadataOriginalLanguage) {
this.metadataOriginalLanguage = metadataOriginalLanguage;
}
/**
* Returns the Metadata_original_title
*
* @return the Metadata_original_title
*/
public String getMetadataOriginalTitle() {
return metadataOriginalTitle;
}
/**
* Set the Metadata_original_title
*
* @param metadataOriginalTitle the Metadata_original_title to set
*/
public void setMetadataOriginalTitle(String metadataOriginalTitle) {
this.metadataOriginalTitle = metadataOriginalTitle;
}
/**
* Returns the Metadata_released
*
* @return the Metadata_released
*/
public String getMetadataReleased() {
return metadataReleased;
}
/**
* Set the Metadata_released
*
* @param metadataReleased the Metadata_released to set
*/
public void setMetadataReleased(String metadataReleased) {
this.metadataReleased = metadataReleased;
}
/**
* Returns the Metadata_show_episod
*
* @return the Metadata_show_episod
*/
public String getMetadataShowEpisod() {
return metadataShowEpisod;
}
/**
* Set the Metadata_show_episod
*
* @param metadataShowEpisod the Metadata_show_episod to set
*/
public void setMetadataShowEpisod(String metadataShowEpisod) {
this.metadataShowEpisod = metadataShowEpisod;
}
/**
* Returns the Metadata_show_season
*
* @return the Metadata_show_season
*/
public String getMetadataShowSeason() {
return metadataShowSeason;
}
/**
* Set the Metadata_show_season
*
* @param metadataShowSeason the Metadata_show_season to set
*/
public void setMetadataShowSeason(String metadataShowSeason) {
this.metadataShowSeason = metadataShowSeason;
}
/**
* Returns the Metadata_visa
*
* @return the Metadata_visa
*/
public String getMetadataVisa() {
return metadataVisa;
}
/**
* Set the Metadata_visa
*
* @param metadataVisa the Metadata_visa to set
*/
public void setMetadataVisa(String metadataVisa) {
this.metadataVisa = metadataVisa;
}
/**
* Returns the Mode
*
* @return the Mode
*/
public String getMode() {
return mode;
}
/**
* Set the Mode
*
* @param mode the Mode to set
*/
public void setMode(String mode) {
this.mode = mode;
}
/**
* Returns the moderated
*
* @return the moderated
*/
public boolean isModerated() {
return moderated;
}
/**
* Set the Moderated
*
* @param moderated the Moderated to set
*/
public void setModerated(boolean moderated) {
this.moderated = moderated;
}
/**
* Returns the Modified_after
*
* @return the Modified_after
*/
public Timestamp getModifiedAfter() {
return modifiedAfter;
}
/**
* Set the Modified_after
*
* @param modifiedAfter the Modified_after to set
*/
public void setModifiedAfter(Timestamp modifiedAfter) {
this.modifiedAfter = modifiedAfter;
}
/**
* Returns the Modified_before
*
* @return the Modified_before
*/
public Timestamp getModifiedBefore() {
return modifiedBefore;
}
/**
* Set the Modified_before
*
* @param modifiedBefore the Modified_before to set
*/
public void setModifiedBefore(Timestamp modifiedBefore) {
this.modifiedBefore = modifiedBefore;
}
/**
* Returns the Modified_time
*
* @return the Modified_time
*/
public Timestamp getModifiedTime() {
return modifiedTime;
}
/**
* Set the Modified_time
*
* @param modifiedTime the Modified_time to set
*/
public void setModifiedTime(Timestamp modifiedTime) {
this.modifiedTime = modifiedTime;
}
/**
* Returns the Muyap
*
* @return the Muyap
*/
public String getMuyap() {
return muyap;
}
/**
* Set the Muyap
*
* @param muyap the Muyap to set
*/
public void setMuyap(String muyap) {
this.muyap = muyap;
}
/**
* Returns the onair
*
* @return the onair
*/
public boolean isOnair() {
return onair;
}
/**
* Set the Onair
*
* @param onair the Onair to set
*/
public void setOnair(boolean onair) {
this.onair = onair;
}
/**
* Returns the Owner
*
* @return the Owner
*/
public User getOwner() {
return owner;
}
/**
* Set the Owner
*
* @param owner the Owner to set
*/
public void setOwner(User owner) {
this.owner = owner;
}
/**
* Returns the paywall
*
* @return the paywall
*/
public boolean isPaywall() {
return paywall;
}
/**
* Set the Paywall
*
* @param paywall the Paywall to set
*/
public void setPaywall(boolean paywall) {
this.paywall = paywall;
}
/**
* Returns the poster
*
* @return the poster
*/
public boolean isPoster() {
return poster;
}
/**
* Set the Poster
*
* @param poster the Poster to set
*/
public void setPoster(boolean poster) {
this.poster = poster;
}
/**
* Returns the Poster_135x180_url
*
* @return the Poster_135x180_url
*/
public String getPoster135x180Url() {
return poster135x180Url;
}
/**
* Set the Poster_135x180_url
*
* @param poster135x180Url the Poster_135x180_url to set
*/
public void setPoster135x180Url(String poster135x180Url) {
this.poster135x180Url = poster135x180Url;
}
/**
* Returns the Poster_180x240_url
*
* @return the Poster_180x240_url
*/
public String getPoster180x240Url() {
return poster180x240Url;
}
/**
* Set the Poster_180x240_url
*
* @param poster180x240Url the Poster_180x240_url to set
*/
public void setPoster180x240Url(String poster180x240Url) {
this.poster180x240Url = poster180x240Url;
}
/**
* Returns the Poster_270x360_url
*
* @return the Poster_270x360_url
*/
public String getPoster270x360Url() {
return poster270x360Url;
}
/**
* Set the Poster_270x360_url
*
* @param poster270x360Url the Poster_270x360_url to set
*/
public void setPoster270x360Url(String poster270x360Url) {
this.poster270x360Url = poster270x360Url;
}
/**
* Returns the Poster_360x480_url
*
* @return the Poster_360x480_url
*/
public String getPoster360x480Url() {
return poster360x480Url;
}
/**
* Set the Poster_360x480_url
*
* @param poster360x480Url the Poster_360x480_url to set
*/
public void setPoster360x480Url(String poster360x480Url) {
this.poster360x480Url = poster360x480Url;
}
/**
* Returns the Poster_45x60_url
*
* @return the Poster_45x60_url
*/
public String getPoster45x60Url() {
return poster45x60Url;
}
/**
* Set the Poster_45x60_url
*
* @param poster45x60Url the Poster_45x60_url to set
*/
public void setPoster45x60Url(String poster45x60Url) {
this.poster45x60Url = poster45x60Url;
}
/**
* Returns the Poster_90x120_url
*
* @return the Poster_90x120_url
*/
public String getPoster90x120Url() {
return poster90x120Url;
}
/**
* Set the Poster_90x120_url
*
* @param poster90x120Url the Poster_90x120_url to set
*/
public void setPoster90x120Url(String poster90x120Url) {
this.poster90x120Url = poster90x120Url;
}
/**
* Returns the Poster_url
*
* @return the Poster_url
*/
public String getPosterUrl() {
return posterUrl;
}
/**
* Set the Poster_url
*
* @param posterUrl the Poster_url to set
*/
public void setPosterUrl(String posterUrl) {
this.posterUrl = posterUrl;
}
/**
* Returns the Price_details
*
* @return the Price_details
*/
public String getPriceDetails() {
return priceDetails;
}
/**
* Set the Price_details
*
* @param priceDetails the Price_details to set
*/
public void setPriceDetails(String priceDetails) {
this.priceDetails = priceDetails;
}
public boolean ispRivate() {
return pRivate;
}
/**
* Set the Private_
*
* @param pRivate the Private_ to set
*/
public void setpRivate(boolean pRivate) {
this.pRivate = pRivate;
}
public boolean isPublished() {
return published;
}
/**
* Set the Published
*
* @param published the Published to set
*/
public void setPublished(boolean published) {
this.published = published;
}
/**
* Returns the Rating
*
* @return the Rating
*/
public float getRating() {
return rating;
}
/**
* Set the Rating
*
* @param rating the Rating to set
*/
public void setRating(float rating) {
this.rating = rating;
}
/**
* Returns the Ratings_total
*
* @return the Ratings_total
*/
public int getRatingsTotal() {
return ratingsTotal;
}
/**
* Set the Ratings_total
*
* @param ratingsTotal the Ratings_total to set
*/
public void setRatingsTotal(int ratingsTotal) {
this.ratingsTotal = ratingsTotal;
}
/**
* Returns the Recurrence
*
* @return the Recurrence
*/
public String getRecurrence() {
return recurrence;
}
/**
* Set the Recurrence
*
* @param recurrence the Recurrence to set
*/
public void setRecurrence(String recurrence) {
this.recurrence = recurrence;
}
/**
* Returns the Rental_duration
*
* @return the Rental_duration
*/
public int getRentalDuration() {
return rentalDuration;
}
/**
* Set the Rental_duration
*
* @param rentalDuration the Rental_duration to set
*/
public void setRentalDuration(int rentalDuration) {
this.rentalDuration = rentalDuration;
}
/**
* Returns the Rental_price
*
* @return the Rental_price
*/
public float getRentalPrice() {
return rentalPrice;
}
/**
* Set the Rental_price
*
* @param rentalPrice the Rental_price to set
*/
public void setRentalPrice(float rentalPrice) {
this.rentalPrice = rentalPrice;
}
/**
* Returns the Rental_price_formatted
*
* @return the Rental_price_formatted
*/
public String getRentalPriceFormatted() {
return rentalPriceFormatted;
}
/**
* Set the Rental_price_formatted
*
* @param rentalPriceFormatted the Rental_price_formatted to set
*/
public void setRentalPriceFormatted(String rentalPriceFormatted) {
this.rentalPriceFormatted = rentalPriceFormatted;
}
/**
* Returns the Rental_start_time
*
* @return the Rental_start_time
*/
public int getRentalStartTime() {
return rentalStartTime;
}
/**
* Set the Rental_start_time
*
* @param rentalStartTime the Rental_start_time to set
*/
public void setRentalStartTime(int rentalStartTime) {
this.rentalStartTime = rentalStartTime;
}
/**
* Returns the Search
*
* @return the Search
*/
public String getSearch() {
return search;
}
/**
* Set the Search
*
* @param search the Search to set
*/
public void setSearch(String search) {
this.search = search;
}
/**
* Returns the Sharing_urls
*
* @return the Sharing_urls
*/
public String getSharingUrls() {
return sharingUrls;
}
/**
* Set the Sharing_urls
*
* @param sharingUrls the Sharing_urls to set
*/
public void setSharingUrls(String sharingUrls) {
this.sharingUrls = sharingUrls;
}
/**
* Returns the Sort
*
* @return the Sort
*/
public String getSort() {
return sort;
}
/**
* Set the Sort
*
* @param sort the Sort to set
*/
public void setSort(String sort) {
this.sort = sort;
}
/**
* Returns the Soundtrack_info
*
* @return the Soundtrack_info
*/
public String getSoundtrackInfo() {
return soundtrackInfo;
}
/**
* Set the Soundtrack_info
*
* @param soundtrackInfo the Soundtrack_info to set
*/
public void setSoundtrackInfo(String soundtrackInfo) {
this.soundtrackInfo = soundtrackInfo;
}
/**
* Returns the Start_time
*
* @return the Start_time
*/
public Date getStartTime() {
return this.startTime != null ? new Date(this.startTime.getTime()) : null;
}
/**
* Set the Start_time
*
* @param startTime the Start_time to set
*/
public void setStartTime(Date startTime) {
this.startTime = startTime != null ? new Date(startTime.getTime()) : null;
}
/**
* Returns the Status
*
* @return the Status
*/
public String getStatus() {
return status;
}
/**
* Set the Status
*
* @param status the Status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* Returns the Stream_h264_hd1080_url
*
* @return the Stream_h264_hd1080_url
*/
public String getStreamH264Hd1080Url() {
return streamH264Hd1080Url;
}
/**
* Set the Stream_h264_hd1080_url
*
* @param streamH264Hd1080Url the Stream_h264_hd1080_url to set
*/
public void setStreamH264Hd1080Url(String streamH264Hd1080Url) {
this.streamH264Hd1080Url = streamH264Hd1080Url;
}
/**
* Returns the Stream_h264_hd_url
*
* @return the Stream_h264_hd_url
*/
public String getStreamH264HdUrl() {
return streamH264HdUrl;
}
/**
* Set the Stream_h264_hd_url
*
* @param streamH264HdUrl the Stream_h264_hd_url to set
*/
public void setStreamH264HdUrl(String streamH264HdUrl) {
this.streamH264HdUrl = streamH264HdUrl;
}
/**
* Returns the Stream_h264_hq_url
*
* @return the Stream_h264_hq_url
*/
public String getStreamH264HqUrl() {
return streamH264HqUrl;
}
/**
* Set the Stream_h264_hq_url
*
* @param streamH264HqUrl the Stream_h264_hq_url to set
*/
public void setStreamH264HqUrl(String streamH264HqUrl) {
this.streamH264HqUrl = streamH264HqUrl;
}
/**
* Returns the Stream_h264_l1_url
*
* @return the Stream_h264_l1_url
*/
public String getStreamH264L1Url() {
return streamH264L1Url;
}
/**
* Set the Stream_h264_l1_url
*
* @param streamH264L1Url the Stream_h264_l1_url to set
*/
public void setStreamH264L1Url(String streamH264L1Url) {
this.streamH264L1Url = streamH264L1Url;
}
/**
* Returns the Stream_h264_l2_url
*
* @return the Stream_h264_l2_url
*/
public String getStreamH264L2Url() {
return streamH264L2Url;
}
/**
* Set the Stream_h264_l2_url
*
* @param streamH264L2Url the Stream_h264_l2_url to set
*/
public void setStreamH264L2Url(String streamH264L2Url) {
this.streamH264L2Url = streamH264L2Url;
}
/**
* Returns the Stream_h264_ld_url
*
* @return the Stream_h264_ld_url
*/
public String getStreamH264LdUrl() {
return streamH264LdUrl;
}
/**
* Set the Stream_h264_ld_url
*
* @param streamH264LdUrl the Stream_h264_ld_url to set
*/
public void setStreamH264LdUrl(String streamH264LdUrl) {
this.streamH264LdUrl = streamH264LdUrl;
}
/**
* Returns the Stream_h264_url
*
* @return the Stream_h264_url
*/
public String getStreamH264Url() {
return streamH264Url;
}
/**
* Set the Stream_h264_url
*
* @param streamH264Url the Stream_h264_url to set
*/
public void setStreamH264Url(String streamH264Url) {
this.streamH264Url = streamH264Url;
}
/**
* Returns the Stream_hls_url
*
* @return the Stream_hls_url
*/
public String getStreamHlsUrl() {
return streamHlsUrl;
}
/**
* Set the Stream_hls_url
*
* @param streamHlsUrl the Stream_hls_url to set
*/
public void setStreamHlsUrl(String streamHlsUrl) {
this.streamHlsUrl = streamHlsUrl;
}
/**
* Returns the Stream_live_hds_url
*
* @return the Stream_live_hds_url
*/
public String getStreamLiveHdsUrl() {
return streamLiveHdsUrl;
}
/**
* Set the Stream_live_hds_url
*
* @param streamLiveHdsUrl the Stream_live_hds_url to set
*/
public void setStreamLiveHdsUrl(String streamLiveHdsUrl) {
this.streamLiveHdsUrl = streamLiveHdsUrl;
}
/**
* Returns the Stream_live_hls_url
*
* @return the Stream_live_hls_url
*/
public String getStreamLiveHlsUrl() {
return streamLiveHlsUrl;
}
/**
* Set the Stream_live_hls_url
*
* @param streamLiveHlsUrl the Stream_live_hls_url to set
*/
public void setStreamLiveHlsUrl(String streamLiveHlsUrl) {
this.streamLiveHlsUrl = streamLiveHlsUrl;
}
/**
* Returns the Stream_live_rtmp_url
*
* @return the Stream_live_rtmp_url
*/
public String getStreamLiveRtmpUrl() {
return streamLiveRtmpUrl;
}
/**
* Set the Stream_live_rtmp_url
*
* @param streamLiveRtmpUrl the Stream_live_rtmp_url to set
*/
public void setStreamLiveRtmpUrl(String streamLiveRtmpUrl) {
this.streamLiveRtmpUrl = streamLiveRtmpUrl;
}
/**
* Returns the Stream_premium_preview_hls_url
*
* @return the Stream_premium_preview_hls_url
*/
public String getStreamPremiumPreviewHlsUrl() {
return streamPremiumPreviewHlsUrl;
}
/**
* Set the Stream_premium_preview_hls_url
*
* @param streamPremiumPreviewHlsUrl the Stream_premium_preview_hls_url to set
*/
public void setStreamPremiumPreviewHlsUrl(String streamPremiumPreviewHlsUrl) {
this.streamPremiumPreviewHlsUrl = streamPremiumPreviewHlsUrl;
}
/**
* Returns the Stream_premium_preview_mp4_url
*
* @return the Stream_premium_preview_mp4_url
*/
public String getStreamPremiumPreviewMp4Url() {
return streamPremiumPreviewMp4Url;
}
/**
* Set the Stream_premium_preview_mp4_url
*
* @param streamPremiumPreviewMp4Url the Stream_premium_preview_mp4_url to set
*/
public void setStreamPremiumPreviewMp4Url(String streamPremiumPreviewMp4Url) {
this.streamPremiumPreviewMp4Url = streamPremiumPreviewMp4Url;
}
/**
* Returns the Stream_premium_preview_web_url
*
* @return the Stream_premium_preview_web_url
*/
public String getStreamPremiumPreviewWebUrl() {
return streamPremiumPreviewWebUrl;
}
/**
* Set the Stream_premium_preview_web_url
*
* @param streamPremiumPreviewWebUrl the Stream_premium_preview_web_url to set
*/
public void setStreamPremiumPreviewWebUrl(String streamPremiumPreviewWebUrl) {
this.streamPremiumPreviewWebUrl = streamPremiumPreviewWebUrl;
}
/**
* Returns the Stream_source_url
*
* @return the Stream_source_url
*/
public String getStreamSourceUrl() {
return streamSourceUrl;
}
/**
* Set the Stream_source_url
*
* @param streamSourceUrl the Stream_source_url to set
*/
public void setStreamSourceUrl(String streamSourceUrl) {
this.streamSourceUrl = streamSourceUrl;
}
/**
* Returns the Strongtags
*
* @return the Strongtags
*/
public List<Strongtag> getStrongtags() {
return strongtags;
}
/**
* Set the Strongtags
*
* @param strongtags the Strongtags to set
*/
public void setStrongtags(List<Strongtag> strongtags) {
this.strongtags = strongtags;
}
public boolean isSvod() {
return svod;
}
/**
* Set the Svod
*
* @param svod the Svod to set
*/
public void setSvod(boolean svod) {
this.svod = svod;
}
/**
* Returns the Swf_url
*
* @return the Swf_url
*/
public String getSwfUrl() {
return swfUrl;
}
/**
* Set the Swf_url
*
* @param swfUrl the Swf_url to set
*/
public void setSwfUrl(String swfUrl) {
this.swfUrl = swfUrl;
}
public boolean isSyncAllowed() {
return syncAllowed;
}
/**
* Set the Sync_allowed
*
* @param syncAllowed the Sync_allowed to set
*/
public void setSyncAllowed(boolean syncAllowed) {
this.syncAllowed = syncAllowed;
}
/**
* Returns the Tags
*
* @return the Tags
*/
public List<String> getTags() {
return tags;
}
/**
* Set the Tags
*
* @param tags the Tags to set
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/**
* Returns the Taken_time
*
* @return the Taken_time
*/
public Date getTakenTime() {
return this.takenTime != null ? new Date(this.takenTime.getTime()) : null;
}
/**
* Set the Taken_time
*
* @param takenTime the Taken_time to set
*/
public void setTakenTime(Date takenTime) {
this.takenTime = takenTime != null ? new Date(takenTime.getTime()) : null;
}
/**
* Returns the Thumbnail_120_url
*
* @return the Thumbnail_120_url
*/
public String getThumbnail120Url() {
return thumbnail120Url;
}
/**
* Set the Thumbnail_120_url
*
* @param thumbnail120Url the Thumbnail_120_url to set
*/
public void setThumbnail120Url(String thumbnail120Url) {
this.thumbnail120Url = thumbnail120Url;
}
/**
* Returns the Thumbnail_180_url
*
* @return the Thumbnail_180_url
*/
public String getThumbnail180Url() {
return thumbnail180Url;
}
/**
* Set the Thumbnail_180_url
*
* @param thumbnail180Url the Thumbnail_180_url to set
*/
public void setThumbnail180Url(String thumbnail180Url) {
this.thumbnail180Url = thumbnail180Url;
}
/**
* Returns the Thumbnail_240_url
*
* @return the Thumbnail_240_url
*/
public String getThumbnail240Url() {
return thumbnail240Url;
}
/**
* Set the Thumbnail_240_url
*
* @param thumbnail240Url the Thumbnail_240_url to set
*/
public void setThumbnail240Url(String thumbnail240Url) {
this.thumbnail240Url = thumbnail240Url;
}
/**
* Returns the Thumbnail_360_url
*
* @return the Thumbnail_360_url
*/
public String getThumbnail360Url() {
return thumbnail360Url;
}
/**
* Set the Thumbnail_360_url
*
* @param thumbnail360Url the Thumbnail_360_url to set
*/
public void setThumbnail360Url(String thumbnail360Url) {
this.thumbnail360Url = thumbnail360Url;
}
/**
* Returns the Thumbnail_480_url
*
* @return the Thumbnail_480_url
*/
public String getThumbnail480Url() {
return thumbnail480Url;
}
/**
* Set the Thumbnail_480_url
*
* @param thumbnail480Url the Thumbnail_480_url to set
*/
public void setThumbnail480Url(String thumbnail480Url) {
this.thumbnail480Url = thumbnail480Url;
}
/**
* Returns the Thumbnail_60_url
*
* @return the Thumbnail_60_url
*/
public String getThumbnail60Url() {
return thumbnail60Url;
}
/**
* Set the Thumbnail_60_url
*
* @param thumbnail60Url the Thumbnail_60_url to set
*/
public void setThumbnail60Url(String thumbnail60Url) {
this.thumbnail60Url = thumbnail60Url;
}
/**
* Returns the Thumbnail_720_url
*
* @return the Thumbnail_720_url
*/
public String getThumbnail720Url() {
return thumbnail720Url;
}
/**
* Set the Thumbnail_720_url
*
* @param thumbnail720Url the Thumbnail_720_url to set
*/
public void setThumbnail720Url(String thumbnail720Url) {
this.thumbnail720Url = thumbnail720Url;
}
/**
* Returns the Thumbnail_url
*
* @return the Thumbnail_url
*/
public String getThumbnailUrl() {
return thumbnailUrl;
}
/**
* Set the Thumbnail_url
*
* @param thumbnailUrl the Thumbnail_url to set
*/
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
/**
* Returns the Title
*
* @return the Title
*/
public String getTitle() {
return title;
}
/**
* Set the Title
*
* @param title the Title to set
*/
public void setTitle(String title) {
this.title = title;
}
public boolean isTvod() {
return tvod;
}
/**
* Set the Tvod
*
* @param tvod the Tvod to set
*/
public void setTvod(boolean tvod) {
this.tvod = tvod;
}
/**
* Returns the Type
*
* @return the Type
*/
public String getType() {
return type;
}
/**
* Set the Type
*
* @param type the Type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* Returns the Upc
*
* @return the Upc
*/
public String getUpc() {
return upc;
}
/**
* Set the Upc
*
* @param upc the Upc to set
*/
public void setUpc(String upc) {
this.upc = upc;
}
/**
* Returns the Url
*
* @return the Url
*/
public String getUrl() {
return url;
}
/**
* Set the Url
*
* @param url the Url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* Returns the Views_last_day
*
* @return the Views_last_day
*/
public int getViewsLastDay() {
return viewsLastDay;
}
/**
* Set the Views_last_day
*
* @param viewsLastDay the Views_last_day to set
*/
public void setViewsLastDay(int viewsLastDay) {
this.viewsLastDay = viewsLastDay;
}
/**
* Returns the Views_last_hour
*
* @return the Views_last_hour
*/
public int getViewsLastHour() {
return viewsLastHour;
}
/**
* Set the Views_last_hour
*
* @param viewsLastHour the Views_last_hour to set
*/
public void setViewsLastHour(int viewsLastHour) {
this.viewsLastHour = viewsLastHour;
}
/**
* Returns the Views_last_month
*
* @return the Views_last_month
*/
public int getViewsLastMonth() {
return viewsLastMonth;
}
/**
* Set the Views_last_month
*
* @param viewsLastMonth the Views_last_month to set
*/
public void setViewsLastMonth(int viewsLastMonth) {
this.viewsLastMonth = viewsLastMonth;
}
/**
* Returns the Views_last_week
*
* @return the Views_last_week
*/
public int getViewsLastWeek() {
return viewsLastWeek;
}
/**
* Set the Views_last_week
*
* @param viewsLastWeek the Views_last_week to set
*/
public void setViewsLastWeek(int viewsLastWeek) {
this.viewsLastWeek = viewsLastWeek;
}
/**
* Returns the Views_total
*
* @return the Views_total
*/
public int getViewsTotal() {
return viewsTotal;
}
/**
* Set the Views_total
*
* @param viewsTotal the Views_total to set
*/
public void setViewsTotal(int viewsTotal) {
this.viewsTotal = viewsTotal;
}
/**
* {@docRoot}
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE);
}
/**
* {@docRoot}
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Video video = (Video) o;
if (id != null ? !id.equals(video.id) : video.id != null) {
return false;
}
return true;
}
/**
* {@docRoot}
*/
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
|
#!/bin/bash
#SBATCH --account=def-dkulic
#SBATCH --mem=8000M # memory per node
#SBATCH --time=10:00:00 # time (DD-HH:MM)
#SBATCH --output=/project/6001934/lingheng/Double_DDPG_Job_output/discrete_MountainCar-v0_ddpg_softcopy_action_noise_seed3_run0_%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 MountainCar-v0 --random-seed 3 --exploration-strategy action_noise --summary-dir ../Double_DDPG_Results_no_monitor/discrete/MountainCar-v0/ddpg_softcopy_action_noise_seed3_run0 --double-ddpg-flag
|
<gh_stars>0
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import enMessages from '@/locales/en'
import zhMessages from '@/locales/zh'
import jaMessages from '@/locales/ja'
import koMessages from '@/locales/ko'
Vue.use(VueI18n)
export default new VueI18n({
locale: 'zh',
fallbackLocale: 'en',
silentFallbackWarn: true,
formatFallbackMessages: true,
messages: {
en: enMessages,
zh: zhMessages,
ja: jaMessages,
ko: koMessages
}
})
|
<filename>TX23Manipulations.h
#ifndef TX23manipulations_h
#define TX23manipulations_h
#include <LaCrosse_TX23.h>
class TX23manipulations{
public:
float metersToMiles(float speed);
float getMeterToMile();
void printTX23Data(LaCrosse_TX23 anemometer);
int getDir();
int getSpeed();
private:
const float meterToMile = 2.2369;
int theDirection;
float theSpeed;
};
#endif
|
<reponame>escenic/TwelveMonkeys
/*
* Copyright (c) 2014, <NAME>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name "TwelveMonkeys" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.plugins.bmp;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* Implements 4 bit RLE decoding as specified by in the Windows BMP (aka DIB) file format.
* <p/>
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @version $Id: RLE4Decoder.java#1 $
*/
final class RLE4Decoder extends AbstractRLEDecoder {
final static int BIT_MASKS[] = {0xf0, 0x0f};
final static int BIT_SHIFTS[] = {4, 0};
public RLE4Decoder(final int width) {
super(width, 4);
}
protected void decodeRow(final InputStream stream) throws IOException {
// Just clear row now, and be done with it...
Arrays.fill(row, (byte) 0);
int deltaX = 0;
int deltaY = 0;
while (srcY >= 0) {
int byte1 = stream.read();
int byte2 = checkEOF(stream.read());
if (byte1 == 0x00) {
switch (byte2) {
case 0x00:
// End of line
// NOTE: Some BMPs have double EOLs..
if (srcX != 0) {
srcX = row.length * 2;
}
break;
case 0x01:
// End of bitmap
srcX = row.length * 2;
srcY = -1;
break;
case 0x02:
// Delta
deltaX = srcX + stream.read();
deltaY = srcY + checkEOF(stream.read());
srcX = row.length * 2;
break;
default:
// Absolute mode
// Copy the next byte2 (3..255) nibbles from file to output
// Two samples are packed into one byte
// If the *number of bytes* used to pack is not a multiple of 2,
// an additional padding byte is in the stream and must be skipped
boolean paddingByte = (((byte2 + 1) / 2) % 2) != 0;
int packed = 0;
for (int i = 0; i < byte2; i++) {
if (i % 2 == 0) {
packed = checkEOF(stream.read());
}
row[srcX / 2] |= (byte) (((packed & BIT_MASKS[i % 2]) >> BIT_SHIFTS[i % 2])<< BIT_SHIFTS[srcX % 2]);
srcX++;
}
if (paddingByte) {
checkEOF(stream.read());
}
}
}
else {
// Encoded mode
// Replicate the two samples in byte2 as many times as byte1 says
for (int i = 0; i < byte1; i++) {
row[srcX / 2] |= (byte) (((byte2 & BIT_MASKS[i % 2]) >> BIT_SHIFTS[i % 2]) << BIT_SHIFTS[srcX % 2]);
srcX++;
}
}
// If we're done with a complete row, copy the data
if (srcX >= row.length * 2) {
// Move to new position, either absolute (delta) or next line
if (deltaX != 0 || deltaY != 0) {
srcX = deltaX;
if (deltaY != srcY) {
srcY = deltaY;
break;
}
deltaX = 0;
deltaY = 0;
}
else if (srcY == -1) {
break;
}
else {
srcX = 0;
srcY++;
break;
}
}
}
}
}
|
#!/bin/bash
# vim: softtabstop=2 shiftwidth=2 expandtab
# shellcheck disable=SC1091
. /lib/dracut-lib.sh
# Source options detected at build time
# shellcheck disable=SC1091
[ -r /etc/zfsbootmenu.conf ] && source /etc/zfsbootmenu.conf
# shellcheck disable=SC2154
if [ -n "${embedded_kcl}" ]; then
mkdir -p /etc/cmdline.d/
echo "${embedded_kcl}" > /etc/cmdline.d/zfsbootmenu.conf
fi
if [ -z "${BYTE_ORDER}" ]; then
warn "unable to determine platform endianness; assuming little-endian"
BYTE_ORDER="le"
fi
# Let the command line override our host id.
# shellcheck disable=SC2034
cli_spl_hostid=$( getarg spl.spl_hostid ) || cli_spl_hostid=$( getarg spl_hostid )
if [ -n "${cli_spl_hostid}" ] ; then
# Start empty so only valid hostids are set for future use
spl_hostid=
# Test for decimal
if (( 10#${cli_spl_hostid} )) >/dev/null 2>&1 ; then
spl_hostid="$( printf "%08x" "${cli_spl_hostid}" )"
# Test for hex. Requires 0x, if present, to be stripped
# The change to cli_spl_hostid isn't saved outside of the test
elif (( 16#${cli_spl_hostid#0x} )) >/dev/null 2>&1 ; then
spl_hostid="${cli_spl_hostid#0x}"
# printf will strip leading 0s if there are more than 8 hex digits
# normalize to a maximum of 8, then run through printf to fill in
# if there are fewer than 8 digits.
spl_hostid="$( printf "%08x" "0x${spl_hostid:0:8}" )"
# base 10 / base 16 tests fail on 0
elif [ "${cli_spl_hostid#0x}" -eq "0" ] >/dev/null 2>&1 ; then
spl_hostid=0
# Not valid hex or dec, log
else
warn "ZFSBootMenu: invalid hostid value ${cli_spl_hostid}, ignoring"
fi
fi
# Use the last defined console= to control menu output
control_term=$( getarg console )
if [ -n "${control_term}" ]; then
control_term="/dev/${control_term%,*}"
info "ZFSBootMenu: setting controlling terminal to: ${control_term}"
else
control_term="/dev/tty1"
info "ZFSBootMenu: defaulting controlling terminal to: ${control_term}"
fi
# Use loglevel to determine logging to /dev/kmsg
min_logging=4
loglevel=$( getarg loglevel )
if [ -n "${loglevel}" ]; then
# minimum log level of 4, so we never lose error or warning messages
[ "${loglevel}" -ge ${min_logging} ] || loglevel=${min_logging}
info "ZFSBootMenu: setting log level from command line: ${loglevel}"
else
loglevel=${min_logging}
fi
# hostid - discover the hostid used to import a pool on failure, assume it
# force - append -f to zpool import
# strict - legacy behavior, drop to an emergency shell on failure
import_policy=$( getarg zbm.import_policy )
if [ -n "${import_policy}" ]; then
case "${import_policy}" in
hostid)
if [ "${BYTE_ORDER}" = "be" ]; then
info "ZFSBootMenu: invalid option for big endian systems"
info "ZFSBootMenu: setting import_policy to strict"
import_policy="strict"
else
info "ZFSBootMenu: setting import_policy to hostid matching"
fi
;;
force)
info "ZFSBootMenu: setting import_policy to force"
;;
strict)
info "ZFSBootMenu: setting import_policy to strict"
;;
*)
info "ZFSBootMenu: unknown import policy ${import_policy}, defaulting to hostid"
import_policy="hostid"
;;
esac
elif getargbool 0 zbm.force_import -d force_import ; then
import_policy="force"
info "ZFSBootMenu: setting import_policy to force"
else
info "ZFSBootMenu: defaulting import_policy to hostid"
import_policy="hostid"
fi
# zbm.timeout= overrides timeout=
menu_timeout=$( getarg zbm.timeout -d timeout )
if [ -n "${menu_timeout}" ]; then
info "ZFSBootMenu: setting menu timeout from command line: ${menu_timeout}"
elif getargbool 0 zbm.show ; then
menu_timeout=-1;
info "ZFSBootMenu: forcing display of menu"
elif getargbool 0 zbm.skip ; then
menu_timeout=0;
info "ZFSBootMenu: skipping display of menu"
else
menu_timeout=10
fi
zbm_import_delay=$( getarg zbm.import_delay )
if [ "${zbm_import_delay:-0}" -gt 0 ] 2>/dev/null ; then
# Again, this validates that zbm_import_delay is numeric in addition to logging
info "ZFSBootMenu: import retry delay is ${zbm_import_delay} seconds"
else
zbm_import_delay=5
fi
# Allow setting of console size; there are no defaults here
# shellcheck disable=SC2034
zbm_lines=$( getarg zbm.lines )
# shellcheck disable=SC2034
zbm_columns=$( getarg zbm.columns )
# Allow sorting based on a key
zbm_sort=
sort_key=$( getarg zbm.sort_key )
if [ -n "${sort_key}" ] ; then
valid_keys=( "name" "creation" "used" )
for key in "${valid_keys[@]}"; do
if [ "${key}" == "${sort_key}" ]; then
zbm_sort="${key}"
fi
done
# If zbm_sort is empty (invalid user provided key)
# Default the starting sort key to 'name'
if [ -z "${zbm_sort}" ] ; then
sort_key="name"
zbm_sort="name"
fi
# Append any other sort keys to the selected one
for key in "${valid_keys[@]}"; do
if [ "${key}" != "${sort_key}" ]; then
zbm_sort="${zbm_sort};${key}"
fi
done
info "ZFSBootMenu: setting sort key order to ${zbm_sort}"
else
zbm_sort="name;creation;used"
info "ZFSBootMenu: defaulting sort key order to ${zbm_sort}"
fi
# Turn on tmux integrations
# shellcheck disable=SC2034
if getargbool 0 zbm.tmux ; then
zbm_tmux=1
info "ZFSBootMenu: enabling tmux integrations"
fi
# shellcheck disable=SC2034
if [ "${BYTE_ORDER}" = "be" ]; then
zbm_set_hostid=0
info "ZFSBootMenu: big endian detected, disabling automatic replacement of spl_hostid"
elif getargbool 1 zbm.set_hostid ; then
zbm_set_hostid=1
info "ZFSBootMenu: enabling automatic replacement of spl_hostid"
else
zbm_set_hostid=0
info "ZFSBootMenu: disabling automatic replacement of spl_hostid"
fi
# rewrite root=
prefer=$( getarg zbm.prefer )
if [ -n "${prefer}" ]; then
root="zfsbootmenu:POOL=${prefer}"
fi
wait_for_zfs=0
case "${root}" in
""|zfsbootmenu|zfsbootmenu:)
# We'll take root unset, root=zfsbootmenu, or root=zfsbootmenu:
root="zfsbootmenu"
# shellcheck disable=SC2034
rootok=1
wait_for_zfs=1
info "ZFSBootMenu: enabling menu after udev settles"
;;
zfsbootmenu:POOL=*)
# Prefer a specific pool for bootfs value, root=zfsbootmenu:POOL=zroot
root="${root#zfsbootmenu:POOL=}"
# shellcheck disable=SC2034
rootok=1
wait_for_zfs=1
info "ZFSBootMenu: preferring ${root} for bootfs"
;;
esac
# Pool preference ending in ! indicates a hard requirement
bpool="${root%\!}"
if [ "${bpool}" != "${root}" ]; then
# shellcheck disable=SC2034
zbm_require_bpool=1
root="${bpool}"
fi
# Make sure Dracut is happy that we have a root
if [ ${wait_for_zfs} -eq 1 ]; then
ln -s /dev/null /dev/root 2>/dev/null
fi
|
#!/bin/bash
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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.
#
# author: johncox@google.com (John Cox)
#
# Android Container Demo Course Builder module setup script.
#
set -e
shopt -s nullglob
export SOURCE_DIR="$( cd "$( dirname "$0" )" && cd .. && pwd )"
export MODULE_NAME=android_container
export MODULE_SRC_DIR=$SOURCE_DIR/src
function check_directory() {
# Die if the given directory does not exist.
local target=$1 && shift
if [ ! -d $target ]; then
echo "$target does not exist; aborting"
exit 1
fi
}
function link_module() {
# Symlinks module files into Course Builder directory.
local target=$1 && shift
_link $MODULE_SRC_DIR $target/modules/$MODULE_NAME
}
function _link() {
local from=$1 && shift
local to=$1 && shift
if [ ! -h $to ]; then
ln -s $from $to
fi
}
function usage() { cat <<EOF
Usage: $0 [-d <directory>]
-d Required argument. Absolute path to the directory containing your Course
Builder installation.
-h Show this message
EOF
}
while getopts d:h option
do
case $option
in
d) TARGET="$OPTARG" ;;
h) usage; exit 0;;
*) usage; exit 1;;
esac
done
if [ ! $TARGET ]; then
usage
exit 1
fi
check_directory $TARGET
link_module $TARGET
|
#!/bin/zsh
echo "Retrieve the metadata about the images"
python photography_meta.py
PHOTO_DIR=`jq -r '.folders.directory' "$OLI_LOCAL_DIR/photography/conf.json"`
echo $PHOTO_DIR
if [[ ! -d "$PHOTO_DIR" ]]
then
echo "$DIRECTORY with images does exists on the filesystem."
exit 1
fi
echo "Saving js from Elm code in $PHOTO_DIR"
cd photography/webviewer
elm-test
elm make src/Main.elm --output="$PHOTO_DIR/main.js"
cp html/* "$PHOTO_DIR/"
|
#!/usr/bin/env bash
echo 'Starting ssh build script for nougat 7.1 (sdk 25)'
./scripts/build_ssh.sh scripts/config/ssh-25.config
|
<reponame>deoncarlette/AutoMod
"""
auto_mod_cli.py
RTC: For voice communication
"""
# import os
# import sys
import logging
from .clubhouse import Clubhouse
class AudioClient:
AGORA_KEY = Clubhouse.AGORA_KEY
try:
import agorartc
logging.info("Imported agorartc")
RTC = agorartc.createRtcEngineBridge()
eventHandler = agorartc.RtcEngineEventHandlerBase()
RTC.initEventHandler(eventHandler)
# 0xFFFFFFFE will exclude Chinese servers from Agora's servers.
RTC.initialize(AGORA_KEY, None, agorartc.AREA_CODE_GLOB & 0xFFFFFFFE)
audio_recording_device_manager, err = RTC.createAudioRecordingDeviceManager()
count = audio_recording_device_manager.getCount()
audio_recording_device_result = False
for i in range(count):
_audio_device = audio_recording_device_manager.getDevice(i, '', '')
if 'BlackHole 2ch' in _audio_device[1]:
audio_recording_device_manager.setDevice(_audio_device[2])
audio_recording_device_manager.setDeviceVolume(50)
audio_recording_device_result = True
logging.info("Audio recording device set to BlackHole 2ch")
break
if not audio_recording_device_result:
logging.warning("Audio recording device not set")
# Enhance voice quality
if RTC.setAudioProfile(
agorartc.AUDIO_PROFILE_MUSIC_HIGH_QUALITY_STEREO,
agorartc.AUDIO_SCENARIO_GAME_STREAMING
) < 0:
logging.warning("Failed to set the high quality audio profile")
except ImportError:
RTC = None
def __init__(self):
self.clubhouse_audio = super().__init__()
# Set some global variables
# Figure this out when you're ready to start playing music
def mute_audio(self):
self.RTC.muteLocalAudioStream(mute=True)
return
def unmute_audio(self):
self.RTC.muteLocalAudioStream(mute=False)
return
def start_audio(self, channel, token=None, join_info=None):
if not token and not join_info:
join_info = Clubhouse().channel.join_channel(channel)
token = join_info.get(token)
elif not token and join_info:
token = join_info.get(token)
# Check for the voice level.
if self.RTC:
token = token
self.RTC.joinChannel(token, channel, "", int(Clubhouse().client_id))
self.RTC.muteLocalAudioStream(mute=False)
Clubhouse().channel.update_audio_mode(channel)
self.RTC.muteAllRemoteAudioStreams(mute=True)
logging.info("RTC audio loaded")
logging.info("RTC remote audio muted")
else:
logging.warning("Agora SDK is not installed.")
return
def terminate_music(self, channel):
if self.RTC:
self.RTC.leaveChannel()
return
if __name__ == "__main__":
pass
|
#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Run a shell command on all slave hosts.
#
# Environment Variables
#
# SPARK_SLAVES File naming remote hosts.
# Default is ${SPARK_CONF_DIR}/slaves.
# SPARK_CONF_DIR Alternate conf dir. Default is ${SPARK_HOME}/conf.
# SPARK_SLAVE_SLEEP Seconds to sleep between spawning remote commands.
# SPARK_SSH_OPTS Options passed to ssh when running remote commands.
##
usage="Usage: slaves.sh [--config <conf-dir>] command..."
# if no args specified, show usage
if [ $# -le 0 ]; then
echo $usage
exit 1
fi
sbin="`dirname "$0"`"
sbin="`cd "$sbin"; pwd`"
. "$sbin/spark-config.sh"
# If the slaves file is specified in the command line,
# then it takes precedence over the definition in
# spark-env.sh. Save it here.
HOSTLIST="$SPARK_SLAVES"
# Check if --config is passed as an argument. It is an optional parameter.
# Exit if the argument is not a directory.
if [ "$1" == "--config" ]
then
shift
conf_dir="$1"
if [ ! -d "$conf_dir" ]
then
echo "ERROR : $conf_dir is not a directory"
echo $usage
exit 1
else
export SPARK_CONF_DIR="$conf_dir"
fi
shift
fi
. "$SPARK_PREFIX/bin/load-spark-env.sh"
if [ "$HOSTLIST" = "" ]; then
if [ "$SPARK_SLAVES" = "" ]; then
export HOSTLIST="${SPARK_CONF_DIR}/slaves"
else
export HOSTLIST="${SPARK_SLAVES}"
fi
fi
# By default disable strict host key checking
if [ "$SPARK_SSH_OPTS" = "" ]; then
SPARK_SSH_OPTS="-o StrictHostKeyChecking=no"
fi
for slave in `cat "$HOSTLIST"|sed "s/#.*$//;/^$/d"`; do
ssh $SPARK_SSH_OPTS "$slave" $"${@// /\\ }" \
2>&1 | sed "s/^/$slave: /" &
if [ "$SPARK_SLAVE_SLEEP" != "" ]; then
sleep $SPARK_SLAVE_SLEEP
fi
done
wait
|
function validateEmail(email) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
let valid = validateEmail('test@example.com'); // returns true
|
<filename>swexpertacademy.com/source/1873.cpp<gh_stars>1-10
// 1873. 상호의 배틀필드
// 2019.07.02
#include<iostream>
#include<string>
using namespace std;
// U D L R
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0, -1, 1 };
char map[21][21];
char tank;
int xPos;
int yPos;
int h;
int w;
void move(int dir, int x, int y)
{
int xx = x + dx[dir];
int yy = y + dy[dir];
if (xx >= h || yy >= w || xx < 0 || yy < 0 || map[xx][yy] != '.')
{
return;
}
else
{
map[x][y] = '.';
map[xx][yy] = tank;
xPos = xx;
yPos = yy;
}
}
void shoot(char tank, int x, int y)
{
int xx = x;
int yy = y;
int dir = 0;
switch (tank)
{
case '^':
dir = 0;
break;
case 'v':
dir = 1;
break;
case '<':
dir = 2;
break;
case '>':
dir = 3;
break;
}
while (true)
{
xx += dx[dir];
yy += dy[dir];
if (xx >= h || yy >= w || xx < 0 || yy < 0)
{
break;
}
else if (map[xx][yy] == '*')
{
map[xx][yy] = '.';
break;
}
else if (map[xx][yy] == '#')
{
break;
}
}
}
int main()
{
int t;
cin >> t;
for (int testCase = 1; testCase <= t; testCase++)
{
cin >> h >> w;
string line[21];
for (int i = 0; i < h; i++)
{
cin >> line[i];
}
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
map[i][j] = line[i][j];
if (map[i][j] == '<' || map[i][j] == '^' || map[i][j] == 'v' || map[i][j] == '>')
{
xPos = i;
yPos = j;
tank = map[i][j]; // 초기 탱크 모양 저장
}
}
}
int length;
cin >> length;
string order;
cin >> order;
for (int i = 0; i < length; i++)
{
switch (order[i])
{
case 'U':
move(0, xPos, yPos);
tank = '^';
map[xPos][yPos] = '^';
break;
case 'D':
move(1, xPos, yPos);
tank = 'v';
map[xPos][yPos] = 'v';
break;
case 'L':
move(2, xPos, yPos);
tank = '<';
map[xPos][yPos] = '<';
break;
case 'R':
move(3, xPos, yPos);
tank = '>';
map[xPos][yPos] = '>';
break;
case 'S':
shoot(tank, xPos, yPos);
break;
}
}
cout << "#" << testCase << " ";
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
cout << map[i][j];
}
cout << endl;
}
}
return 0;
}
|
#!/bin/bash
export PATH=/n/home04/xiaoleliu/ChiLin/alvin/xiaoleliu_lab/marge2/phaseI_init/miniconda3/bin:$PATH
source activate lisa
mkdir -p logs/cluster
#snakemake --unlock
#parallel simple job
#snakemake -j 150 --cluster-config ../cluster.json --immediate-submit --cluster "sbatch --time={cluster.time} --mem={cluster.memory} --partition={cluster.queue} --cpus-per-task={cluster.nCPUs} -J {cluster.name} -o {cluster.output} -e {cluster.error} --open-mode=append"
#with dependencies/multi-dependencies on
split -d -l 100 ../creeds_tf.txt ../creeds_tf.txt.
for i in ../creeds_tf.txt.*;do
echo "------"
echo $i
echo "------"
snakemake --config gene_list=${i} -j 50 --immediate-submit --cluster-config ../cluster.json --cluster "export PATH=/n/home04/xiaoleliu/ChiLin/alvin/xiaoleliu_lab/marge2/phaseI_init/miniconda3/bin:$PATH;source activate lisa; ../sbatch_script.py {dependencies}"
break
done
|
package tae.cosmetics.guiscreen.utilities;
import java.awt.Color;
import java.io.IOException;
import java.util.List;
import org.lwjgl.input.Keyboard;
import io.netty.buffer.Unpooled;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiUtilRenderComponents;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.nbt.NBTTagString;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.CPacketCustomPayload;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import tae.cosmetics.ColorCode;
import tae.cosmetics.gui.util.GuiSetKeybind;
import tae.cosmetics.gui.util.GuiSignature;
import tae.cosmetics.guiscreen.AbstractTAEGuiScreen;
import tae.cosmetics.guiscreen.GuiHome;
import tae.cosmetics.guiscreen.GuiScreenRendering;
import tae.cosmetics.guiscreen.button.GuiOnOffButton;
import tae.cosmetics.settings.Keybind;
public class BookArt extends AbstractTAEGuiScreen {
public static final Keybind openGui = new Keybind("Open bookart gui", 0, () -> {
AbstractTAEGuiScreen.displayScreen(new BookArt(new GuiScreenRendering(new GuiHome())));
});
private static final int bookWidth = 14; //height oops
private static final int bookHeight = 12; //width
private Pixel[][] pixels = new Pixel[bookWidth][bookHeight];
private final Pixel[][] prevCache = new Pixel[bookWidth][bookHeight];
private final Pixel[][] postCache = new Pixel[bookWidth][bookHeight];
private final GuiButton[] buttonSize = new GuiButton[15];
private final GuiButton[] buttonColor = new GuiButton[16];
private final GuiButton[] buttonFormat = new GuiButton[4];
private int xStart = 0;
private int yStart = 0;
{
for(int i = 0; i < pixels.length; i++) {
for(int j = 0; j < pixels[i].length; j++) {
pixels[i][j] = new Pixel();
}
}
for(int i = 0; i < 9; i++) {
buttonSize[i] = new GuiButton(i, 0, 0, 20, 20, Character.toString((char)(0x2580 + i)));
}
buttonSize[9] = new GuiButton(9, 0, 0, 20, 20, Character.toString((char)(0x2580 + 16)));
buttonSize[10] = new GuiButton(10, 0, 0, 20, 20, Character.toString((char)(0x2580 + 18)));
buttonSize[11] = new GuiButton(11, 0, 0, 20, 20, Character.toString((char)(0x2580 + 19)));
for(int i = 12; i < 15; i++) {
buttonSize[i] = new GuiButton(i, 0, 0, 20, 20, Character.toString((char)(0x2580 + 13 + i)));
}
int index = 0;
int counter = 0;
for(ColorCode c : ColorCode.values()) {
if(c.getType() == 0) {
buttonColor[index] = new GuiButton(32 + counter, 0, 0, 20, 20, ColorCode.values()[counter].getCode() + (char)0x2588);
index++;
}
counter++;
}
index = 0;
counter = 0;
for(ColorCode c : ColorCode.values()) {
if(c.getType() == 1 && c != ColorCode.BOLD && c != ColorCode.OBFUSCATED) {
buttonFormat[index] = new GuiButton(64 + counter, 0, 0, 20, 20, ColorCode.values()[counter].getCode() + (char)0x2588);
index++;
}
counter++;
}
}
private static final ResourceLocation BOOK_GUI_TEXTURES = new ResourceLocation("textures/gui/book.png");
private GuiButton currentButtonSize;
private GuiButton currentButtonColor;
private GuiButton currentButtonFormat;
private GuiButton buttonSingle;
private GuiButton buttonAll;
private GuiButton buttonBack;
private GuiButton buttonForward;
private GuiButton addPage;
private GuiButton clear;
private GuiButton save;
private GuiButton load;
private GuiOnOffButton mode2b2t;
private boolean shorten = false;
public BookArt(GuiScreen parent) {
super(parent);
guiwidth = 350;
guiheight = 220;
buttonSingle = new GuiButton(97, 0, 0, 20, 20, Character.toString((char) 0x2196));
buttonSingle.enabled = false;
buttonAll = new GuiButton(98, 0, 0, 20, 20, Character.toString((char) 0x2294));
buttonBack = new GuiButton(100, 0, 0, 20, 20, Character.toString((char) 0x27f2));
buttonBack.enabled = false;
buttonForward = new GuiButton(101, 0, 0, 20, 20, Character.toString((char) 0x27f3));
buttonForward.enabled = false;
addPage = new GuiButton(99, 0, 0, 90, 20, "Add this page");
mode2b2t = new GuiOnOffButton(102, 0, 0, 130, 20, "2b2t mode: ", false, "Render how servers will set the book", 1);
clear = new GuiButton(103, 0, 0, 40, 20, "Clear");
save = new GuiButton(104, 0, 0, 40, 20, "Save");
load = new GuiButton(105, 0, 0, 40, 20, "Load");
settingsScreen = new AbstractTAEGuiScreen(parent) {
{
guiwidth = 200;
guiheight = 100;
}
private GuiSetKeybind openGuiKeyBind = null;
private String keyBindInfo = "Keybind to open book title mod";
@Override
public void initGui() {
if(openGuiKeyBind == null) {
openGuiKeyBind = new GuiSetKeybind(0, fontRenderer, 0, 0, 12, openGui.getInt());
openGuiKeyBind.setTextColor(-1);
openGuiKeyBind.setDisabledTextColour(-1);
openGuiKeyBind.setEnableBackgroundDrawing(true);
openGuiKeyBind.setMaxStringLength(32);
openGuiKeyBind.setCanLoseFocus(true);
}
super.initGui();
}
@Override
public void onGuiClosed() {
Keyboard.enableRepeatEvents(false);
openGui.updateBinding(openGuiKeyBind.getKeyCode());
mc.gameSettings.saveOptions();
}
@Override
protected void keyTyped(char typedChar, int keyCode) throws IOException {
if (openGuiKeyBind.textboxKeyTyped(typedChar, keyCode)) {
} else {
super.keyTyped(typedChar, keyCode);
}
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
super.mouseClicked(mouseX, mouseY, mouseButton);
if(openGuiKeyBind.mouseClicked(mouseX, mouseY, mouseButton)) {
}
}
@Override
protected void drawScreen0(int mouseX, int mouseY, float partialTicks) {
int i = width / 2;
int j = height / 2;
openGuiKeyBind.drawTextBox();
this.drawCenteredString(fontRenderer, keyBindInfo, i, j - 20, Color.WHITE.getRGB());
}
@Override
protected void updateButtonPositions(int x, int y) {
openGuiKeyBind.x = x - openGuiKeyBind.width / 2;
openGuiKeyBind.y = y - 6;
back.x = x - back.width / 2;
back.y = y + 16;
}
};
}
@Override
public void initGui() {
for(int i = 0; i < buttonSize.length; i++) {
buttonList.add(buttonSize[i]);
}
for(int i = 0; i < buttonColor.length; i++) {
buttonList.add(buttonColor[i]);
}
for(int i = 0; i < buttonFormat.length; i++) {
buttonList.add(buttonFormat[i]);
}
buttonList.add(buttonSingle);
buttonList.add(buttonAll);
buttonList.add(buttonBack);
buttonList.add(buttonForward);
buttonList.add(addPage);
buttonList.add(mode2b2t);
buttonList.add(clear);
buttonList.add(save);
buttonList.add(load);
super.initGui();
}
protected void drawScreen0(int mouseX, int mouseY, float partialTicks) {
int i = width / 2;
int j = height / 2;
drawPseudoBook(i, j - 10, mouseX, mouseY);
GuiSignature.draw(i + 132, j + 110);
}
private void drawPseudoBook(int x, int y, int mouseX, int mouseY) {
this.mc.getTextureManager().bindTexture(BOOK_GUI_TEXTURES);
this.drawTexturedModalRect(x, y - 192 / 2 + 6, 0, 0, 192, 192);
ITextComponent itextcomponent = ITextComponent.Serializer.jsonToComponent(updateText(shorten));
List<ITextComponent> lines = GuiUtilRenderComponents.splitText(itextcomponent, 116, this.fontRenderer, true, true);
int k1 = Math.min(128 / this.fontRenderer.FONT_HEIGHT, lines.size());
for (int l1 = 0; l1 < k1; ++l1)
{
ITextComponent itextcomponent2 = lines.get(l1);
this.fontRenderer.drawString(itextcomponent2.getUnformattedText(), x + 36, y - 192 / 2 + 32 + l1 * this.fontRenderer.FONT_HEIGHT, 0);
}
xStart = x + 36;
yStart = y - 192 / 2 + 32;
}
public void updatePixels(Pixel[][] other) {
updatePrevCache();
deepArrayCopy(pixels, other);
}
private String updateText(boolean shorten) {
StringBuilder builder = new StringBuilder();
builder.append("{\"text\":\"");
for(int i = 0; i < pixels.length; i++) {
for(int j = 0; j < pixels[i].length; j++) {
Pixel p = pixels[i][j];
if(j > 0) {
Pixel prev = pixels[i][j-1];
if(p.code == prev.code && p.format == prev.format) {
builder.append(p.c);
} else if(p.code == prev.code && p.format != prev.format) {
builder.append(p.format.getCode() + p.c);
} else {
builder.append(p.getPixel());
}
} else {
builder.append(p.getPixel());
}
}
if(i != pixels.length - 1) {
builder.append("\\n");
}
}
if(shorten && builder.length() > "{\"text\":\"".length() + 256) {
builder.setLength("{\"text\":\"".length() + 256);
}
builder.append("\"}");
return builder.toString();
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException {
int yCoord = -1;
for(int i = 0; i < pixels.length; i++) {
if(mouseY >= yStart + i * fontRenderer.FONT_HEIGHT && mouseY <= yStart + (i+1) * fontRenderer.FONT_HEIGHT) {
yCoord = i;
break;
}
}
int xCoord = -1;
if(yCoord > -1) {
for(int i = 0; i < pixels[yCoord].length; i++) {
if(mouseX >= xStart + i * fontRenderer.getCharWidth((char) 0x2588) && mouseX <= xStart + (i + 1) * fontRenderer.getCharWidth((char) 0x2588)) {
xCoord = i;
break;
}
}
}
if(xCoord > -1 && yCoord > -1) {
if(buttonAll.enabled == false) {
updatePrevCache();
mapFromPixel(yCoord, xCoord);
} else {
updatePrevCache();
updatePixel(pixels[yCoord][xCoord]);
}
}
super.mouseClicked(mouseX, mouseY, mouseButton);
}
private void updatePrevCache() {
buttonForward.enabled = false;
if(!buttonBack.enabled) {
buttonBack.enabled = true;
}
deepArrayCopy(prevCache, pixels);
}
private void mapFromPixel(int yCoord, int xCoord) {
mapFromPixel0(new Pixel(pixels[yCoord][xCoord]), yCoord, xCoord, true);
}
private void mapFromPixel0(Pixel original, int yCoord, int xCoord, boolean first) {
if(yCoord < 0 || xCoord < 0 || yCoord >= pixels.length || xCoord >= pixels[yCoord].length) {
return;
}
Pixel p = pixels[yCoord][xCoord];
if(first) {
Pixel test = new Pixel();
updatePixel(test);
if(p.equals(test)) {
return;
}
}
if(!original.equals(p)) {
return;
}
updatePixel(p);
mapFromPixel0(original, yCoord - 1, xCoord, false);
mapFromPixel0(original, yCoord + 1, xCoord, false);
mapFromPixel0(original, yCoord, xCoord - 1, false);
mapFromPixel0(original, yCoord, xCoord + 1, false);
}
private void updatePixel(Pixel pixel) {
if(currentButtonSize != null) {
pixel.setChar(currentButtonSize.displayString.charAt(0));
}
if(currentButtonColor != null) {
pixel.setColor(ColorCode.values()[currentButtonColor.id - 32]);
}
if(currentButtonFormat != null) {
pixel.setFormat(ColorCode.values()[currentButtonFormat.id - 64]);
}
}
private static void deepArrayCopy(Pixel[][] original, Pixel[][] toCopy) {
for(int i = 0; i < original.length; i++) {
for(int j = 0; j < original[i].length; j++) {
original[i][j] = new Pixel(toCopy[i][j]);
}
}
}
@Override
protected void actionPerformed(GuiButton button) throws IOException {
if(button != back) {
if(button.id < 32 && button != currentButtonSize) {
if(currentButtonSize != null) {
currentButtonSize.enabled = true;
}
currentButtonSize = button;
currentButtonSize.enabled = false;
} else if(button.id >= 32 && button.id < 64 && button != currentButtonColor) {
if(currentButtonColor != null) {
currentButtonColor.enabled = true;
}
currentButtonColor = button;
currentButtonColor.enabled = false;
} else if(button.id >= 64 && button.id < 96 && button != currentButtonFormat) {
if(currentButtonFormat != null) {
currentButtonFormat.enabled = true;
}
currentButtonFormat = button;
currentButtonFormat.enabled = false;
} else if(button == buttonAll) {
buttonSingle.enabled = true;
buttonAll.enabled = false;
} else if(button == buttonSingle) {
buttonSingle.enabled = false;
buttonAll.enabled = true;
} else if(button == buttonBack) {
buttonBack.enabled = false;
buttonForward.enabled = true;
deepArrayCopy(postCache, pixels);
deepArrayCopy(pixels, prevCache);
} else if(button == buttonForward) {
buttonBack.enabled = true;
buttonForward.enabled = false;
deepArrayCopy(pixels, postCache);
} else if(button == addPage) {
String text = updateText(false).replace("{\"text\":\"", "").replace("\"}", "").replace("\\n", "\n");
//text = text.substring(0, 128);
ItemStack held = mc.player.inventory.getCurrentItem();
if(held.getItem().equals(Items.WRITABLE_BOOK)) {
NBTTagCompound nbt = held.getTagCompound();
if(nbt != null) {
NBTTagList list = nbt.getTagList("pages", 8);
if(list != null) {
list.appendTag(new NBTTagString(text));
} else {
list = new NBTTagList();
list.appendTag(new NBTTagString(text));
nbt.setTag("pages", list);
}
} else {
nbt = new NBTTagCompound();
NBTTagList list = new NBTTagList();
list.appendTag(new NBTTagString(text));
nbt.setTag("pages", list);
held.setTagCompound(nbt);
}
PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer());
packetbuffer.writeItemStack(held);
this.mc.getConnection().sendPacket(new CPacketCustomPayload("MC|BEdit", packetbuffer));
addMessage("Added", width / 2 - 100, height / 2 - 95 + 8 * 22, 250, Color.GREEN);
} else {
addMessage("Please hold a book", width / 2 - 100, height / 2 - 95 + 8 * 22, 250, Color.RED);
}
} else if(button == mode2b2t) {
mode2b2t.changeStateOnClick();
shorten = mode2b2t.getValue();
} else if(button == clear) {
for(int i = 0; i < pixels.length; i++) {
for(int j = 0; j < pixels[i].length; j++) {
pixels[i][j] = new Pixel();
}
}
} else if(button == save) {
Pixel[][] toCopy = new Pixel[pixels.length][pixels[0].length];
deepArrayCopy(toCopy, pixels);
displayScreen(new GuiBookArtSaveLoad(this, toCopy));
} else if(button == load) {
displayScreen(new GuiBookArtSaveLoad(this));
}
}
super.actionPerformed(button);
}
@Override
public void onGuiClosed() {
}
@Override
protected void updateButtonPositions(int x, int y) {
for(int i = 0; i < buttonSize.length; i++) {
buttonSize[i].x = x - 100 + (i % 5) * 22;
buttonSize[i].y = y - 100 + (i / 5) * 22;
}
for(int i = 0; i < buttonColor.length; i++) {
buttonColor[i].x = x - 160 + (i % 2) * 22;
buttonColor[i].y = y - 100 + (i / 2) * 22;
}
for(int i = 0; i < buttonFormat.length; i++) {
buttonFormat[i].x = x - 100 + i * 22;
buttonFormat[i].y = (int) (y - 100 + 3.5 * 22);
}
buttonSingle.x = x - 100;
buttonSingle.y = y - 100 + 5 * 22;
buttonAll.x = x - 100 + 22;
buttonAll.y = y - 100 + 5 * 22;
buttonBack.x = x - 100 + 44;
buttonBack.y = y - 100 + 5 * 22;
buttonForward.x = x - 100 + 66;
buttonForward.y = y - 100 + 5 * 22;
addPage.x = x - 100;
addPage.y = y - 100 + 7 * 22;
mode2b2t.x = x + 30;
mode2b2t.y = y - 95 + 8 * 22;
clear.x = x - 160;
clear.y = y - 95 + 8 * 22;
save.x = x - 100;
save.y = y - 100 + 6 * 22;
load.x = x - 52;
load.y = y - 100 + 6 * 22;
}
static class Pixel {
private char c;
private ColorCode code;
private ColorCode format;
private Pixel() {
c = 0x2588;
code = ColorCode.BLACK;
format = ColorCode.RESET;
}
public Pixel(char c, ColorCode color, ColorCode format) {
this.c = c;
code = color;
this.format = format;
}
private Pixel(Pixel p) {
c = p.c;
code = p.code;
format = p.format;
}
private void setChar(char c) {
this.c = c;
}
private void setColor(ColorCode code) {
this.code = code;
}
private void setFormat(ColorCode code) {
this.format = code;
}
private String getPixel() {
return code.getCode() + (format == ColorCode.RESET ? "" : format.getCode()) + c;
}
public int getChar() {
return c;
}
public ColorCode getColor() {
return code;
}
public ColorCode getFormat() {
return format;
}
@Override
public boolean equals(Object pixel) {
if(this == pixel) {
return true;
} else if(!(pixel instanceof Pixel)) {
return false;
} else {
Pixel p = (Pixel) pixel;
return this.c == p.c && this.code == p.code && this.format == p.format;
}
}
}
}
|
\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
|
import java.util.Scanner;
public class FruitSearch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a list of fruits separated by a comma (i.e. apples, bananas, oranges): ");
String input = in.nextLine();
// Split the input string and store the fruits in an array
String[] fruits = input.split(",");
System.out.println("Enter the fruit you are looking for: ");
String searchInput = in.nextLine();
// Iterate over the array and compare each element to the user input
boolean found = false;
for (String fruit : fruits) {
if (fruit.toLowerCase().equals(searchInput.toLowerCase())) {
found = true;
break;
}
}
if (found) {
System.out.println("The fruit you are looking for is available.");
} else {
System.out.println("The fruit you are looking for is not available.");
}
}
}
|
#!/bin/sh
/bin/sleep 10
exec ./server
|
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/IDuxFE/idux/blob/main/LICENSE
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import type { InputModalityDetector } from './inputModalityDetector'
import type { ComponentPublicInstance, ComputedRef, InjectionKey, Ref, WatchStopHandle } from 'vue'
import { computed, inject, onScopeDispose, shallowRef, watchEffect } from 'vue'
import { _getEventTarget, _getShadowRoot, isBrowser, normalizePassiveListenerOptions } from '@idux/cdk/platform'
import { convertElement, createSharedComposable } from '@idux/cdk/utils'
import { TOUCH_BUFFER_MS, useSharedInputModalityDetector } from './inputModalityDetector'
export type FocusOrigin = 'touch' | 'mouse' | 'keyboard' | 'program' | null
/**
* Corresponds to the options that can be passed to the native `focus` event.
* via https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
*/
export interface FocusOptions {
/** Whether the browser should scroll to the element when it is focused. */
preventScroll?: boolean
}
/**
* Detection mode used for attributing the origin of a focus event.
*
* **immediate**: Any mousedown, keydown, or touchstart event that happened in the previous tick
* or the current tick will be used to assign a focus event's origin (to either mouse, keyboard, or touch).
* This is the default option.
*
* **eventual**: A focus event's origin is always attributed to the last corresponding
* mousedown, keydown, or touchstart event, no matter how long ago it occurred.
*/
export type FocusMonitorDetectionMode = 'immediate' | 'eventual'
/** Injectable service-level options for FocusMonitor. */
export interface FocusMonitorOptions {
detectionMode?: FocusMonitorDetectionMode
inputModalityDetector?: InputModalityDetector
}
/** InjectionToken for FocusMonitorOptions. */
export const FOCUS_MONITOR_OPTIONS_TOKEN: InjectionKey<FocusMonitorOptions> = Symbol('cdk-focus-monitor-options')
export const FOCUS_MONITOR_DEFAULT_OPTIONS: FocusMonitorOptions = {
detectionMode: 'immediate',
}
type MonitoredElementInfo = {
checkChildren: boolean
subject: Ref<FocusMonitorEvent>
rootNode: HTMLElement | ShadowRoot | Document
}
type ElementType =
| Ref<ComponentPublicInstance | HTMLElement | null | undefined>
| ComponentPublicInstance
| HTMLElement
| null
| undefined
/**
* Event listener options that enable capturing and also
* mark the listener as passive if the browser supports it.
*/
const captureEventListenerOptions = normalizePassiveListenerOptions({
passive: true,
capture: true,
})
export interface FocusMonitorEvent {
/**
* Focus origin.
*
* **mouse**: indicates the element was focused with the mouse
* **keyboard**: indicates the element was focused with the keyboard
* **touch**: indicates the element was focused by touching on a touchscreen
* **program**: indicates the element was focused programmatically
* **null**: indicates the element was blurred
*/
origin: FocusOrigin
/**
* Focus event, which may be 'undefined' if the focus is triggered by 'focusVia'.
*/
event?: FocusEvent
}
export interface FocusMonitor {
/**
* Monitors focus on an element and applies appropriate CSS classes.
*
* @param element The element to monitor
* @param checkChildren Whether to count the element as focused when its children are focused.
* @returns An observable that emits when the focus state of the element changes.
* When the element is blurred, null will be emitted.
*/
monitor(element: ElementType, checkChildren?: boolean): ComputedRef<FocusMonitorEvent>
/**
* Stops monitoring an element and removes all focus classes.
*
* @param element The element to stop monitoring.
*/
stopMonitoring(element: ElementType): void
/**
* Focuses the element via the specified focus origin.
*
* @param element Element to focus.
* @param origin Focus origin.
* @param options Options that can be used to configure the focus behavior.
*/
focusVia(element: ElementType, origin: FocusOrigin, options?: FocusOptions): void
}
/** Monitors mouse and keyboard events to determine the cause of focus events. */
export function useFocusMonitor(options?: FocusMonitorOptions): FocusMonitor {
const contextOptions = inject(FOCUS_MONITOR_OPTIONS_TOKEN, FOCUS_MONITOR_DEFAULT_OPTIONS)
/** Options for this InputModalityDetector. */
const _options = { ...contextOptions, ...options }
const _detectionMode = _options.detectionMode
const _inputModalityDetector = _options.inputModalityDetector ?? useSharedInputModalityDetector()
/** The focus origin that the next focus event is a result of. */
let _origin: FocusOrigin = null
/** The FocusOrigin of the last focus event tracked by the FocusMonitor. */
let _lastFocusOrigin: FocusOrigin
/** Whether the window has just been focused. */
let _windowFocused = false
/** The timeout id of the window focus timeout. */
let _windowFocusTimeoutId: number
/** The timeout id of the origin clearing timeout. */
let _originTimeoutId: number
/**
* Whether the origin was determined via a touch interaction. Necessary as properly attributing
* focus events to touch interactions requires special logic.
*/
let _originFromTouchInteraction = false
/** Map of elements being monitored to their info. */
const _elementInfo = new Map<HTMLElement, MonitoredElementInfo>()
/** The number of elements currently being monitored. */
let _monitoredElementCount = 0
/**
* Keeps track of the root nodes to which we've currently bound a focus/blur handler,
* as well as the number of monitored elements that they contain. We have to treat focus/blur
* handlers differently from the rest of the events, because the browser won't emit events
* to the document when focus moves inside of a shadow root.
*/
const _rootNodeFocusListenerCount = new Map<HTMLElement | Document | ShadowRoot, number>()
/**
* Event listener for `focus` events on the window.
* Needs to be an arrow function in order to preserve the context when it gets bound.
*/
const _windowFocusListener = () => {
// Make a note of when the window regains focus, so we can
// restore the origin info for the focused element.
_windowFocused = true
_windowFocusTimeoutId = setTimeout(() => (_windowFocused = false))
}
/** Subject for stopping our InputModalityDetector subscription. */
let _stopInputModalityDetector: WatchStopHandle | null = null
/**
* Event listener for `focus` and 'blur' events on the document.
* Needs to be an arrow function in order to preserve the context when it gets bound.
*/
const _rootNodeFocusAndBlurListener = (event: Event) => {
const target = _getEventTarget<HTMLElement>(event)
const handler = event.type === 'focus' ? _onFocus : _onBlur
// We need to walk up the ancestor chain in order to support `checkChildren`.
for (let element = target; element; element = element.parentElement) {
handler(event as FocusEvent, element)
}
}
/**
* Monitors focus on an element and applies appropriate CSS classes.
*
* @param element The element to monitor
* @param checkChildren Whether to count the element as focused when its children are focused.
* @returns An observable that emits when the focus state of the element changes.
* When the element is blurred, null will be emitted.
*/
function monitor(element: ElementType, checkChildren = false): ComputedRef<FocusMonitorEvent> {
const nativeElement = convertElement(element)
// Do nothing if we're not on the browser platform or the passed in node isn't an element.
if (!isBrowser || !nativeElement || nativeElement.nodeType !== 1) {
return computed(() => ({ origin: null }))
}
// If the element is inside the shadow DOM, we need to bind our focus/blur listeners to
// the shadow root, rather than the `document`, because the browser won't emit focus events
// to the `document`, if focus is moving within the same shadow root.
const rootNode = _getShadowRoot(nativeElement) || _getDocument()
const cachedInfo = _elementInfo.get(nativeElement)
// Check if we're already monitoring this element.
if (cachedInfo) {
if (checkChildren) {
// TODO(COMP-318): this can be problematic, because it'll turn all non-checkChildren
// observers into ones that behave as if `checkChildren` was turned on. We need a more
// robust solution.
cachedInfo.checkChildren = true
}
return computed(() => cachedInfo.subject.value)
}
// Create monitored element info.
const info: MonitoredElementInfo = {
checkChildren: checkChildren,
subject: shallowRef<FocusMonitorEvent>({ origin: null }),
rootNode,
}
_elementInfo.set(nativeElement, info)
_registerGlobalListeners(info)
return computed(() => info.subject.value)
}
/**
* Stops monitoring an element and removes all focus classes.
*
* @param element The element to stop monitoring.
*/
function stopMonitoring(element: ElementType): void {
const nativeElement = convertElement(element)
if (!nativeElement) {
return
}
const elementInfo = _elementInfo.get(nativeElement)
if (elementInfo) {
_setClasses(nativeElement)
_elementInfo.delete(nativeElement)
_removeGlobalListeners(elementInfo)
}
}
/**
* Focuses the element via the specified focus origin.
*
* @param element Element to focus.
* @param origin Focus origin.
* @param options Options that can be used to configure the focus behavior.
*/
function focusVia(element: ElementType, origin: FocusOrigin, options?: FocusOptions): void {
const nativeElement = convertElement(element)
const focusedElement = _getDocument().activeElement
// If the element is focused already, calling `focus` again won't trigger the event listener
// which means that the focus classes won't be updated. If that's the case, update the classes
// directly without waiting for an event.
if (nativeElement === focusedElement) {
_getClosestElementsInfo(nativeElement).forEach(([currentElement, info]) =>
_originChanged(currentElement, origin, info),
)
} else {
_setOrigin(origin)
// `focus` isn't available on the server
if (nativeElement && typeof nativeElement.focus === 'function') {
nativeElement.focus(options)
}
}
}
/** Access injected document if available or fallback to global document reference */
function _getDocument(): Document {
return document
}
/** Use defaultView of injected document if available or fallback to global window reference */
function _getWindow(): Window {
const doc = _getDocument()
return doc.defaultView || window
}
function _toggleClass(element: Element, className: string, shouldSet: boolean) {
if (shouldSet) {
element.classList.add(className)
} else {
element.classList.remove(className)
}
}
function _getFocusOrigin(focusEventTarget: HTMLElement | null): FocusOrigin {
if (_origin) {
// If the origin was realized via a touch interaction, we need to perform additional checks
// to determine whether the focus origin should be attributed to touch or program.
if (_originFromTouchInteraction) {
return _shouldBeAttributedToTouch(focusEventTarget) ? 'touch' : 'program'
} else {
return _origin
}
}
// If the window has just regained focus, we can restore the most recent origin from before the
// window blurred. Otherwise, we've reached the point where we can't identify the source of the
// focus. This typically means one of two things happened:
//
// 1) The element was programmatically focused, or
// 2) The element was focused via screen reader navigation (which generally doesn't fire
// events).
//
// Because we can't distinguish between these two cases, we default to setting `program`.
return _windowFocused && _lastFocusOrigin ? _lastFocusOrigin : 'program'
}
/**
* Returns whether the focus event should be attributed to touch. Recall that in IMMEDIATE mode, a
* touch origin isn't immediately reset at the next tick (see _setOrigin). This means that when we
* handle a focus event following a touch interaction, we need to determine whether (1) the focus
* event was directly caused by the touch interaction or (2) the focus event was caused by a
* subsequent programmatic focus call triggered by the touch interaction.
*
* @param focusEventTarget The target of the focus event under examination.
*/
function _shouldBeAttributedToTouch(focusEventTarget: HTMLElement | null): boolean {
// Please note that this check is not perfect. Consider the following edge case:
//
// <div #parent tabindex="0">
// <div #child tabindex="0" (click)="#parent.focus()"></div>
// </div>
//
// Suppose there is a FocusMonitor in IMMEDIATE mode attached to #parent. When the user touches
// #child, #parent is programmatically focused. This code will attribute the focus to touch
// instead of program. This is a relatively minor edge-case that can be worked around by using
// focusVia(parent, 'program') to focus #parent.
return _detectionMode === 'eventual' || !!focusEventTarget?.contains(_inputModalityDetector.target.value)
}
/**
* Sets the focus classes on the element based on the given focus origin.
*
* @param element The element to update the classes on.
* @param origin The focus origin.
*/
function _setClasses(element: HTMLElement, origin?: FocusOrigin): void {
_toggleClass(element, 'cdk-focused', !!origin)
_toggleClass(element, 'cdk-touch-focused', origin === 'touch')
_toggleClass(element, 'cdk-keyboard-focused', origin === 'keyboard')
_toggleClass(element, 'cdk-mouse-focused', origin === 'mouse')
_toggleClass(element, 'cdk-program-focused', origin === 'program')
}
/**
* Updates the focus origin. If we're using immediate detection mode, we schedule an async
* function to clear the origin at the end of a timeout. The duration of the timeout depends on
* the origin being set.
*
* @param origin The origin to set.
* @param isFromInteraction Whether we are setting the origin from an interaction event.
*/
function _setOrigin(origin: FocusOrigin, isFromInteraction = false): void {
_origin = origin
_originFromTouchInteraction = origin === 'touch' && isFromInteraction
// If we're in IMMEDIATE mode, reset the origin at the next tick (or in `TOUCH_BUFFER_MS` ms
// for a touch event). We reset the origin at the next tick because Firefox focuses one tick
// after the interaction event. We wait `TOUCH_BUFFER_MS` ms before resetting the origin for
// a touch event because when a touch event is fired, the associated focus event isn't yet in
// the event queue. Before doing so, clear any pending timeouts.
if (_detectionMode === 'immediate') {
clearTimeout(_originTimeoutId)
const ms = _originFromTouchInteraction ? TOUCH_BUFFER_MS : 1
_originTimeoutId = setTimeout(() => (_origin = null), ms)
}
}
/**
* Handles focus events on a registered element.
*
* @param event The focus event.
* @param element The monitored element.
*/
function _onFocus(event: FocusEvent, element: HTMLElement) {
// NOTE(mmalerba): We currently set the classes based on the focus origin of the most recent
// focus event affecting the monitored element. If we want to use the origin of the first event
// instead we should check for the cdk-focused class here and return if the element already has
// it. (This only matters for elements that have includesChildren = true).
// If we are not counting child-element-focus as focused, make sure that the event target is the
// monitored element itself.
const elementInfo = _elementInfo.get(element)
const focusEventTarget = _getEventTarget<HTMLElement>(event)
if (!elementInfo || (!elementInfo.checkChildren && element !== focusEventTarget)) {
return
}
_originChanged(element, _getFocusOrigin(focusEventTarget), elementInfo, event)
}
/**
* Handles blur events on a registered element.
*
* @param event The blur event.
* @param element The monitored element.
*/
function _onBlur(event: FocusEvent, element: HTMLElement) {
// If we are counting child-element-focus as focused, make sure that we aren't just blurring in
// order to focus another child of the monitored element.
const elementInfo = _elementInfo.get(element)
if (
!elementInfo ||
(elementInfo.checkChildren && event.relatedTarget instanceof Node && element.contains(event.relatedTarget))
) {
return
}
_setClasses(element)
_emitOrigin(elementInfo.subject, null, event)
}
function _emitOrigin(subject: Ref<FocusMonitorEvent>, origin: FocusOrigin, event?: FocusEvent) {
subject.value = { origin, event }
}
function _registerGlobalListeners(elementInfo: MonitoredElementInfo) {
if (!isBrowser) {
return
}
const rootNode = elementInfo.rootNode
const rootNodeFocusListeners = _rootNodeFocusListenerCount.get(rootNode) || 0
if (!rootNodeFocusListeners) {
rootNode.addEventListener('focus', _rootNodeFocusAndBlurListener, captureEventListenerOptions)
rootNode.addEventListener('blur', _rootNodeFocusAndBlurListener, captureEventListenerOptions)
}
_rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners + 1)
// Register global listeners when first element is monitored.
if (++_monitoredElementCount === 1) {
// Note: we listen to events in the capture phase so we
// can detect them even if the user stops propagation.
const window = _getWindow()
window.addEventListener('focus', _windowFocusListener)
// The InputModalityDetector is also just a collection of global listeners.
_stopInputModalityDetector = watchEffect(() => {
_setOrigin(_inputModalityDetector.modalityDetected.value, true /* isFromInteraction */)
})
}
}
function _removeGlobalListeners(elementInfo: MonitoredElementInfo) {
const rootNode = elementInfo.rootNode
if (_rootNodeFocusListenerCount.has(rootNode)) {
const rootNodeFocusListeners = _rootNodeFocusListenerCount.get(rootNode)!
if (rootNodeFocusListeners > 1) {
_rootNodeFocusListenerCount.set(rootNode, rootNodeFocusListeners - 1)
} else {
rootNode.removeEventListener('focus', _rootNodeFocusAndBlurListener, captureEventListenerOptions)
rootNode.removeEventListener('blur', _rootNodeFocusAndBlurListener, captureEventListenerOptions)
_rootNodeFocusListenerCount.delete(rootNode)
}
}
// Unregister global listeners when last element is unmonitored.
if (!--_monitoredElementCount) {
const window = _getWindow()
window.removeEventListener('focus', _windowFocusListener)
// Equivalently, stop our InputModalityDetector subscription.
if (_stopInputModalityDetector) {
_stopInputModalityDetector()
_stopInputModalityDetector = null
}
// Clear timeouts for all potentially pending timeouts to prevent the leaks.
clearTimeout(_windowFocusTimeoutId)
clearTimeout(_originTimeoutId)
}
}
/** Updates all the state on an element once its focus origin has changed. */
function _originChanged(
element: HTMLElement,
origin: FocusOrigin,
elementInfo: MonitoredElementInfo,
event?: FocusEvent,
) {
_setClasses(element, origin)
_emitOrigin(elementInfo.subject, origin, event)
_lastFocusOrigin = origin
}
/**
* Collects the `MonitoredElementInfo` of a particular element and
* all of its ancestors that have enabled `checkChildren`.
*
* @param element Element from which to start the search.
*/
function _getClosestElementsInfo(element: HTMLElement): [HTMLElement, MonitoredElementInfo][] {
const results: [HTMLElement, MonitoredElementInfo][] = []
_elementInfo.forEach((info, currentElement) => {
if (currentElement === element || (info.checkChildren && currentElement.contains(element))) {
results.push([currentElement, info])
}
})
return results
}
onScopeDispose(() => _elementInfo.forEach((_info, element) => stopMonitoring(element)))
return { monitor, stopMonitoring, focusVia }
}
export const useSharedFocusMonitor = createSharedComposable(() => useFocusMonitor())
|
<filename>packages/fractures-library/src/config/reset.ts
export const reset: string = `* {
margin: 0;
padding: 0;
}
*,
*:before,
*:after {
box-sizing: border-box;
}
html,
body {
position: relative;
}
html {
overflow-y: scroll;
}
a {
text-decoration: none;
}
ul,
ol {
list-style: none;
}
img { max-width: 100%; }
sub { vertical-align: sub; }
sup { vertical-align: super; }`;
|
import Minus from './minus.vue'
import Plus from './plus.vue'
import Tick from './tick.vue'
import Times from './times.vue'
import Time from './time.vue'
import Date from './date.vue'
import Datetime from './datetime.vue'
import Exclam from './exclam.vue'
import Caret from './caret.vue'
import Arrow from './arrow.vue'
import Navicon from './navicon.vue'
import Search from './search.vue'
import Theme from './theme.vue'
import CustomIcon from './custom.vue'
import Ellipsis from './ellipsis.vue'
import Backtop from './back-top.vue'
import Sun from './sun.vue'
import Moon from './moon.vue'
import Mobile from './mobile.vue'
import Sort from './sort.vue'
import Tselect from './tselect.vue'
import Cselect from './cselect.vue'
import Eye from './eye.vue'
export * from './square'
export * from './circle'
export * from './loading'
export {
Minus,
Plus,
Tick,
Times,
Time,
Date,
Datetime,
Exclam,
Caret,
Navicon,
Search,
Arrow,
Theme,
Ellipsis,
Backtop,
CustomIcon,
Sun,
Moon,
Mobile,
Sort,
Tselect,
Cselect,
Eye
}
|
// XML layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="16dp" />
<Button
android:id="@+id/submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Submit"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="64dp" />
<com.github.mikephil.charting.charts.BarChart
android:id="@+id/chart"
android:layout_width="match_parent"
android:layout_height="500dp"
android:layout_gravity="center_horizontal"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="112dp" />
</LinearLayout>
// Java Code
public class MainActivity extends AppCompatActivity {
private EditText editText;
private BarChart barChart;
private Button submitButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
barChart = findViewById(R.id.chart);
submitButton = findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = editText.getText().toString();
Map<String, Integer> map = getWordCountMap(text);
List<BarEntry> data = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
data.add(new BarEntry((float) entry.getValue(), entry.getKey()));
}
BarDataSet set = new BarDataSet(data, "Most Used Words");
BarData barData = new BarData(set);
barChart.setData(barData);
}
});
}
private Map<String, Integer> getWordCountMap(String text) {
Map<String, Integer> map = new HashMap<>();
String[] words = text.split(" ");
for (String word : words) {
if (map.containsKey(word)) {
int count = map.get(word);
map.put(word, count + 1);
} else {
map.put(word, 1);
}
}
return map;
}
}
|
<reponame>DinhLantstk789/codelibrary
package optimization;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
public class GeneticAlgorithm extends JFrame {
Random rnd = new Random(1);
int n = rnd.nextInt(300) + 250;
int generation;
double[] x = new double[n];
double[] y = new double[n];
int[] bestState;
{
for (int i = 0; i < n; i++) {
x[i] = rnd.nextDouble();
y[i] = rnd.nextDouble();
}
}
public void geneticAlgorithm() {
bestState = new int[n];
for (int i = 0; i < n; i++)
bestState[i] = i;
final int populationLimit = 100;
final Population population = new Population(populationLimit);
final int n = x.length;
for (int i = 0; i < populationLimit; i++)
population.chromosomes.add(new Chromosome(optimize(getRandomPermutation(n))));
final double mutationRate = 0.3;
final int generations = 10_000;
for (generation = 0; generation < generations; generation++) {
int i = 0;
while (population.chromosomes.size() < population.populationLimit) {
int i1 = rnd.nextInt(population.chromosomes.size());
int i2 = (i1 + 1 + rnd.nextInt(population.chromosomes.size() - 1)) % population.chromosomes.size();
Chromosome parent1 = population.chromosomes.get(i1);
Chromosome parent2 = population.chromosomes.get(i2);
int[][] pair = crossOver(parent1.p, parent2.p);
if (rnd.nextDouble() < mutationRate) {
mutate(pair[0]);
mutate(pair[1]);
}
population.chromosomes.add(new Chromosome(optimize(pair[0])));
population.chromosomes.add(new Chromosome(optimize(pair[1])));
}
population.nextGeneration();
bestState = population.chromosomes.get(0).p;
repaint();
}
}
int[][] crossOver(int[] p1, int[] p2) {
int n = p1.length;
int i1 = rnd.nextInt(n);
int i2 = (i1 + 1 + rnd.nextInt(n - 1)) % n;
int[] n1 = p1.clone();
int[] n2 = p2.clone();
boolean[] used1 = new boolean[n];
boolean[] used2 = new boolean[n];
for (int i = i1; ; i = (i + 1) % n) {
n1[i] = p2[i];
used1[n1[i]] = true;
n2[i] = p1[i];
used2[n2[i]] = true;
if (i == i2) {
break;
}
}
for (int i = (i2 + 1) % n; i != i1; i = (i + 1) % n) {
if (used1[n1[i]]) {
n1[i] = -1;
} else {
used1[n1[i]] = true;
}
if (used2[n2[i]]) {
n2[i] = -1;
} else {
used2[n2[i]] = true;
}
}
int pos1 = 0;
int pos2 = 0;
for (int i = 0; i < n; i++) {
if (n1[i] == -1) {
while (used1[pos1])
++pos1;
n1[i] = pos1++;
}
if (n2[i] == -1) {
while (used2[pos2])
++pos2;
n2[i] = pos2++;
}
}
return new int[][]{n1, n2};
}
void mutate(int[] p) {
int n = p.length;
int i = rnd.nextInt(n);
int j = (i + 1 + rnd.nextInt(n - 1)) % n;
reverse(p, i, j);
}
// http://en.wikipedia.org/wiki/2-opt
static void reverse(int[] p, int i, int j) {
int n = p.length;
// reverse order from i to j
while (i != j) {
int t = p[j];
p[j] = p[i];
p[i] = t;
i = (i + 1) % n;
if (i == j) break;
j = (j - 1 + n) % n;
}
}
double eval(int[] state) {
double res = 0;
for (int i = 0, j = state.length - 1; i < state.length; j = i++)
res += dist(x[state[i]], y[state[i]], x[state[j]], y[state[j]]);
return res;
}
static double dist(double x1, double y1, double x2, double y2) {
double dx = x1 - x2;
double dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
int[] getRandomPermutation(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
int j = rnd.nextInt(i + 1);
res[i] = res[j];
res[j] = i;
}
return res;
}
// try all 2-opt moves
int[] optimize(int[] p) {
int[] res = p.clone();
for (boolean improved = true; improved; ) {
improved = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j || (j + 1) % n == i) continue;
int i1 = (i - 1 + n) % n;
int j1 = (j + 1) % n;
double delta = dist(x[res[i1]], y[res[i1]], x[res[j]], y[res[j]])
+ dist(x[res[i]], y[res[i]], x[res[j1]], y[res[j1]])
- dist(x[res[i1]], y[res[i1]], x[res[i]], y[res[i]])
- dist(x[res[j]], y[res[j]], x[res[j1]], y[res[j1]]);
if (delta < -1e-9) {
reverse(res, i, j);
improved = true;
}
}
}
}
return res;
}
class Chromosome implements Comparable<Chromosome> {
final int[] p;
private double cost = Double.NaN;
public Chromosome(int[] p) {
this.p = p;
}
public double getCost() {
return Double.isNaN(cost) ? cost = eval(p) : cost;
}
@Override
public int compareTo(Chromosome o) {
return Double.compare(getCost(), o.getCost());
}
}
static class Population {
List<Chromosome> chromosomes = new ArrayList<>();
final int populationLimit;
public Population(int populationLimit) {
this.populationLimit = populationLimit;
}
public void nextGeneration() {
Collections.sort(chromosomes);
chromosomes = new ArrayList<>(chromosomes.subList(0, (chromosomes.size() + 1) / 2));
}
}
// visualization code
public GeneticAlgorithm() {
setContentPane(new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
int w = getWidth() - 5;
int h = getHeight() - 30;
for (int i = 0, j = n - 1; i < n; j = i++)
g.drawLine((int) (x[bestState[i]] * w), (int) ((1 - y[bestState[i]]) * h),
(int) (x[bestState[j]] * w), (int) ((1 - y[bestState[j]]) * h));
g.setColor(Color.RED);
for (int i = 0; i < n; i++)
g.drawOval((int) (x[i] * w) - 1, (int) ((1 - y[i]) * h) - 1, 3, 3);
g.setColor(Color.BLACK);
g.drawString(String.format("length: %.3f", eval(bestState)), 5, h + 20);
g.drawString(String.format("generation: %d", generation), 150, h + 20);
}
});
setSize(new Dimension(600, 600));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
new Thread(this::geneticAlgorithm).start();
}
public static void main(String[] args) {
new GeneticAlgorithm();
}
}
|
package sunset.gitcore.database;
import java.util.List;
public interface Client
{
void createTable(Class<?> cls) throws Exception;
void migrateTable(Class<?> cls) throws NotSupportedException;
void dropTable(Class<?> cls);
long insert(Object obj);
long insert(Object obj, String extra, Class<?> objType);
long insertOrReplace(Object obj);
long insertOrReplace(Object obj, Class<?> objType);
long update(Object obj);
long update(Object obj, String where, Object ...args);
long updateAll(Iterable<Object> objects);
long delete(Object objectToDelete) throws NotSupportedException;
long delete(Class<?> cls, Object primaryKey) throws NotSupportedException;
long delete(Class<?> cls) throws NotSupportedException;
<T> T get(Class<T> cls, Object pk);
<T> T get(Class<T> cls, String where, Object ...args);
<T> List<T> getList(Class<T> cls);
<T> List<T> getList(Class<T> cls, String orderBy);
<T> List<T> getList(Class<T> cls, String where, String orderBy, Object ...args);
<T> List<T> getList(Class<T> cls, String where, String groupBy, String orderBy, int pageIndex, int pageSize, Object ...args);
void setLogger(Log log);
}
|
<reponame>otaviomad/react-native-iconly
import { G, Path } from 'react-native-svg';
import * as React from 'react';
import withIcon from '../../lib/withIcon';
type Props = {
opacity?: string;
color?: string;
secondaryColor?: string;
set?: string;
strokeWidth?: string | number;
};
const Chart = ({
color, secondaryColor, strokeWidth, opacity, set,
}: Props) => {
const Bold = () => (
<G transform="translate(2 2)">
<Path
d="M14.669,20H5.33a5.352,5.352,0,0,1-3.94-1.39A5.353,5.353,0,0,1,0,14.67V5.33a5.353,5.353,0,0,1,1.389-3.94A5.353,5.353,0,0,1,5.33,0h9.339a5.345,5.345,0,0,1,3.937,1.389A5.38,5.38,0,0,1,20,5.33v9.34a5.352,5.352,0,0,1-1.39,3.94A5.354,5.354,0,0,1,14.669,20Zm-.02-9.087a.865.865,0,0,0-.449.128.807.807,0,0,0-.38.789v3.28a.826.826,0,0,0,.83.75.843.843,0,0,0,.83-.75V11.83a.839.839,0,0,0-.391-.789A.823.823,0,0,0,14.649,10.913ZM10.051,4a.823.823,0,0,0-.44.128.847.847,0,0,0-.392.79V15.11a.843.843,0,0,0,.831.75.827.827,0,0,0,.83-.75V4.92a.816.816,0,0,0-.379-.79A.872.872,0,0,0,10.051,4ZM5.39,7.282a.822.822,0,0,0-.44.128.843.843,0,0,0-.39.79v6.91a.834.834,0,0,0,1.659,0V8.2a.845.845,0,0,0-.389-.79A.825.825,0,0,0,5.39,7.282Z"
transform="translate(0 0)"
fill={color}
/>
</G>
);
const Bulk = () => (
<G transform="translate(2 2)">
<Path
d="M14.676,0H5.333C1.929,0,0,1.929,0,5.333v9.333C0,18.071,1.929,20,5.333,20h9.342C18.08,20,20,18.071,20,14.667V5.333C20,1.929,18.08,0,14.676,0"
fill={secondaryColor}
opacity={opacity}
/>
<Path
d="M.827,0A.833.833,0,0,0,0,.836V7.707a.831.831,0,0,0,1.662,0V.836A.835.835,0,0,0,.827,0"
transform="translate(4.542 7.369)"
fill={color}
/>
<Path
d="M.827,0A.833.833,0,0,0,0,.836V10.987a.831.831,0,0,0,1.662,0V.836A.835.835,0,0,0,.827,0"
transform="translate(9.209 4.089)"
fill={color}
/>
<Path
d="M.836,0A.835.835,0,0,0,0,.836V4.08a.831.831,0,0,0,1.662,0V.836A.833.833,0,0,0,.836,0"
transform="translate(13.804 10.996)"
fill={color}
/>
</G>
);
const Light = () => (
<G transform="translate(2 2)">
<Path
d="M.476,0V6.86"
transform="translate(4.895 8.202)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
<Path
d="M.476,0V10.143"
transform="translate(9.562 4.919)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
<Path
d="M.476,0V3.235"
transform="translate(14.152 11.827)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
<Path
d="M14.686,0H5.314C2.048,0,0,2.312,0,5.585v8.83C0,17.688,2.038,20,5.314,20h9.371C17.962,20,20,17.688,20,14.415V5.585C20,2.312,17.962,0,14.686,0Z"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
</G>
);
const Broken = () => (
<G transform="translate(2 2)">
<Path
d="M6.253,20C2.392,20,0,17.608,0,13.756v-7.5C0,2.392,2.392,0,6.253,0h7.493C17.59,0,20,2.392,20,6.253V8.575a.764.764,0,0,1-.765.765h-.009a.756.756,0,0,1-.756-.774V6.253c0-3.043-1.68-4.723-4.723-4.723H6.253C3.2,1.53,1.53,3.21,1.53,6.253v7.5c0,3.043,1.68,4.714,4.723,4.714h7.493c3.052,0,4.723-1.68,4.723-4.714a.765.765,0,1,1,1.53,0C20,17.608,17.608,20,13.756,20ZM5.7,15.479a.765.765,0,0,1-.738-.791v-6.4a.757.757,0,0,1,.791-.731.766.766,0,0,1,.739.792V14.74a.765.765,0,0,1-.765.739ZM9.27,14.7V5.321a.765.765,0,1,1,1.53,0V14.7a.765.765,0,1,1-1.53,0Zm4.239-.009V11.7a.765.765,0,0,1,1.531,0v2.991a.765.765,0,0,1-1.531,0ZM9.27,5.277v.044Z"
fill={color}
/>
</G>
);
const TwoTone = () => (
<G transform="translate(2 2)">
<Path
d="M.476,0V6.86"
transform="translate(4.895 8.202)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
opacity={opacity}
/>
<Path
d="M.476,0V10.143"
transform="translate(9.562 4.919)"
fill="none"
stroke={secondaryColor}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
opacity={opacity}
/>
<Path
d="M.476,0V3.235"
transform="translate(14.152 11.827)"
fill="none"
stroke={secondaryColor}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
opacity={opacity}
/>
<Path
d="M14.686,0H5.314C2.048,0,0,2.312,0,5.585v8.83C0,17.688,2.038,20,5.314,20h9.371C17.962,20,20,17.688,20,14.415V5.585C20,2.312,17.962,0,14.686,0Z"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
</G>
);
const Curved = () => (
<G transform="translate(2.3 2.3)">
<Path
d="M.526,0V6.694"
transform="translate(4.657 7.961)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
<Path
d="M.526,0V9.9"
transform="translate(9.211 4.757)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
<Path
d="M.526,0V3.157"
transform="translate(13.689 11.498)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
<Path
d="M0,9.737C0,2.435,2.435,0,9.737,0s9.737,2.435,9.737,9.737-2.435,9.737-9.737,9.737S0,17.039,0,9.737Z"
transform="translate(0 0)"
fill="none"
stroke={color}
strokeLinecap="round"
strokeLinejoin="round"
strokeMiterlimit="10"
strokeWidth={strokeWidth}
/>
</G>
);
switch (set) {
case 'bold':
return <Bold />;
case 'bulk':
return <Bulk />;
case 'broken':
return <Broken />;
case 'two-tone':
return <TwoTone />;
case 'curved':
return <Curved />;
default:
return <Light />;
}
};
Chart.displayName = 'IconlyChart';
export default withIcon(Chart);
|
package org.ednovo.gooru.core.api.model;
import java.io.Serializable;
public class OrganizationDomainAssoc extends OrganizationModel {
/**
*
*/
private static final long serialVersionUID = -2837330304486624576L;
private Idp domain;
public void setDomain(Idp domain) {
this.domain = domain;
}
public Idp getDomain() {
return domain;
}
}
|
<filename>src/flux/reducers/comparisonreport.js
import C from '../actions/constants';
export default function (state = {}, action) {
switch (action.type) {
case C.FETCH_COMPARISON_REPORT:
if (action.payload && Array.isArray(action.payload)) {
let data_arr = []
action.payload.map((data, index) => {
if (data.model_name) {
data_arr.push(data)
}
return true;
})
return data_arr
}
return action.payload;
default:
return state;
}
}
|
#!/usr/bin/env bash
FZF_DEFAULT_OPTS=$(echo $FZF_DEFAULT_OPTS | sed -r -e '$a --header="select a key binding"')
CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ "$TMUX_FZF_OPTIONS"x == ""x ]]; then
TARGET_ORIGIN=$(tmux list-keys | sed '1i [cancel]' | "$CURRENT_DIR/.fzf-tmux")
else
TARGET_ORIGIN=$(tmux list-keys | sed '1i [cancel]' | "$CURRENT_DIR/.fzf-tmux" "$TMUX_FZF_OPTIONS")
fi
if [[ "$TARGET_ORIGIN" == "[cancel]" ]]; then
exit
else
if [[ $(echo "$TARGET_ORIGIN" | grep -o "copy-mode")x != ""x && $(echo "$TARGET_ORIGIN" | grep -o "prefix")x == x ]]; then
tmux copy-mode
echo "$TARGET_ORIGIN" | sed -r 's/^.{46}//g' | xargs tmux
else
echo "$TARGET_ORIGIN" | sed -r 's/^.{46}//g' | xargs tmux
fi
fi
|
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Usage: $0 [/path/to/some/example.jar;/path/to/another/example/created.jar]
#
# accepts a single command line argument with a colon separated list of
# paths to jars to check. Iterates through each such passed jar and checks
# all the contained paths to make sure they follow the below constructed
# safe list.
# We use +=, which is a bash 3.1+ feature
if [[ -z "${BASH_VERSINFO[0]}" ]] \
|| [[ "${BASH_VERSINFO[0]}" -lt 3 ]] \
|| [[ "${BASH_VERSINFO[0]}" -eq 3 && "${BASH_VERSINFO[1]}" -lt 1 ]]; then
echo "bash v3.1+ is required. Sorry."
exit 1
fi
set -e
set -o pipefail
# we have to allow the directories that lead to the org/apache/hadoop dir
allowed_expr="(^org/$|^org/apache/$"
# We allow the following things to exist in our client artifacts:
# * classes in packages that start with org.apache.hadoop, which by
# convention should be in a path that looks like org/apache/hadoop
allowed_expr+="|^org/apache/hadoop/"
# * whatever in the "META-INF" directory
allowed_expr+="|^META-INF/"
# * whatever under the "webapps" directory; for things shipped by yarn
allowed_expr+="|^webapps/"
# * Hadoop's default configuration files, which have the form
# "_module_-default.xml"
allowed_expr+="|^[^-]*-default.xml$"
# * Hadoop's versioning properties files, which have the form
# "_module_-version-info.properties"
allowed_expr+="|^[^-]*-version-info.properties$"
# * Hadoop's application classloader properties file.
allowed_expr+="|^org.apache.hadoop.application-classloader.properties$"
# * Used by JavaSandboxLinuxContainerRuntime as a default, loaded
# from root, so can't relocate. :(
allowed_expr+="|^java.policy$"
# * allowing native libraries from rocksdb. Leaving native libraries as it is.
allowed_expr+="|^librocksdbjni-linux32.so"
allowed_expr+="|^librocksdbjni-linux64.so"
allowed_expr+="|^librocksdbjni-osx.jnilib"
allowed_expr+="|^librocksdbjni-win64.dll"
allowed_expr+="|^librocksdbjni-linux-ppc64le.so"
allowed_expr+=")"
declare -i bad_artifacts=0
declare -a bad_contents
declare -a artifact_list
while IFS='' read -r -d ';' line; do artifact_list+=("$line"); done < <(printf '%s;' "$1")
if [ "${#artifact_list[@]}" -eq 0 ]; then
echo "[ERROR] No artifacts passed in."
exit 1
fi
jar_list_failed ()
{
echo "[ERROR] Listing jar contents for file '${artifact}' failed."
exit 1
}
trap jar_list_failed SIGUSR1
for artifact in "${artifact_list[@]}"; do
# Note: On Windows the output from jar tf may contain \r\n's. Normalize to \n.
while IFS='' read -r line; do bad_contents+=("$line"); done < <( ( jar tf "${artifact}" | sed 's/\\r//' || kill -SIGUSR1 $$ ) | grep -v -E "${allowed_expr}" )
if [ ${#bad_contents[@]} -gt 0 ]; then
echo "[ERROR] Found artifact with unexpected contents: '${artifact}'"
echo " Please check the following and either correct the build or update"
echo " the allowed list with reasoning."
echo ""
for bad_line in "${bad_contents[@]}"; do
echo " ${bad_line}"
done
bad_artifacts=${bad_artifacts}+1
else
echo "[INFO] Artifact looks correct: '$(basename "${artifact}")'"
fi
done
if [ "${bad_artifacts}" -gt 0 ]; then
exit 1
fi
|
# -*- coding: utf-8 -*-
from src.file_oper import copy_celeba
from src.util import faceFromDir
CELEBA_IDENTITY_FILE = "datasets/celeba/identity_CelebA.txt"
CELEBA_DATASET = "datasets/celeba/img_align_celeba"
MIDDLE_DIR = "datasets/celeba/celeba_identified"
OUT_DIR = "datasets/celeba_aligned_bleed"
copy_celeba(CELEBA_IDENTITY_FILE, CELEBA_DATASET, MIDDLE_DIR)
SHAPE_MODEL = "models/shape_predictor_68_face_landmarks.dat"
faceFromDir(MIDDLE_DIR, OUT_DIR, SHAPE_MODEL)
|
def find_unique(str1, str2):
words1 = str1.split(' ')
words2 = str2.split(' ')
unique_words = []
for word1 in words1:
if word1 not in words2:
unique_words.append(word1)
for word2 in words2:
if word2 not in words1:
unique_words.append(word2)
return unique_words
unique_words = find_unique(str1, str2)
print(unique_words)
|
#!/bin/sh
set -e
image="${namespace:-minidocks}/perl"
versions="
5
latest
"
build() {
IFS=" "
docker buildx build $docker_opts -t "$image:$1" "$(dirname $0)"
}
case "$1" in
--versions) echo "$versions" | awk 'NF' | cut -d';' -f1;;
'') echo "$versions" | grep -v "^$" | while read -r version; do IFS=';'; build $version; done;;
*) args="$(echo "$versions" | grep -E "^$1(;|$)")"; if [ -n "$args" ]; then IFS=';'; build $args; else echo "Version $1 does not exist." >/dev/stderr; exit 1; fi
esac
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.