text
stringlengths 3
1.05M
|
---|
/**
* Contains all the value services that will be used in the app
*/
module.exports = [{
name: 'GameResultEnum',
type: 'value',
service: {
Win: {
value: 'W',
label: 'Win'
},
Draw: {
value: 'D',
label: 'Draw'
},
Loss: {
value: 'L',
label: 'Loss'
}
}
}]; |
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { get, isEqual } from 'lodash';
import { keyCodes, EuiFlexGroup, EuiFlexItem, EuiButton, EuiText, EuiSwitch } from '@elastic/eui';
import { getVisualizeLoader } from 'ui/visualize/loader/visualize_loader';
import { FormattedMessage, injectI18n } from '@kbn/i18n/react';
import {
getInterval,
convertIntervalIntoUnit,
isAutoInterval,
isGteInterval,
AUTO_INTERVAL,
} from './lib/get_interval';
import { PANEL_TYPES } from '../../common/panel_types';
const MIN_CHART_HEIGHT = 250;
class VisEditorVisualizationUI extends Component {
constructor(props) {
super(props);
this.state = {
height: MIN_CHART_HEIGHT,
dragging: false,
panelInterval: 0,
};
this._visEl = React.createRef();
this._subscription = null;
}
handleMouseDown = () => {
window.addEventListener('mouseup', this.handleMouseUp);
this.setState({ dragging: true });
};
handleMouseUp = () => {
window.removeEventListener('mouseup', this.handleMouseUp);
this.setState({ dragging: false });
};
handleMouseMove = event => {
if (this.state.dragging) {
this.setState(prevState => ({
height: Math.max(MIN_CHART_HEIGHT, prevState.height + event.movementY),
}));
}
};
async _loadVisualization() {
const loader = await getVisualizeLoader();
if (!this._visEl.current) {
// In case the visualize loader isn't done before the component is unmounted.
return;
}
const { uiState, timeRange, appState, savedObj, onDataChange } = this.props;
this._handler = loader.embedVisualizationWithSavedObject(this._visEl.current, savedObj, {
listenOnChange: false,
uiState,
timeRange,
appState,
});
this._subscription = this._handler.data$.subscribe(data => {
this.setPanelInterval(data.visData);
onDataChange(data);
});
}
setPanelInterval(visData) {
const panelInterval = getInterval(visData, this.props.model);
if (this.state.panelInterval !== panelInterval) {
this.setState({ panelInterval });
}
}
/**
* Resize the chart height when pressing up/down while the drag handle
* for resizing has the focus.
* We use 15px steps to do the scaling and make sure the chart has at least its
* defined minimum width (MIN_CHART_HEIGHT).
*/
onSizeHandleKeyDown = ev => {
const { keyCode } = ev;
if (keyCode === keyCodes.UP || keyCode === keyCodes.DOWN) {
ev.preventDefault();
this.setState(prevState => {
const newHeight = prevState.height + (keyCode === keyCodes.UP ? -15 : 15);
return {
height: Math.max(MIN_CHART_HEIGHT, newHeight),
};
});
}
};
hasShowPanelIntervalValue() {
const type = get(this.props, 'model.type', '');
const interval = get(this.props, 'model.interval', AUTO_INTERVAL);
return (
[
PANEL_TYPES.METRIC,
PANEL_TYPES.TOP_N,
PANEL_TYPES.GAUGE,
PANEL_TYPES.MARKDOWN,
PANEL_TYPES.TABLE,
].includes(type) &&
(isAutoInterval(interval) || isGteInterval(interval))
);
}
getFormattedPanelInterval() {
const interval = convertIntervalIntoUnit(this.state.panelInterval, false);
return interval ? `${interval.unitValue}${interval.unitString}` : null;
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.handleMouseMove);
window.removeEventListener('mouseup', this.handleMouseUp);
if (this._handler) {
this._handler.destroy();
}
if (this._subscription) {
this._subscription.unsubscribe();
}
}
componentDidMount() {
window.addEventListener('mousemove', this.handleMouseMove);
this._loadVisualization();
}
componentDidUpdate(prevProps) {
if (this._handler && !isEqual(this.props.timeRange, prevProps.timeRange)) {
this._handler.update({
timeRange: this.props.timeRange,
});
}
}
render() {
const { dirty, autoApply, title, description, onToggleAutoApply, onCommit } = this.props;
const style = { height: this.state.height };
if (this.state.dragging) {
style.userSelect = 'none';
}
const panelInterval = this.hasShowPanelIntervalValue() && this.getFormattedPanelInterval();
let applyMessage = (
<FormattedMessage
id="tsvb.visEditorVisualization.changesSuccessfullyAppliedMessage"
defaultMessage="The latest changes have been applied."
/>
);
if (dirty) {
applyMessage = (
<FormattedMessage
id="tsvb.visEditorVisualization.changesHaveNotBeenAppliedMessage"
defaultMessage="The changes to this visualization have not been applied."
/>
);
}
if (autoApply) {
applyMessage = (
<FormattedMessage
id="tsvb.visEditorVisualization.changesWillBeAutomaticallyAppliedMessage"
defaultMessage="The changes will be automatically applied."
/>
);
}
const applyButton = (
<EuiFlexGroup className="tvbEditorVisualization__apply" alignItems="center">
<EuiFlexItem grow={true}>
<EuiSwitch
id="tsvbAutoApplyInput"
label={
<FormattedMessage
id="tsvb.visEditorVisualization.autoApplyLabel"
defaultMessage="Auto apply"
/>
}
checked={autoApply}
onChange={onToggleAutoApply}
/>
</EuiFlexItem>
{panelInterval && (
<EuiFlexItem grow={false}>
<EuiText color="default" size="xs">
<p>
<FormattedMessage
id="tsvb.visEditorVisualization.panelInterval"
defaultMessage="Interval: {panelInterval}"
values={{ panelInterval }}
/>
</p>
</EuiText>
</EuiFlexItem>
)}
<EuiFlexItem grow={false}>
<EuiText color={dirty ? 'default' : 'subdued'} size="xs">
<p>{applyMessage}</p>
</EuiText>
</EuiFlexItem>
{!autoApply && (
<EuiFlexItem grow={false}>
<EuiButton
iconType="play"
fill
size="s"
onClick={onCommit}
disabled={!dirty}
data-test-subj="applyBtn"
>
<FormattedMessage
id="tsvb.visEditorVisualization.applyChangesLabel"
defaultMessage="Apply changes"
/>
</EuiButton>
</EuiFlexItem>
)}
</EuiFlexGroup>
);
return (
<div>
<div
style={style}
className="tvbEditorVisualization"
data-shared-items-container
data-title={title}
data-description={description}
ref={this._visEl}
/>
<div className="tvbEditor--hideForReporting">
{applyButton}
<button
className="tvbEditorVisualization__draghandle"
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
onKeyDown={this.onSizeHandleKeyDown}
aria-label={this.props.intl.formatMessage({
id: 'tsvb.colorRules.adjustChartSizeAriaLabel',
defaultMessage: 'Press up/down to adjust the chart size',
})}
>
<i className="fa fa-ellipsis-h" />
</button>
</div>
</div>
);
}
}
VisEditorVisualizationUI.propTypes = {
model: PropTypes.object,
onCommit: PropTypes.func,
uiState: PropTypes.object,
onToggleAutoApply: PropTypes.func,
savedObj: PropTypes.object,
timeRange: PropTypes.object,
dirty: PropTypes.bool,
autoApply: PropTypes.bool,
appState: PropTypes.object,
};
export const VisEditorVisualization = injectI18n(VisEditorVisualizationUI);
|
import React from "react";
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import { createStackNavigator } from "@react-navigation/stack";
import { createDrawerNavigator} from '@react-navigation/drawer';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import COLORS from "./utils/COLORS";
import Profile from "./screens/Profile";
import Contact from "./screens/Contact";
import LogIn from "./screens/LogIn";
import Register from "./screens/Register";
import CustomDrawer from "./components/CustomDrawer";
import Foods from "./screens/Foods";
import Drinks from "./screens/Drinks";
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const Tab = createBottomTabNavigator();
const BottomTabs = () => {
return (
<Tab.Navigator screenOptions={({ route }) => ({
headerShown: false,
tabBarActiveTintColor: COLORS.orange,
tabBarInactiveTintColor: COLORS.greyDark,
tabBarStyle: { backgroundColor: COLORS.white },
})}>
<Tab.Screen
name="Foods"
component={Foods}
options={{
tabBarLabel: 'Yiyecekler',
tabBarIcon: (tabInfo) => (
<Ionicons
name="restaurant"
size={tabInfo.focused ? 26 : 20}
color={tabInfo.focused ? COLORS.orange : COLORS.greyDark}
/>
),
}} />
<Tab.Screen
name="Icecekler"
component={Drinks}
options={{
tabBarLabel: 'İçecekler',
tabBarIcon: (tabInfo) => (
<Ionicons
name="cafe"
size={tabInfo.focused ? 26 : 20}
color={tabInfo.focused ? COLORS.orange : COLORS.greyDark}
/>
),
}}/>
</Tab.Navigator>
);
}
const DrawerNavigator = () => {
return(
<Drawer.Navigator drawerContent={(props) => <CustomDrawer {...props} />} initialRouteName="Home" screenOptions={{
drawerStyle: {
backgroundColor: COLORS.white,
width: 200,
},
drawerActiveBackgroundColor: COLORS.greyLight2,
drawerActiveTintColor: COLORS.orange,
headerTitle: "",
headerTintColor: COLORS.greyDark,
headerPressColor: COLORS.orange,
}}>
<Drawer.Screen name="Home" component={BottomTabs} options={{
drawerIcon: ({focused, size}) => (
<Ionicons
name="home"
size={size}
color={focused ? COLORS.orange : COLORS.greyDark}
/>
),
drawerLabel: 'Ana Sayfa'
}}/>
<Drawer.Screen name="Profile" component={Profile} options={{
drawerIcon: ({focused, size}) => (
<Ionicons
name="person-circle"
size={size}
color={focused ? COLORS.orange : COLORS.greyDark}
/>
),
drawerLabel: 'Profil'
}}/>
<Drawer.Screen name="Contact" component={Contact} options={{
drawerIcon: ({focused, size}) => (
<Ionicons
name="call"
size={size}
color={focused ? COLORS.orange : COLORS.greyDark}
/>
),
drawerLabel: 'İletişim'
}}/>
</Drawer.Navigator>
);
}
const App = () => {
return (
<SafeAreaProvider>
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false,
}}
>
<Stack.Screen name="Login" component={LogIn}/>
<Stack.Screen name="Register" component={Register} />
<Stack.Screen name="App" component={DrawerNavigator}/>
</Stack.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
}
export default App; |
# coding=utf-8
import logging
import re
import types
import os
from ignore import ignore_list
from helpers import is_recent, get_plex_item_display_title, query_plex
from lib import Plex, get_intent
from config import config, IGNORE_FN
logger = logging.getLogger(__name__)
MI_KIND, MI_TITLE, MI_KEY, MI_DEEPER, MI_ITEM = 0, 1, 2, 3, 4
container_size_re = re.compile(ur'totalSize="(\d+)"')
def get_item(key):
item_id = int(key)
item_container = Plex["library"].metadata(item_id)
item = list(item_container)[0]
return item
def get_item_kind(item):
return type(item).__name__
PLEX_API_TYPE_MAP = {
"Show": "series",
"Season": "season",
"Episode": "episode",
"Movie": "movie",
}
def get_item_kind_from_rating_key(key):
item = get_item(key)
return PLEX_API_TYPE_MAP[get_item_kind(item)]
def get_item_thumb(item):
kind = get_item_kind(item)
if kind == "Episode":
return item.show.thumb
elif kind == "Section":
return item.art
return item.thumb
def get_items_info(items):
return items[0][MI_KIND], items[0][MI_DEEPER]
def get_kind(items):
return items[0][MI_KIND]
def get_section_size(key):
"""
quick query to determine the section size
:param key:
:return:
"""
size = None
url = "http://127.0.0.1:32400/library/sections/%s/all" % int(key)
use_args = {
"X-Plex-Container-Size": "0",
"X-Plex-Container-Start": "0"
}
response = query_plex(url, use_args)
matches = container_size_re.findall(response.content)
if matches:
size = int(matches[0])
return size
def get_items(key="recently_added", base="library", value=None, flat=False, add_section_title=False):
"""
try to handle all return types plex throws at us and return a generalized item tuple
"""
items = []
apply_value = None
if value:
if isinstance(value, types.ListType):
apply_value = value
else:
apply_value = [value]
result = getattr(Plex[base], key)(*(apply_value or []))
for item in result:
cls = getattr(getattr(item, "__class__"), "__name__")
if hasattr(item, "scanner"):
kind = "section"
elif cls == "Directory":
kind = "directory"
else:
kind = item.type
# only return items for our enabled sections
section_key = None
if kind == "section":
section_key = item.key
else:
if hasattr(item, "section_key"):
section_key = getattr(item, "section_key")
if section_key and section_key not in config.enabled_sections:
continue
if kind == "season":
# fixme: i think this case is unused now
if flat:
# return episodes
for child in item.children():
items.append(("episode", get_plex_item_display_title(child, "show", parent=item, add_section_title=add_section_title), int(item.rating_key),
False, child))
else:
# return seasons
items.append(("season", item.title, int(item.rating_key), True, item))
elif kind == "directory":
items.append(("directory", item.title, item.key, True, item))
elif kind == "section":
if item.type in ['movie', 'show']:
item.size = get_section_size(item.key)
items.append(("section", item.title, int(item.key), True, item))
elif kind == "episode":
items.append(
(kind, get_plex_item_display_title(item, "show", parent=item.season, parent_title=item.show.title, section_title=item.section.title,
add_section_title=add_section_title), int(item.rating_key), False, item))
elif kind in ("movie", "artist", "photo"):
items.append((kind, get_plex_item_display_title(item, kind, section_title=item.section.title, add_section_title=add_section_title),
int(item.rating_key), False, item))
elif kind == "show":
items.append((
kind, get_plex_item_display_title(item, kind, section_title=item.section.title, add_section_title=add_section_title), int(item.rating_key), True,
item))
return items
def get_recent_items():
"""
actually get the recent items, not limited like /library/recentlyAdded
:return:
"""
args = {
"sort": "addedAt:desc",
"X-Plex-Container-Start": "0",
"X-Plex-Container-Size": "%s" % config.max_recent_items_per_library
}
episode_re = re.compile(ur'ratingKey="(?P<key>\d+)"'
ur'.+?grandparentRatingKey="(?P<parent_key>\d+)"'
ur'.+?title="(?P<title>.*?)"'
ur'.+?grandparentTitle="(?P<parent_title>.*?)"'
ur'.+?index="(?P<episode>\d+?)"'
ur'.+?parentIndex="(?P<season>\d+?)".+?addedAt="(?P<added>\d+)"')
movie_re = re.compile(ur'ratingKey="(?P<key>\d+)".+?title="(?P<title>.*?)".+?addedAt="(?P<added>\d+)"')
available_keys = ("key", "title", "parent_key", "parent_title", "season", "episode", "added")
recent = []
for section in Plex["library"].sections():
if section.type not in ("movie", "show") \
or section.key not in config.enabled_sections \
or section.key in ignore_list.sections:
Log.Debug(u"Skipping section: %s" % section.title)
continue
use_args = args.copy()
if section.type == "show":
use_args["type"] = "4"
url = "http://127.0.0.1:32400/library/sections/%s/all" % int(section.key)
response = query_plex(url, use_args)
matcher = episode_re if section.type == "show" else movie_re
matches = [m.groupdict() for m in matcher.finditer(response.content)]
for match in matches:
data = dict((key, match[key] if key in match else None) for key in available_keys)
if section.type == "show" and data["parent_key"] in ignore_list.series:
Log.Debug(u"Skipping series: %s" % data["parent_title"])
continue
if data["key"] in ignore_list.videos:
Log.Debug(u"Skipping item: %s" % data["title"])
continue
if is_recent(int(data["added"])):
recent.append((int(data["added"]), section.type, section.title, data["key"]))
return recent
def get_on_deck_items():
return get_items(key="on_deck", add_section_title=True)
def get_recently_added_items():
return get_items(key="recently_added", add_section_title=True, flat=False)
def get_all_items(key, base="library", value=None, flat=False):
return get_items(key, base=base, value=value, flat=flat)
def is_ignored(rating_key, item=None):
"""
check whether an item, its show/season/section is in the soft or the hard ignore list
:param rating_key:
:param item:
:return:
"""
# item in soft ignore list
if rating_key in ignore_list["videos"]:
Log.Debug("Item %s is in the soft ignore list" % rating_key)
return True
item = item or get_item(rating_key)
kind = get_item_kind(item)
# show in soft ignore list
if kind == "Episode" and item.show.rating_key in ignore_list["series"]:
Log.Debug("Item %s's show is in the soft ignore list" % rating_key)
return True
# section in soft ignore list
if item.section.key in ignore_list["sections"]:
Log.Debug("Item %s's section is in the soft ignore list" % rating_key)
return True
# physical/path ignore
if config.ignore_sz_files or config.ignore_paths:
# normally check current item folder and the library
check_ignore_paths = [".", "../"]
if kind == "Episode":
# series/episode, we've got a season folder here, also
check_ignore_paths.append("../../")
for part in item.media.parts:
if config.ignore_paths and config.is_path_ignored(part.file):
Log.Debug("Item %s's path is manually ignored" % rating_key)
return True
if config.ignore_sz_files:
for sub_path in check_ignore_paths:
if config.is_physically_ignored(os.path.abspath(os.path.join(os.path.dirname(part.file), sub_path))):
Log.Debug("An ignore file exists in either the items or its parent folders")
return True
return False
def refresh_item(rating_key, force=False, timeout=8000, refresh_kind=None, parent_rating_key=None):
intent = get_intent()
# timeout actually is the time for which the intent will be valid
if force:
Log.Debug("Setting intent for force-refresh of %s to timeout: %s", rating_key, timeout)
intent.set("force", rating_key, timeout=timeout)
# force Dict.Save()
intent.store.save()
refresh = [rating_key]
if refresh_kind == "season":
# season refresh, needs explicit per-episode refresh
refresh = [item.rating_key for item in list(Plex["library/metadata"].children(int(rating_key)))]
for key in refresh:
Log.Info("%s item %s", "Refreshing" if not force else "Forced-refreshing", key)
Plex["library/metadata"].refresh(key)
|
var searchData=
[
['t_3407',['t',['../classQCPCurveData.html#aecc395525be28e9178a088793beb3ff3',1,'QCPCurveData']]],
['ticklabelcolor_3408',['tickLabelColor',['../classQCPAxisPainterPrivate.html#a88032cf15c997e3956b79617b859e8ad',1,'QCPAxisPainterPrivate']]],
['ticklabelfont_3409',['tickLabelFont',['../classQCPAxisPainterPrivate.html#a06cb4b185feb1e560e01d65887e4d80d',1,'QCPAxisPainterPrivate']]],
['ticklabelpadding_3410',['tickLabelPadding',['../classQCPAxisPainterPrivate.html#a264cfa080e84e536cf2d1ab9c5d5cc5f',1,'QCPAxisPainterPrivate']]],
['ticklabelrotation_3411',['tickLabelRotation',['../classQCPAxisPainterPrivate.html#ae6ade9232a8e400924009e8edca94bac',1,'QCPAxisPainterPrivate']]],
['ticklabels_3412',['tickLabels',['../classQCPAxisPainterPrivate.html#ad0a4998ca358ba751e84fca45a025abd',1,'QCPAxisPainterPrivate']]],
['ticklabelside_3413',['tickLabelSide',['../classQCPAxisPainterPrivate.html#a9d27f7625fcfbeb3a60193d0c18fc7e9',1,'QCPAxisPainterPrivate']]],
['ticklengthin_3414',['tickLengthIn',['../classQCPAxisPainterPrivate.html#ae7360ff805fc6097019de8b35ffbd7e7',1,'QCPAxisPainterPrivate']]],
['ticklengthout_3415',['tickLengthOut',['../classQCPAxisPainterPrivate.html#acbebb1f868906200f968627bc907b77d',1,'QCPAxisPainterPrivate']]],
['tickpen_3416',['tickPen',['../classQCPAxisPainterPrivate.html#a389dde97f02fdee23965e4736e7d8c62',1,'QCPAxisPainterPrivate']]],
['tickpositions_3417',['tickPositions',['../classQCPAxisPainterPrivate.html#ae55e3dc2cf2af8d8a6e7235ccab54786',1,'QCPAxisPainterPrivate']]],
['top_3418',['top',['../classQCPItemRect.html#a96e50db552fb297d6fb62614676217bc',1,'QCPItemRect::top()'],['../classQCPItemText.html#a5c87ee162cbbe3d166b97826c8849304',1,'QCPItemText::top()'],['../classQCPItemEllipse.html#ad50f907d6f9d1402c6c5d302dca5c5d5',1,'QCPItemEllipse::top()'],['../classQCPItemPixmap.html#af7a156590b1d59ab21b453c430c56a7c',1,'QCPItemPixmap::top()']]],
['topleft_3419',['topLeft',['../classQCPItemRect.html#aa70feeef173489b03c3fbe906a5023c4',1,'QCPItemRect::topLeft()'],['../classQCPItemText.html#a6354d8762182a3502103fabe5fbb8512',1,'QCPItemText::topLeft()'],['../classQCPItemEllipse.html#a12fd8420c06718d0c8a2303d6a652848',1,'QCPItemEllipse::topLeft()'],['../classQCPItemPixmap.html#a43c281ef6ad46f3cf04f365289abe51a',1,'QCPItemPixmap::topLeft()']]],
['topleftrim_3420',['topLeftRim',['../classQCPItemEllipse.html#a33ebd2a751b63b9240edc9aa46c19eff',1,'QCPItemEllipse']]],
['topright_3421',['topRight',['../classQCPItemRect.html#a77e0eb6e4aa6efee620d35e2c21bdad7',1,'QCPItemRect::topRight()'],['../classQCPItemText.html#ad18ac45cb4cc135de1eb78f2e86b6504',1,'QCPItemText::topRight()'],['../classQCPItemPixmap.html#a72eabd0010be41a4ec1b22aa983d2aa1',1,'QCPItemPixmap::topRight()']]],
['toprightrim_3422',['topRightRim',['../classQCPItemEllipse.html#a744446970b38a4a3bbea46d722b7c54d',1,'QCPItemEllipse']]],
['totalbounds_3423',['totalBounds',['../structQCPLabelPainterPrivate_1_1LabelData.html#af4843231109ed291e6d1801e355ea723',1,'QCPLabelPainterPrivate::LabelData::totalBounds()'],['../structQCPAxisPainterPrivate_1_1TickLabelData.html#afbb3163cf4c628914f1b703945419ea5',1,'QCPAxisPainterPrivate::TickLabelData::totalBounds()']]],
['transform_3424',['transform',['../structQCPLabelPainterPrivate_1_1LabelData.html#a5e53ca7c728fbbd6abaf66f9eba5186c',1,'QCPLabelPainterPrivate::LabelData']]],
['type_3425',['type',['../classQCPAxisPainterPrivate.html#ae04594e97417336933d807c86d353098',1,'QCPAxisPainterPrivate']]]
];
|
import React,{useState} from 'react';
import {useHistory} from 'react-router-dom';
import {TextField, InputLabel, MenuItem, FormControl, Select} from '@material-ui/core';
import SearchIcon from '@material-ui/icons/Search';
import useStyles from './styles'
const Search = () => {
const classes = useStyles();
const [location, setLocation] = useState('');
const [searchValue, setSearchValue] = useState('');
const history = useHistory();
const handleSubmit = async (e) => {
history.push(`/search-results?location=${location}&searchValue=${searchValue}`)
}
return (
<div>
<FormControl variant='filled' className={classes.formControl}>
<InputLabel style={{color: 'white'}}>Location</InputLabel>
<Select
value={location}
onChange={(e) => setLocation(e.target.value)}
label='Location'
style={{color: 'white'}}
>
<MenuItem value=''>
<em>None</em>
</MenuItem>
<MenuItem value={'Lucknow'}>Lucknow</MenuItem>
<MenuItem value={'Delhi'}>Delhi</MenuItem>
<MenuItem value={'Mumbai'}>Mumbai</MenuItem>
<MenuItem value={'Bangalore'}>Bangalore</MenuItem>
<MenuItem value={'Hyderabad'}>Hyderabad</MenuItem>
</Select>
</FormControl>
{/* <TextField
label='Search for a Service...'
variant='filled'
className={classes.root}
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
style={{color: 'white'}}
/> */}
<SearchIcon
style={{ fontSize: 44, marginLeft: '4px', marginTop: '5px', color: 'white', cursor: 'pointer' }}
onClick={handleSubmit}
/>
</div>
)
}
export default Search;
|
// Copyright (c) 2014-2019, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.
//
"use strict"
//
const View = require('../../Views/View.web')
const commonComponents_forms = require('../../MMAppUICommonComponents/forms.web')
const commonComponents_navigationBarButtons = require('../../MMAppUICommonComponents/navigationBarButtons.web')
//
const BaseView_AWalletWizardScreen = require('./BaseView_AWalletWizardScreen.web')
//
class CreateWallet_Instructions_View extends BaseView_AWalletWizardScreen
{
_setup_views()
{
const self = this
super._setup_views()
{
const div = document.createElement("div")
div.style.width = "236px"
div.style.margin = "38px auto 24px auto"
div.style.wordBreak = "break-word"
{
const titlesAndParagraphs = self._new_messages_titlesAndParagraphs()
titlesAndParagraphs.forEach(function(titleAndParagraph, i)
{
div.appendChild(self._new_messages_subheaderLayer(titleAndParagraph[0]))
div.appendChild(self._new_messages_paragraphLayer(titleAndParagraph[1]))
})
}
self.layer.appendChild(div)
}
{
const div = document.createElement("div")
div.style.backgroundColor = "#302D2F"
div.style.height = "1px"
div.style.width = "236px"
div.style.margin = "0 auto 20px auto"
self.layer.appendChild(div)
}
{
const centeringLayer = document.createElement("div")
centeringLayer.style.margin = "0 auto 24px auto"
centeringLayer.style.width = "236px"
const view = self._new_acceptCheckboxButtonView()
centeringLayer.appendChild(view.layer)
self.acceptCheckboxButtonView = view
self.layer.appendChild(centeringLayer)
}
}
_setup_startObserving()
{
const self = this
super._setup_startObserving()
}
//
//
// Lifecycle - Teardown
//
TearDown()
{
const self = this
super.TearDown()
}
//
//
// Runtime - Accessors - Factories
//
_new_messages_subheaderLayer(contentString)
{
const self = this
const layer = document.createElement("h3")
layer.innerHTML = contentString
layer.style.fontFamily = self.context.themeController.FontFamily_sansSerif()
layer.style.fontSize = "13px"
layer.style.lineHeight = "20px"
layer.style.fontWeight = "500"
layer.style.color = "#F8F7F8"
layer.style.marginTop = "24px"
return layer
}
_new_messages_paragraphLayer(contentString)
{
const self = this
const layer = document.createElement("p")
layer.innerHTML = contentString
layer.style.fontFamily = self.context.themeController.FontFamily_sansSerif()
layer.style.fontWeight = "normal"
layer.style.fontSize = "13px"
layer.style.color = "#8D8B8D"
layer.style.lineHeight = "20px"
return layer
}
_new_messages_titlesAndParagraphs()
{
const self = this
const list = []
list.push([
"Creating a wallet",
"Each Swap wallet gets a unique word-sequence called a mnemonic."
])
list.push([
"Write down your mnemonic",
"It's the only way to regain access, and <span style='text-decoration: underline;'>it's never sent to the server!</span>"
])
list.push([
"Keep it secret and safe",
"If you save it to an insecure location, copy, screenshot, or email it, it may be viewable by other apps."
])
list.push([
"Use it like an actual wallet",
"For large amounts and better privacy, make a cold-storage wallet or set your own server in Preferences."
])
if (self.context.isLiteApp == true) {
list.push([
"Web browsers are insecure",
"The convenience of MySwap for web comes at a security cost. <a href='https://xwp.one' target='_blank' style='color: #11bbec; cursor: pointer; -webkit-user-select: none; text-decoration: none;'>Download the desktop or mobile app</a>."
])
}
return list
}
_new_acceptCheckboxButtonView()
{
const self = this
const view = new View({ tag: "a" }, self.context)
{ // state
view.isChecked = false
}
{ // style
const layer = view.layer
layer.innerHTML = "GOT IT!"
layer.style.cursor = "default"
layer.style.position = "relative"
layer.style.textAlign = "left"
layer.style.display = "block"
layer.style.padding = "10px 12px"
layer.style.textIndent = `${37 - 12}px`
const isMacOS = process.platform === 'darwin' // TODO: check for iOS too I suppose
if (isMacOS) {
layer.style.width = "72px"
} else {
layer.style.width = "85px"
}
layer.style.height = `${32 - 10 * 2 }px`
self.context.themeController.StyleLayer_FontAsMessageBearingSmallLightMonospace(layer)
layer.style.color = "#f8f7f8"
layer.style.background = "#383638"
if (self.context.Views_selectivelyEnableMobileRenderingOptimizations !== true) {
layer.style.boxShadow = "0 0.5px 1px 0 #161416, inset 0 0.5px 0 0 #494749"
} else { // avoiding shadow
layer.style.boxShadow = "inset 0 0.5px 0 0 #494749"
}
layer.style.borderRadius = "3px"
}
var checkboxIconLayer;
{
const layer = document.createElement("div")
checkboxIconLayer = layer
layer.style.cursor = "default"
layer.style.position = "absolute"
layer.style.left = "9px"
layer.style.top = "9px"
layer.style.background = "#1d1b1d"
if (self.context.Views_selectivelyEnableMobileRenderingOptimizations !== true) {
layer.style.boxShadow = "0 0.5px 0 0 rgba(56,54,56,0.50), inset 0 0.5px 0 0 #161416"
} else { // avoiding shadow
layer.style.boxShadow = "inset 0 0.5px 0 0 #161416"
}
layer.style.borderRadius = "3px"
layer.style.width = "16px"
layer.style.height = "16px"
view.layer.appendChild(layer)
}
{ // methods
view.Component_ConfigureWithChecked = function()
{
if (view.isChecked) { // img path relative to window location
checkboxIconLayer.style.background = "#1d1b1d url("+self.context.crossPlatform_appBundledIndexRelativeAssetsRootPath+"WalletWizard/Resources/[email protected]) 3px 4px no-repeat"
checkboxIconLayer.style.backgroundSize = "10px 9px"
} else {
checkboxIconLayer.style.background = "#1d1b1d"
}
}
view.Component_ToggleChecked = function()
{
view.isChecked = !view.isChecked
view.Component_ConfigureWithChecked()
//
// this will need to be moved out to an event handler if this component is extracted
self._configureInteractivityOfNextButton()
}
}
{ // initial config via methods
view.Component_ConfigureWithChecked()
}
{ // observation
view.layer.addEventListener("click", function(e)
{
e.preventDefault()
view.Component_ToggleChecked()
return false
})
}
//
return view
}
//
//
// Runtime - Accessors - Navigation
//
Navigation_Title()
{
return "New Wallet"
}
Navigation_New_RightBarButtonView()
{
const self = this
const view = commonComponents_navigationBarButtons.New_RightSide_SaveButtonView(self.context)
self.rightBarButtonView = view
const layer = view.layer
layer.innerHTML = "Next"
layer.addEventListener(
"click",
function(e)
{
e.preventDefault()
{
if (self.isSubmitButtonDisabled !== true) { // button is enabled
self._userSelectedNextButton()
}
}
return false
}
)
self._configureInteractivityOfNextButton() // will be disabled on first push - but not necessarily on hitting Back
return view
}
Navigation_New_LeftBarButtonView()
{
const self = this
if (self.context.isLiteApp != true) {
return null // we want null or maybe a back button
}
// we need a cancel button
const view = commonComponents_navigationBarButtons.New_LeftSide_CancelButtonView(self.context)
const layer = view.layer
layer.addEventListener(
"click",
function(e)
{
e.preventDefault()
if (view.isEnabled !== false) {
self.wizardController._fromScreen_userPickedCancel()
}
return false
}
)
return view
}
//
//
// Runtime - Imperatives - Submit button enabled state
//
_configureInteractivityOfNextButton()
{
const self = this
if (self.acceptCheckboxButtonView.isChecked) {
self.enable_submitButton()
} else {
self.disable_submitButton()
}
}
disable_submitButton()
{
const self = this
if (self.isSubmitButtonDisabled !== true) {
self.isSubmitButtonDisabled = true
self.rightBarButtonView.SetEnabled(false)
}
}
enable_submitButton()
{
const self = this
if (self.isSubmitButtonDisabled !== false) {
self.isSubmitButtonDisabled = false
self.rightBarButtonView.SetEnabled(true)
}
}
//
//
// Runtime - Delegation - Interactions
//
_userSelectedNextButton()
{
const self = this
if (self.context.isLiteApp == true) { // must be set manually since we do not show the meta-info screen for this
self.wizardController.walletMeta_name = self.context.walletsListController.LiteAppWalletName()
self.wizardController.walletMeta_colorHexString = self.context.walletsListController.LiteAppWalletSwatchColor() // possibly change this to random color at some point
}
self.wizardController.GenerateAndUseNewWallet(
function(err, walletInstance)
{
if (err) {
throw err
}
self.wizardController.ProceedToNextStep()
}
// not specifying a locale here
)
}
//
//
// Runtime - Delegation - Navigation View special methods
//
navigationView_viewIsBeingPoppedFrom()
{
const self = this
// I don't always get popped but when I do I maintain correct state
self.wizardController.PatchToDifferentWizardTaskMode_withoutPushingScreen(
self.options.wizardController_current_wizardTaskModeName,
self.options.wizardController_current_wizardTaskMode_stepIdx - 1
)
}
}
module.exports = CreateWallet_Instructions_View
|
(function() {
var fn = function() {
(function(global) {
function now() {
return new Date();
}
var force = false;
if (typeof (window._bokeh_onload_callbacks) === "undefined" || force === true) {
window._bokeh_onload_callbacks = [];
window._bokeh_is_loading = undefined;
}
function run_callbacks() {
window._bokeh_onload_callbacks.forEach(function(callback) { callback() });
delete window._bokeh_onload_callbacks
console.info("Bokeh: all callbacks have finished");
}
function load_libs(js_urls, callback) {
window._bokeh_onload_callbacks.push(callback);
if (window._bokeh_is_loading > 0) {
console.log("Bokeh: BokehJS is being loaded, scheduling callback at", now());
return null;
}
if (js_urls == null || js_urls.length === 0) {
run_callbacks();
return null;
}
console.log("Bokeh: BokehJS not loaded, scheduling load and callback at", now());
window._bokeh_is_loading = js_urls.length;
for (var i = 0; i < js_urls.length; i++) {
var url = js_urls[i];
var s = document.createElement('script');
s.src = url;
s.async = false;
s.onreadystatechange = s.onload = function() {
window._bokeh_is_loading--;
if (window._bokeh_is_loading === 0) {
console.log("Bokeh: all BokehJS libraries loaded");
run_callbacks()
}
};
s.onerror = function() {
console.warn("failed to load library " + url);
};
console.log("Bokeh: injecting script tag for BokehJS library: ", url);
document.getElementsByTagName("head")[0].appendChild(s);
}
};var element = document.getElementById("c60d2bf2-34a9-439a-af76-a02d59679738");
if (element == null) {
console.log("Bokeh: ERROR: autoload.js configured with elementid 'c60d2bf2-34a9-439a-af76-a02d59679738' but no matching script tag was found. ")
return false;
}
var js_urls = ["https://cdn.bokeh.org/bokeh/release/bokeh-0.12.5.min.js", "https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.5.min.js", "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.js"];
var inline_js = [
function(Bokeh) {
Bokeh.set_log_level("info");
},
function(Bokeh) {
(function outer(modules, cache, entry) {
if (Bokeh != null) {
for (var name in modules) {
Bokeh.require.modules[name] = modules[name];
}
for (var i = 0; i < entry.length; i++) {
var plugin = Bokeh.require(entry[i]);
Bokeh.Models.register_models(plugin.models);
for (var name in plugin) {
if (name !== "models") {
Bokeh[name] = plugin[name];
}
}
}
} else {
throw new Error("Cannot find Bokeh. You have to load it prior to loading plugins.");
}
})
({
"custom/main": [function(require, module, exports) {
module.exports = {
models: {
"LatexLabel": require("custom/bk_script_a14de02787a54585be895bc685587404.latex_label").LatexLabel
}
};
}, {}],
"custom/bk_script_a14de02787a54585be895bc685587404.latex_label": [function(require, module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var extend = function (child, parent) { for (var key in parent) {
if (hasProp.call(parent, key))
child[key] = parent[key];
} function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty;
var label_1 = require("models/annotations/label");
exports.LatexLabelView = (function (superClass) {
extend(LatexLabelView, superClass);
function LatexLabelView() {
return LatexLabelView.__super__.constructor.apply(this, arguments);
}
LatexLabelView.prototype.render = function () {
var angle, ctx, panel_offset, sx, sy, vx, vy;
ctx = this.plot_view.canvas_view.ctx;
switch (this.model.angle_units) {
case "rad":
angle = -1 * this.model.angle;
break;
case "deg":
angle = -1 * this.model.angle * Math.PI / 180.0;
}
if (this.model.x_units === "data") {
vx = this.xmapper.map_to_target(this.model.x);
}
else {
vx = this.model.x;
}
sx = this.canvas.vx_to_sx(vx);
if (this.model.y_units === "data") {
vy = this.ymapper.map_to_target(this.model.y);
}
else {
vy = this.model.y;
}
sy = this.canvas.vy_to_sy(vy);
if (this.model.panel != null) {
panel_offset = this._get_panel_offset();
sx += panel_offset.x;
sy += panel_offset.y;
}
this._css_text(ctx, "", sx + this.model.x_offset, sy - this.model.y_offset, angle);
return katex.render(this.model.text, this.el, {
displayMode: true
});
};
return LatexLabelView;
})(label_1.LabelView);
exports.LatexLabel = (function (superClass) {
extend(LatexLabel, superClass);
function LatexLabel() {
return LatexLabel.__super__.constructor.apply(this, arguments);
}
LatexLabel.prototype.type = 'LatexLabel';
LatexLabel.prototype.default_view = exports.LatexLabelView;
return LatexLabel;
})(label_1.Label);
}, {}]
}, {}, ["custom/main"]);
},
function(Bokeh) {
(function() {
var fn = function() {
Bokeh.safely(function() {
var docs_json = {"9f5b533e-d4c9-46ef-985a-1985e9e7d236":{"roots":{"references":[{"attributes":{"line_color":{"value":"#1f77b4"},"x":{"field":"x"},"y":{"field":"y"}},"id":"35c7585c-3a99-4784-9a21-302498bea416","type":"Line"},{"attributes":{"below":[{"id":"0cf29300-277e-4dbb-a93a-c13af5f1e0f4","type":"LinearAxis"}],"left":[{"id":"02d16df8-f7cb-4bb4-9e35-7e184be3fc12","type":"LinearAxis"}],"plot_height":500,"plot_width":500,"renderers":[{"id":"0cf29300-277e-4dbb-a93a-c13af5f1e0f4","type":"LinearAxis"},{"id":"54059f05-10f6-458c-ad7f-58cc47d7abf3","type":"Grid"},{"id":"02d16df8-f7cb-4bb4-9e35-7e184be3fc12","type":"LinearAxis"},{"id":"1e728527-6b25-4200-9548-68c8401b6f25","type":"Grid"},{"id":"fdb345a9-5ce8-41c5-9c6a-9c9a82f10986","type":"BoxAnnotation"},{"id":"f987fe3d-ce9c-4057-8361-8a910cb6807e","type":"GlyphRenderer"},{"id":"d65b150a-4a98-4050-a981-3b54727bb46a","type":"LatexLabel"}],"title":{"id":"ba59dcb9-6019-4456-812f-af005b63156d","type":"Title"},"tool_events":{"id":"9a4b3017-3949-4cd6-ae3b-cb435bb04c42","type":"ToolEvents"},"toolbar":{"id":"ed8ac513-a137-4de9-ba1a-8b81dfc403a4","type":"Toolbar"},"x_range":{"id":"54ca7c90-022d-40e5-8353-59700bc11ec7","type":"DataRange1d"},"y_range":{"id":"303f13d6-441a-46d6-a26d-4d3c2d294ff8","type":"DataRange1d"}},"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"},{"attributes":{"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"}},"id":"0b1ff54c-4c5b-47dc-8b16-dd49fb9ce3a0","type":"SaveTool"},{"attributes":{"overlay":{"id":"fdb345a9-5ce8-41c5-9c6a-9c9a82f10986","type":"BoxAnnotation"},"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"}},"id":"b3edb671-0695-4bdb-a3fa-87e10dd53c65","type":"BoxZoomTool"},{"attributes":{"line_alpha":{"value":0.1},"line_color":{"value":"#1f77b4"},"x":{"field":"x"},"y":{"field":"y"}},"id":"5259e359-30dd-4798-9ccf-c4ac245e81e7","type":"Line"},{"attributes":{"formatter":{"id":"9d426af2-3080-4313-a546-3e72a04f3ba1","type":"BasicTickFormatter"},"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"},"ticker":{"id":"3ab1ffe4-31ee-453f-84eb-f8dcd61d7400","type":"BasicTicker"}},"id":"02d16df8-f7cb-4bb4-9e35-7e184be3fc12","type":"LinearAxis"},{"attributes":{"bottom_units":"screen","fill_alpha":{"value":0.5},"fill_color":{"value":"lightgrey"},"left_units":"screen","level":"overlay","line_alpha":{"value":1.0},"line_color":{"value":"black"},"line_dash":[4,4],"line_width":{"value":2},"plot":null,"render_mode":"css","right_units":"screen","top_units":"screen"},"id":"fdb345a9-5ce8-41c5-9c6a-9c9a82f10986","type":"BoxAnnotation"},{"attributes":{"data_source":{"id":"b7ea16d9-d2c2-4fcc-955a-07c3f6a5b4ae","type":"ColumnDataSource"},"glyph":{"id":"35c7585c-3a99-4784-9a21-302498bea416","type":"Line"},"hover_glyph":null,"muted_glyph":null,"nonselection_glyph":{"id":"5259e359-30dd-4798-9ccf-c4ac245e81e7","type":"Line"},"selection_glyph":null},"id":"f987fe3d-ce9c-4057-8361-8a910cb6807e","type":"GlyphRenderer"},{"attributes":{"callback":null},"id":"54ca7c90-022d-40e5-8353-59700bc11ec7","type":"DataRange1d"},{"attributes":{"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"},"ticker":{"id":"3642232b-26f4-4bc7-9060-2d1f11d74991","type":"BasicTicker"}},"id":"54059f05-10f6-458c-ad7f-58cc47d7abf3","type":"Grid"},{"attributes":{"callback":null,"column_names":["x","y"],"data":{"x":{"__ndarray__":"AAAAAAAAAAB7FK5H4XqEP3sUrkfhepQ/uB6F61G4nj97FK5H4XqkP5qZmZmZmak/uB6F61G4rj/sUbgeheuxP3sUrkfherQ/CtejcD0Ktz+amZmZmZm5Pylcj8L1KLw/uB6F61G4vj+kcD0K16PAP+xRuB6F68E/MzMzMzMzwz97FK5H4XrEP8P1KFyPwsU/CtejcD0Kxz9SuB6F61HIP5qZmZmZmck/4XoUrkfhyj8pXI/C9SjMP3E9CtejcM0/uB6F61G4zj8AAAAAAADQP6RwPQrXo9A/SOF6FK5H0T/sUbgehevRP4/C9Shcj9I/MzMzMzMz0z/Xo3A9CtfTP3sUrkfhetQ/H4XrUbge1T/D9Shcj8LVP2dmZmZmZtY/CtejcD0K1z+uR+F6FK7XP1K4HoXrUdg/9ihcj8L12D+amZmZmZnZPz4K16NwPdo/4XoUrkfh2j+F61G4HoXbPylcj8L1KNw/zczMzMzM3D9xPQrXo3DdPxWuR+F6FN4/uB6F61G43j9cj8L1KFzfPwAAAAAAAOA/UrgehetR4D+kcD0K16PgP/YoXI/C9eA/SOF6FK5H4T+amZmZmZnhP+xRuB6F6+E/PgrXo3A94j+PwvUoXI/iP+F6FK5H4eI/MzMzMzMz4z+F61G4HoXjP9ejcD0K1+M/KVyPwvUo5D97FK5H4XrkP83MzMzMzOQ/H4XrUbge5T9xPQrXo3DlP8P1KFyPwuU/Fa5H4XoU5j9nZmZmZmbmP7gehetRuOY/CtejcD0K5z9cj8L1KFznP65H4XoUruc/AAAAAAAA6D9SuB6F61HoP6RwPQrXo+g/9ihcj8L16D9I4XoUrkfpP5qZmZmZmek/7FG4HoXr6T8+CtejcD3qP5DC9Shcj+o/4XoUrkfh6j8zMzMzMzPrP4XrUbgehes/16NwPQrX6z8pXI/C9SjsP3sUrkfheuw/zczMzMzM7D8fhetRuB7tP3E9CtejcO0/w/UoXI/C7T8VrkfhehTuP2dmZmZmZu4/uB6F61G47j8K16NwPQrvP1yPwvUoXO8/rkfhehSu7z8AAAAAAADwPw==","dtype":"float64","shape":[101]},"y":{"__ndarray__":"AAAAAAAACEBBNiDV2e8HQLgHRIeovwdAudZ7py5wB0AWcKATrQIHQCr95ebdeAZABq70gO3UBUBvQK2/cRkFQNQKBo9fSQRANLAk+f5nA0Aq/eXm3XgCQKg3UMbBfwFAnATfUJiAAEDI9kFez/7+P7CQX3N8AP0/rAU0MkQO+z+Zn7YNAjD5P1bq8+FAbfc/In+lgBzN9T/2oxb+JFb0P6wFNDJEDvM/1B+/2KX68T+OUgixoh/xP5Dwd/GugPA/f5O/VUwg8D8AAAAAAADwP36Tv1VMIPA/kPB38a6A8D+OUgixoh/xP9Mfv9il+vE/rAU0MkQO8z/1oxb+JFb0PyN/pYAczfU/Werz4UBt9z+bn7YNAjD5P6wFNDJEDvs/sZBfc3wA/T/J9kFez/7+P5sE31CYgABApzdQxsF/AUAq/eXm3XgCQDOwJPn+ZwNA0woGj19JBEBuQK2/cRkFQAWu9IDt1AVAKv3l5t14BkAWcKATrQIHQLnWe6cucAdAuAdEh6i/B0BANiDV2e8HQAAAAAAAAAhAQTYg1dnvB0C4B0SHqL8HQLnWe6cucAdAFnCgE60CB0Ap/eXm3XgGQASu9IDt1AVAb0Ctv3EZBUDWCgaPX0kEQDSwJPn+ZwNAK/3l5t14AkCoN1DGwX8BQJwE31CYgABAy/ZBXs/+/j+vkF9zfAD9P64FNDJEDvs/lp+2DQIw+T9Y6vPhQG33Px5/pYAczfU/9KMW/iRW9D+tBTQyRA7zP9Yfv9il+vE/jlIIsaIf8T+Q8HfxroDwP36Tv1VMIPA/AAAAAAAA8D9+k79VTCDwP5Dwd/GugPA/jFIIsaIf8T/UH7/YpfrxP6sFNDJEDvM/96MW/iRW9D8if6WAHM31P1zq8+FAbfc/k5+2DQIw+T+qBTQyRA77P6yQX3N8AP0/yPZBXs/+/j+aBN9QmIAAQKg3UMbBfwFAKf3l5t14AkA1sCT5/mcDQNQKBo9fSQRAcECtv3EZBUAGrvSA7dQFQCn95ebdeAZAFXCgE60CB0C51nunLnAHQLgHRIeovwdAQTYg1dnvB0AAAAAAAAAIQA==","dtype":"float64","shape":[101]}}},"id":"b7ea16d9-d2c2-4fcc-955a-07c3f6a5b4ae","type":"ColumnDataSource"},{"attributes":{"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"}},"id":"882297ae-5716-4b80-9325-24a2b3f033c0","type":"HelpTool"},{"attributes":{"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"}},"id":"b21a79e6-66cc-4ba6-82b9-091917713218","type":"WheelZoomTool"},{"attributes":{},"id":"9a4b3017-3949-4cd6-ae3b-cb435bb04c42","type":"ToolEvents"},{"attributes":{"callback":null},"id":"303f13d6-441a-46d6-a26d-4d3c2d294ff8","type":"DataRange1d"},{"attributes":{"active_drag":"auto","active_scroll":"auto","active_tap":"auto","tools":[{"id":"77b09f5c-e74b-4e99-ab76-1eec52f4bbea","type":"PanTool"},{"id":"b21a79e6-66cc-4ba6-82b9-091917713218","type":"WheelZoomTool"},{"id":"b3edb671-0695-4bdb-a3fa-87e10dd53c65","type":"BoxZoomTool"},{"id":"0b1ff54c-4c5b-47dc-8b16-dd49fb9ce3a0","type":"SaveTool"},{"id":"2d734e28-a794-4fb9-bdc4-5586ce50bd6e","type":"ResetTool"},{"id":"882297ae-5716-4b80-9325-24a2b3f033c0","type":"HelpTool"}]},"id":"ed8ac513-a137-4de9-ba1a-8b81dfc403a4","type":"Toolbar"},{"attributes":{},"id":"3642232b-26f4-4bc7-9060-2d1f11d74991","type":"BasicTicker"},{"attributes":{"background_fill_color":{"value":"#ffffff"},"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"},"render_mode":"css","text":"f = \\sum_{n=1}^\\infty\\frac{-e^{i\\pi}}{2^n}!","text_font_size":{"value":"16pt"},"x":35,"x_units":"screen","y":445,"y_units":"screen"},"id":"d65b150a-4a98-4050-a981-3b54727bb46a","type":"LatexLabel"},{"attributes":{"formatter":{"id":"d311c0b5-a4df-4502-9678-df716203b316","type":"BasicTickFormatter"},"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"},"ticker":{"id":"3642232b-26f4-4bc7-9060-2d1f11d74991","type":"BasicTicker"}},"id":"0cf29300-277e-4dbb-a93a-c13af5f1e0f4","type":"LinearAxis"},{"attributes":{"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"}},"id":"77b09f5c-e74b-4e99-ab76-1eec52f4bbea","type":"PanTool"},{"attributes":{"dimension":1,"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"},"ticker":{"id":"3ab1ffe4-31ee-453f-84eb-f8dcd61d7400","type":"BasicTicker"}},"id":"1e728527-6b25-4200-9548-68c8401b6f25","type":"Grid"},{"attributes":{},"id":"d311c0b5-a4df-4502-9678-df716203b316","type":"BasicTickFormatter"},{"attributes":{"plot":null,"text":"LaTex Demonstration"},"id":"ba59dcb9-6019-4456-812f-af005b63156d","type":"Title"},{"attributes":{"plot":{"id":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f","subtype":"Figure","type":"Plot"}},"id":"2d734e28-a794-4fb9-bdc4-5586ce50bd6e","type":"ResetTool"},{"attributes":{},"id":"3ab1ffe4-31ee-453f-84eb-f8dcd61d7400","type":"BasicTicker"},{"attributes":{},"id":"9d426af2-3080-4313-a546-3e72a04f3ba1","type":"BasicTickFormatter"}],"root_ids":["587e0f3f-ad76-4b7e-9e7e-1581272a8e3f"]},"title":"Bokeh Application","version":"0.12.5"}};
var render_items = [{"docid":"9f5b533e-d4c9-46ef-985a-1985e9e7d236","elementid":"c60d2bf2-34a9-439a-af76-a02d59679738","modelid":"587e0f3f-ad76-4b7e-9e7e-1581272a8e3f"}];
Bokeh.embed.embed_items(docs_json, render_items);
});
};
if (document.readyState != "loading") fn();
else document.addEventListener("DOMContentLoaded", fn);
})();
},
function(Bokeh) {
console.log("Bokeh: injecting CSS: https://cdn.bokeh.org/bokeh/release/bokeh-0.12.5.min.css");
Bokeh.embed.inject_css("https://cdn.bokeh.org/bokeh/release/bokeh-0.12.5.min.css");
console.log("Bokeh: injecting CSS: https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.5.min.css");
Bokeh.embed.inject_css("https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.5.min.css");
console.log("Bokeh: injecting CSS: https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.css");
Bokeh.embed.inject_css("https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.css");
}
];
function run_inline_js() {
for (var i = 0; i < inline_js.length; i++) {
inline_js[i](window.Bokeh);
}
}
if (window._bokeh_is_loading === 0) {
console.log("Bokeh: BokehJS loaded, going straight to plotting");
run_inline_js();
} else {
load_libs(js_urls, function() {
console.log("Bokeh: BokehJS plotting callback run at", now());
run_inline_js();
});
}
}(this));
};
if (document.readyState != "loading") fn();
else document.addEventListener("DOMContentLoaded", fn);
})();
|
import React from 'react';
import { StyleSheet, Dimensions, FlatList, View, Image } from 'react-native';
// Galio components
import { Block, Text, theme } from "galio-framework";
// Argon themed components
import { argonTheme } from "../constants";
import { Button } from "../components";
import Images from "../constants/Images";
import * as SQLite from "expo-sqlite";
import { SearchBar } from 'react-native-elements';
const db = SQLite.openDatabase("db.db");
const { width } = Dimensions.get('screen');
class GlobalSearch extends React.Component {
constructor(props) {
super(props);
//setting default state
this.state = { isLoading: true, search: '', subCondition: '', result_count: 0 };
this.arrayholder = [];
}
componentDidMount() {
db.transaction(tx => {
tx.executeSql('SELECT id, title, content FROM tbl_sub_condition_rows', [],
(txObj, { rows }) => {
if (rows.length > 0) {
let menuItem = [];
for (var i = 0; i < rows.length; i++) {
menuItem.push(rows.item(i));
}
this.setState(
{
isLoading: false,
menuItem: menuItem,
},
function () {
this.arrayholder = menuItem;
}
);
}
},
(txObj, error) => console.log('Error ', error)
)
})
}
search = text => {
console.log(text);
};
clear = () => {
this.search.clear();
this.setState({ displayResults: false })
};
_strCount(main_str, sub_str) {
main_str += '';
sub_str += '';
if (sub_str.length <= 0) {
return main_str.length + 1;
}
let subStr = sub_str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return (main_str.match(new RegExp(subStr, 'gi')) || []).length;
}
SearchFilterFunction(text) {
console.log(text);
this.setState({ displayResults: false })
if (text != '') { this.setState({ displayResults: true }) }
const newData = this.arrayholder.filter(function (item) {
const itemData = item.content ? item.content.toUpperCase() : ''.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
let summarizedResults = [];
for (var i = 0; i < newData.length; i++) {
summarizedResults.push({
"id": newData[i].id, "title": newData[i].title, "content": newData[i].content,
"title_count": this._strCount(newData[i].title, text), "content_count": this._strCount(newData[i].content, text)
});
}
summarizedResults.sort((a, b) => b.title_count - a.title_count);
this.setState({
menuItem: summarizedResults,
search: text, result_count: summarizedResults.length
});
}
_handleNavigation = (item) => {
this.props.navigation.push("DiseaseConditionDetail", {
condition_id: item.id,
condition_title: item.title,
condition_content: item.content,
condition_category: 'Diseases and Conditions',
});
}
ItemView = ({ item }) => {
const summary = item.title_count + item.content_count + ' matches found';
return (
<View>
<Text bold size={18} style={styles.title} onPress={() => {
this._handleNavigation(item);
}}>{item.title}</Text>
<Text muted style={styles.subtitle} onPress={() => {
this._handleNavigation(item);
}}>{summary}</Text>
</View>
);
}
ItemSeparatorView = () => {
return (
<View
style={{
height: 0.5,
width: '100%',
backgroundColor: '#C8C8C8',
}}
/>
);
}
render() {
return (
<Block flex style={styles.home}>
<View
style={{
top: 0,
width: '100%',
backgroundColor: '#1E1C24',
}}
>
<Text bold size={28} style={styles.header_title}>
Diseases and Conditions
</Text>
<Text muted size={15} style={styles.header_subtitle}>This is a muted paragraph.</Text>
</View>
<SearchBar
round
searchIcon={{ size: 24 }}
onChangeText={text => this.SearchFilterFunction(text)}
onClear={text => this.SearchFilterFunction('')}
placeholder="Type Here to Search"
value={this.state.search}
containerStyle={{ color: '#1E1C24', backgroundColor: '#1E1C24', foregroundColor: '#5E72E4' }}
/>{this.state.displayResults &&
<View>
<View
style={{
top: 0,
width: '100%',
backgroundColor: '#E1F5FE',
justifyContent: 'center',
alignItems: 'center'
}}
>
<Text muted size={15} style={{ textAlign: 'center', marginBottom: 8, marginTop: 8, marginHorizontal: 20, color: '#0D47A1' }}>Results found under Diseases and Conditions.</Text>
</View>
<FlatList
data={this.state.menuItem}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={this.ItemSeparatorView}
renderItem={this.ItemView}
/>
</View>
}
{!this.state.displayResults &&
<View
style={{
top: 0,
width: '100%',
height: '75%',
backgroundColor: '#FFFFFF',
justifyContent: 'center',
alignItems: 'center'
}}
>
<Image source={Images.icon_resources} style={{ alignSelf: 'center', marginTop: 20, marginBottom: 16, height: 64, width: 64 }} />
<Text bold size={16} style={{ textAlign: 'center', marginBottom: 8, marginHorizontal: 20, color: argonTheme.COLORS.HEADER }}>Quickly dig through thousands of our medicine, disease and condition information using the EDLIZ Smart Search. To search, simply type in the search box above.</Text>
<Block center>
<Button color="default" style={styles.button} onPress={() => { this.props.navigation.push("GlobalSearchMedicine"); }} >Search in Medicines Only</Button>
</Block>
</View>
}
</Block>
);
}
}
const styles = StyleSheet.create({
home: {
width: width,
backgroundColor: 'white',
},
articles: {
width: width - theme.SIZES.BASE * 2,
paddingVertical: theme.SIZES.BASE,
},
title: {
paddingHorizontal: theme.SIZES.BASE * 2,
marginTop: 10,
color: argonTheme.COLORS.HEADER
},
subtitle: {
paddingBottom: theme.SIZES.BASE,
paddingHorizontal: theme.SIZES.BASE * 2,
marginTop: 4,
color: argonTheme.COLORS.HEADER
},
header_title: {
paddingHorizontal: theme.SIZES.BASE * 1,
marginTop: 10,
color: '#FFFFFF'
},
header_subtitle: {
paddingBottom: theme.SIZES.BASE,
paddingHorizontal: theme.SIZES.BASE * 1,
marginTop: 4,
color: argonTheme.COLORS.ACTIVE
},
shadow: {
shadowColor: "black",
shadowOffset: { width: 0, height: 2 },
shadowRadius: 4,
shadowOpacity: 0.2,
elevation: 2
},
button: {
marginBottom: theme.SIZES.BASE,
width: 260
},
});
export default GlobalSearch;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var styled_icon_1 = require("@styled-icons/styled-icon");
exports.LogoutBoxR = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(styled_icon_1.StyledIconBase, tslib_1.__assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }),
React.createElement("path", { fill: "none", d: "M0 0h24v24H0z", key: "k0" }),
React.createElement("path", { d: "M5 22a1 1 0 01-1-1V3a1 1 0 011-1h14a1 1 0 011 1v3h-2V4H6v16h12v-2h2v3a1 1 0 01-1 1H5zm13-6v-3h-7v-2h7V8l5 4-5 4z", key: "k1" })));
});
exports.LogoutBoxR.displayName = 'LogoutBoxR';
exports.LogoutBoxRDimensions = { height: 24, width: 24 };
|
import { AppRegistry } from 'react-native'
import App from './App/Containers/App'
AppRegistry.registerComponent('AzureIoTDevKitCompanion', () => App)
|
import React from "react";
import { MDBContainer, MDBCol, MDBRow, MDBIcon} from "mdbreact";
import styled, { keyframes } from 'styled-components';
import "./HomePage.css";
import BoldCharacter from '../components/BoldCharacter';
import Col from '../components/Col';
import BrainCharacter from '../components/BrainCharacter';
import PenCharacter from '../components/PenCharacter';
import InternetCharacter from '../components/InternetCharacter';
import CleverBanner from '../components/CleverBanner';
import Wave from '../components/Wave';
import Email from '../components/Email';
import Comments from '../components/Comments';
import Form from '../components/Form';
import Button from '../components/Button';
import Text from '../components/Text';
import {WithData} from '../lib';
// import MaterialTable from "material-table";
class HomePage extends React.Component {
state = {
wave1:false,
wave2:false,
wave3:false,
wave4:false,
}
boltBackgroundRef = React.createRef();
addEvent = (messague) => console.log(messague);
toggleWave = (wave) => {
console.log("I was toggle");
this.setState({
...this.state,
[wave]:!this.state[wave]
});
}
render() {
return (
<div>
<MDBContainer>
<MDBRow
style={{padding:"5rem 0 2rem 0"}}
>
<MDBCol
sm="12"
md="6"
style={{
display: "flex",
justifyContent: "center",
flexDirection: "column",
}}
>
<h1><b>Drop us a line</b></h1>
<div className="grey-text">
<Form>
<Text onChangeHandle={this.change} id="name" iconName="user">Name</Text>
<Email id="sender" iconName="envelope">[email protected]</Email>
<Button submit>
Log In <MDBIcon far icon="paper-plane" className="ml-1" />
</Button>
</Form>
</div>
</MDBCol>
</MDBRow>
</MDBContainer>
</div>
);
}
}
export default WithData(HomePage);
|
!function(){var e,t;e=this,t=function(e,t){"use strict";const o=new t.Euler(0,0,0,"YXZ"),n=new t.Vector3,i={type:"change"},r={type:"lock"},c={type:"unlock"},s=Math.PI/2;class m extends t.EventDispatcher{constructor(e,m){super(),void 0===m&&(console.warn('THREE.PointerLockControls: The second parameter "domElement" is now mandatory.'),m=document.body),this.domElement=m,this.isLocked=!1,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.pointerSpeed=1;const d=this;function u(t){if(!1===d.isLocked)return;const n=t.movementX||t.mozMovementX||t.webkitMovementX||0,r=t.movementY||t.mozMovementY||t.webkitMovementY||0;o.setFromQuaternion(e.quaternion),o.y-=.002*n*d.pointerSpeed,o.x-=.002*r*d.pointerSpeed,o.x=Math.max(s-d.maxPolarAngle,Math.min(s-d.minPolarAngle,o.x)),e.quaternion.setFromEuler(o),d.dispatchEvent(i)}function l(){d.domElement.ownerDocument.pointerLockElement===d.domElement?(d.dispatchEvent(r),d.isLocked=!0):(d.dispatchEvent(c),d.isLocked=!1)}function a(){console.error("THREE.PointerLockControls: Unable to use Pointer Lock API")}this.connect=function(){d.domElement.ownerDocument.addEventListener("mousemove",u),d.domElement.ownerDocument.addEventListener("pointerlockchange",l),d.domElement.ownerDocument.addEventListener("pointerlockerror",a)},this.disconnect=function(){d.domElement.ownerDocument.removeEventListener("mousemove",u),d.domElement.ownerDocument.removeEventListener("pointerlockchange",l),d.domElement.ownerDocument.removeEventListener("pointerlockerror",a)},this.dispose=function(){this.disconnect()},this.getObject=function(){return e},this.getDirection=function(){const o=new t.Vector3(0,0,-1);return function(t){return t.copy(o).applyQuaternion(e.quaternion)}}(),this.moveForward=function(t){n.setFromMatrixColumn(e.matrix,0),n.crossVectors(e.up,n),e.position.addScaledVector(n,t)},this.moveRight=function(t){n.setFromMatrixColumn(e.matrix,0),e.position.addScaledVector(n,t)},this.lock=function(){this.domElement.requestPointerLock()},this.unlock=function(){d.domElement.ownerDocument.exitPointerLock()},this.connect()}}e.PointerLockControls=m,Object.defineProperty(e,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).THREE=e["THREE-STD"]||{},e.THREE)}();
|
""" main file for quadrotor tracking with mpc ddp controller """
from ddp.ddp_functions import run_ddp, run_mpc_ddp
import matplotlib.pyplot as plt
import gym
import environments
import argparse
import numpy as np
import pdb
def main(args):
if args.env in environments.learned_models:
# TODO(rebecca) make this less manual
if args.env == 'LearnedPendulum-v0':
from environments.learned_pendulum import LearnedPendulumEnv
env = LearnedPendulumEnv(model_type='structure')
elif args.env == 'LearnedQuad-v0':
from environments.learned_quad import LearnedQuadEnv
env = LearnedQuadEnv(model_type='structure')
else:
raise RuntimeError('Do not recognized learned model %s ' % args.env)
else:
env = gym.make(args.env)
num_iter = env.num_iter
opt_time = 0.1 # how to split the mpc total time horizon
if args.test:
num_iter = 3
print('Running in test mode.')
# print('Using %s environment for %d iterations' % (args.env, num_iter))
costvec, u, x, xf = run_mpc_ddp(env, num_iter, opt_time)
env.plot(xf, x.T, u.T, costvec)
if not args.test:
plt.show()
if __name__ == "__main__":
# envs = ['MPC-DDP-Simple-Quad-v0']
# envs = ['MPC-DDP-Pendulum-v0']
envs = ['DDP-Pendulum-v0'] # slower than MPC-DDP-Pendulum-v0
# Parse Command Line Arguments
# e.g. python ddp_main.py --test
parser = argparse.ArgumentParser(description='Run DDP')
parser.add_argument('--test', action='store_true', help='Run as test')
parser.add_argument('--env', help='Which environment to use.', default=envs[0], choices=envs)
args = parser.parse_args()
main(args)
|
$(document).ready(function() {
// Скачивание
setInterval(function() {
// Изображения
$(".andropov_image__inner img").each(function() {
if (!$(this).hasClass("downloadbl")) {
var link = this.src;
link = link.split("/");
link.splice(4);
var fixed_link = "";
for (var i = 0; i < link.length; i++) {
fixed_link += link[i] + "/";
}
$(this)
.parent()
.parent()
.after(
"<a href='" +
fixed_link +
"' class='downloadbl_link'><p class='download_image' tagret='_blank'><svg class='icon icon--ui_download' width='20' height='20'><use xmlns:xlink='http://www.w3.org/1999/xlink' xlink:href='#ui_download'></use></svg></p></a>"
);
$(this).addClass("downloadbl");
}
});
if ($(".content--full").length) {
if ($(".content-footer__item--share").length) {
if (!$(".item_download").length) {
$(".content-footer__item--share").after(
"<div class='content-footer__item item_download lm-hidden'><div title='Скачать все изображения' class='v-download'><div class='v-download__button'><svg height='21' width='19' class='icon icon--ui_download'><use xlink:href='#ui_download'></use></svg></div></div></div>"
);
$(document).on("click", ".v-download", function() {
$(".downloadbl_link").each(function() {
if (
$(this)
.parent()
.hasClass("content-image")
) {
var href = $(this).attr("href");
console.log(href);
window.open(href, "_blank");
}
});
});
}
}
}
}, 1000);
if (
window.location.href.indexOf("leonardo.osnova.io") > -1 &&
window.location.href.indexOf("format") === -1
) {
var time = new Date().getTime() / 1000;
saveAs(window.location.href, time + ".png");
window.close();
}
});
|
!function(){function e(e){return e&&1==e.nodeType&&"false"===e.contentEditable}function t(t,n,r,i,o){function a(e,t){if(t=t||0,!e[0])throw"findAndReplaceDOMText cannot handle zero-length matches";var n=e.index;if(t>0){var r=e[t];if(!r)throw"Invalid capture group";n+=e[0].indexOf(r),e[0]=r}return[n,n+e[0].length,[e[0]]]}function s(t){var n;if(3===t.nodeType)return t.data;if(m[t.nodeName]&&!p[t.nodeName])return"";if(n="",e(t))return"\n";if((p[t.nodeName]||h[t.nodeName])&&(n+="\n"),t=t.firstChild)do n+=s(t);while(t=t.nextSibling);return n}function l(t,n,r){var i,o,a,s,l=[],c=0,u=t,d=n.shift(),f=0;e:for(;;){if((p[u.nodeName]||h[u.nodeName]||e(u))&&c++,3===u.nodeType&&(!o&&u.length+c>=d[1]?(o=u,s=d[1]-c):i&&l.push(u),!i&&u.length+c>d[0]&&(i=u,a=d[0]-c),c+=u.length),i&&o){if(u=r({startNode:i,startNodeIndex:a,endNode:o,endNodeIndex:s,innerNodes:l,match:d[2],matchIndex:f}),c-=o.length-s,i=null,o=null,l=[],d=n.shift(),f++,!d)break}else if(m[u.nodeName]&&!p[u.nodeName]||!u.firstChild){if(u.nextSibling){u=u.nextSibling;continue}}else if(!e(u)){u=u.firstChild;continue}for(;;){if(u.nextSibling){u=u.nextSibling;break}if(u.parentNode===t)break e;u=u.parentNode}}}function c(e){var t;if("function"!=typeof e){var n=e.nodeType?e:f.createElement(e);t=function(e,t){var r=n.cloneNode(!1);return r.setAttribute("data-mce-index",t),e&&r.appendChild(f.createTextNode(e)),r}}else t=e;return function(e){var n,r,i,o=e.startNode,a=e.endNode,s=e.matchIndex;if(o===a){var l=o;i=l.parentNode,e.startNodeIndex>0&&(n=f.createTextNode(l.data.substring(0,e.startNodeIndex)),i.insertBefore(n,l));var c=t(e.match[0],s);return i.insertBefore(c,l),e.endNodeIndex<l.length&&(r=f.createTextNode(l.data.substring(e.endNodeIndex)),i.insertBefore(r,l)),l.parentNode.removeChild(l),c}n=f.createTextNode(o.data.substring(0,e.startNodeIndex)),r=f.createTextNode(a.data.substring(e.endNodeIndex));for(var u=t(o.data.substring(e.startNodeIndex),s),d=[],p=0,m=e.innerNodes.length;m>p;++p){var h=e.innerNodes[p],g=t(h.data,s);h.parentNode.replaceChild(g,h),d.push(g)}var v=t(a.data.substring(0,e.endNodeIndex),s);return i=o.parentNode,i.insertBefore(n,o),i.insertBefore(u,o),i.removeChild(o),i=a.parentNode,i.insertBefore(v,a),i.insertBefore(r,a),i.removeChild(a),v}}var u,d,f,p,m,h,g=[],v=0;if(f=n.ownerDocument,p=o.getBlockElements(),m=o.getWhiteSpaceElements(),h=o.getShortEndedElements(),d=s(n)){if(t.global)for(;u=t.exec(d);)g.push(a(u,i));else u=d.match(t),g.push(a(u,i));return g.length&&(v=g.length,l(n,g,c(r))),v}}function n(e){function n(){function t(){o.statusbar.find("#next").disabled(!a(d+1).length),o.statusbar.find("#prev").disabled(!a(d-1).length)}function n(){e.windowManager.alert("Could not find the specified string.",function(){o.find("#find")[0].focus()})}var r,i={};r=tinymce.trim(e.selection.getContent({format:"text"}));var o=e.windowManager.open({layout:"flex",pack:"center",align:"center",onClose:function(){e.focus(),u.done()},onSubmit:function(e){var r,s,l,c;return e.preventDefault(),s=o.find("#case").checked(),c=o.find("#words").checked(),l=o.find("#find").value(),l.length?i.text==l&&i.caseState==s&&i.wholeWord==c?0===a(d+1).length?void n():(u.next(),void t()):(r=u.find(l,s,c),r||n(),o.statusbar.items().slice(1).disabled(0===r),t(),void(i={text:l,caseState:s,wholeWord:c})):(u.done(!1),void o.statusbar.items().slice(1).disabled(!0))},buttons:[{text:"Find",subtype:"primary",onclick:function(){o.submit()}},{text:"Replace",disabled:!0,onclick:function(){u.replace(o.find("#replace").value())||(o.statusbar.items().slice(1).disabled(!0),d=-1,i={})}},{text:"Replace all",disabled:!0,onclick:function(){u.replace(o.find("#replace").value(),!0,!0),o.statusbar.items().slice(1).disabled(!0),i={}}},{type:"spacer",flex:1},{text:"Prev",name:"prev",disabled:!0,onclick:function(){u.prev(),t()}},{text:"Next",name:"next",disabled:!0,onclick:function(){u.next(),t()}}],title:"Find and replace",items:{type:"form",padding:20,labelGap:30,spacing:10,items:[{type:"textbox",name:"find",size:40,label:"Find",value:r},{type:"textbox",name:"replace",size:40,label:"Replace with"},{type:"checkbox",name:"case",text:"Match case",label:" "},{type:"checkbox",name:"words",text:"Whole words",label:" "}]}})}function r(e){var t=e.getAttribute("data-mce-index");return"number"==typeof t?""+t:t}function i(n){var r,i;return i=e.dom.create("span",{"data-mce-bogus":1}),i.className="mce-match-marker",r=e.getBody(),u.done(!1),t(n,r,i,!1,e.schema)}function o(e){var t=e.parentNode;e.firstChild&&t.insertBefore(e.firstChild,e),e.parentNode.removeChild(e)}function a(t){var n,i=[];if(n=tinymce.toArray(e.getBody().getElementsByTagName("span")),n.length)for(var o=0;o<n.length;o++){var a=r(n[o]);null!==a&&a.length&&a===t.toString()&&i.push(n[o])}return i}function s(t){var n=d,r=e.dom;t=t!==!1,t?n++:n--,r.removeClass(a(d),"mce-match-marker-selected");var i=a(n);return i.length?(r.addClass(a(n),"mce-match-marker-selected"),e.selection.scrollIntoView(i[0]),n):-1}function l(t){var n=e.dom,r=t.parentNode;n.remove(t),n.isEmpty(r)&&n.remove(r)}function c(e){var t=r(e);return null!==t&&t.length>0}var u=this,d=-1;u.init=function(e){e.addMenuItem("searchreplace",{text:"Find and replace",shortcut:"Meta+F",onclick:n,separator:"before",context:"edit"}),e.addButton("searchreplace",{tooltip:"Find and replace",shortcut:"Meta+F",onclick:n}),e.addCommand("SearchReplace",n),e.shortcuts.add("Meta+F","",n)},u.find=function(e,t,n){e=e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),e=n?"\\b"+e+"\\b":e;var r=i(new RegExp(e,t?"g":"gi"));return r&&(d=-1,d=s(!0)),r},u.next=function(){var e=s(!0);-1!==e&&(d=e)},u.prev=function(){var e=s(!1);-1!==e&&(d=e)},u.replace=function(t,n,i){var s,f,p,m,h,g,v=d;for(n=n!==!1,p=e.getBody(),f=tinymce.grep(tinymce.toArray(p.getElementsByTagName("span")),c),s=0;s<f.length;s++){var b=r(f[s]);if(m=h=parseInt(b,10),i||m===d){for(t.length?(f[s].firstChild.nodeValue=t,o(f[s])):l(f[s]);f[++s];){if(m=parseInt(r(f[s]),10),m!==h){s--;break}l(f[s])}n&&v--}else h>d&&f[s].setAttribute("data-mce-index",h-1)}return e.undoManager.add(),d=v,n?(g=a(v+1).length>0,u.next()):(g=a(v-1).length>0,u.prev()),!i&&g},u.done=function(t){var n,i,a,s;for(i=tinymce.toArray(e.getBody().getElementsByTagName("span")),n=0;n<i.length;n++){var l=r(i[n]);null!==l&&l.length&&(l===d.toString()&&(a||(a=i[n].firstChild),s=i[n].firstChild),o(i[n]))}if(a&&s){var c=e.dom.createRng();return c.setStart(a,0),c.setEnd(s,s.data.length),t!==!1&&e.selection.setRng(c),c}}}tinymce.PluginManager.add("searchreplace",n)}(); |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import mezzanine.core.managers
import mezzanine.core.fields
import pari.article.mixins.admin_thumb
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Factoid',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('keywords_string', models.CharField(max_length=500, editable=False, blank=True)),
('title', models.CharField(max_length=500, verbose_name='Title')),
('slug', models.CharField(help_text='Leave blank to have the URL auto-generated from the title.', max_length=2000, null=True, verbose_name='URL', blank=True)),
('_meta_title', models.CharField(help_text='Optional title to be used in the HTML title tag. If left blank, the main title field will be used.', max_length=500, null=True, verbose_name='Title', blank=True)),
('description', models.TextField(verbose_name='Description', blank=True)),
('gen_description', models.BooleanField(default=True, help_text='If checked, the description will be automatically generated from content. Uncheck if you want to manually set a custom description.', verbose_name='Generate description')),
('created', models.DateTimeField(null=True, editable=False)),
('updated', models.DateTimeField(null=True, editable=False)),
('status', models.IntegerField(default=2, help_text='With Draft chosen, will only be shown for admin users on the site.', verbose_name='Status', choices=[(1, 'Draft'), (2, 'Published')])),
('publish_date', models.DateTimeField(help_text="With Published chosen, won't be shown until this time", null=True, verbose_name='Published from', blank=True)),
('expiry_date', models.DateTimeField(help_text="With Published chosen, won't be shown after this time", null=True, verbose_name='Expires on', blank=True)),
('short_url', models.URLField(null=True, blank=True)),
('in_sitemap', models.BooleanField(default=True, verbose_name='Show in sitemap')),
('image', mezzanine.core.fields.FileField(max_length=255, null=True, verbose_name='Image', blank=True)),
('external_link', models.CharField(max_length=100, blank=True)),
],
options={
'verbose_name': 'Factoid',
'verbose_name_plural': 'Factoids',
},
bases=(models.Model, pari.article.mixins.admin_thumb.AdminThumbMixin),
managers=[
(b'objects', mezzanine.core.managers.DisplayableManager()),
],
),
migrations.CreateModel(
name='Resource',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('keywords_string', models.CharField(max_length=500, editable=False, blank=True)),
('title', models.CharField(max_length=500, verbose_name='Title')),
('slug', models.CharField(help_text='Leave blank to have the URL auto-generated from the title.', max_length=2000, null=True, verbose_name='URL', blank=True)),
('_meta_title', models.CharField(help_text='Optional title to be used in the HTML title tag. If left blank, the main title field will be used.', max_length=500, null=True, verbose_name='Title', blank=True)),
('description', models.TextField(verbose_name='Description', blank=True)),
('gen_description', models.BooleanField(default=True, help_text='If checked, the description will be automatically generated from content. Uncheck if you want to manually set a custom description.', verbose_name='Generate description')),
('created', models.DateTimeField(null=True, editable=False)),
('updated', models.DateTimeField(null=True, editable=False)),
('status', models.IntegerField(default=2, help_text='With Draft chosen, will only be shown for admin users on the site.', verbose_name='Status', choices=[(1, 'Draft'), (2, 'Published')])),
('publish_date', models.DateTimeField(help_text="With Published chosen, won't be shown until this time", null=True, verbose_name='Published from', blank=True)),
('expiry_date', models.DateTimeField(help_text="With Published chosen, won't be shown after this time", null=True, verbose_name='Expires on', blank=True)),
('short_url', models.URLField(null=True, blank=True)),
('in_sitemap', models.BooleanField(default=True, verbose_name='Show in sitemap')),
('embed_source', models.CharField(max_length=100)),
('date', models.DateField(max_length=100, null=True, blank=True)),
('authors', models.TextField(max_length=200, null=True, verbose_name='Author', blank=True)),
('focus', models.TextField(max_length=1000, null=True, verbose_name='Focus', blank=True)),
('copyright', models.TextField(max_length=200, null=True, verbose_name='Copyright', blank=True)),
('thumbnail_url', models.TextField(help_text=b'Non editable field which will be auto-populated based on embed source', null=True, blank=True)),
('site', models.ForeignKey(editable=False, to='sites.Site')),
],
options={
'ordering': ('title',),
'verbose_name': 'Resource',
'verbose_name_plural': 'Resources',
},
managers=[
(b'objects', mezzanine.core.managers.DisplayableManager()),
],
),
migrations.AddField(
model_name='factoid',
name='resource',
field=models.ForeignKey(related_name='factoids', blank=True, to='resources.Resource', null=True),
),
migrations.AddField(
model_name='factoid',
name='site',
field=models.ForeignKey(editable=False, to='sites.Site'),
),
]
|
class TestProperty(object):
def __init__(self, name = "Default"):
self._x = None
self.name = name
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = value
def del_name(self):
del self.__name
name = property(get_name, set_name, del_name, "name's docstring")
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
def main():
"""
"""
testObj = TestProperty()
testObj.x = 10
val = testObj.x
testObj.name = "Pydev"
debugType = testObj.name
print('TEST SUCEEDED!')
if __name__ == '__main__':
main() |
import boto3
import botocore
import os
def run(event, _context):
""" save string API Key as SecureString """
graphql_api_key_key_path = os.environ.get('GRAPHQL_API_KEY_KEY_PATH')
print("graphql_api_key_key_path =", graphql_api_key_key_path)
graphql_api_key = _get_parameter(graphql_api_key_key_path)
if graphql_api_key:
_save_secure_parameter(graphql_api_key_key_path, graphql_api_key)
print("graphql_api_key saved as ssm SecureString")
return event
def _get_parameter(name: str) -> str:
try:
response = boto3.client('ssm').get_parameter(Name=name, WithDecryption=True)
value = response.get('Parameter').get('Value')
return value
except botocore.exceptions.ClientError:
return None
def _save_secure_parameter(name: str, key_id: str) -> bool:
try:
boto3.client('ssm').put_parameter(Name=name, Description='api key for graphql-api-url', Value=key_id, Type='SecureString', Overwrite=True)
return True
except botocore.exceptions.ClientError:
return False
# setup:
# export GRAPHQL_API_KEY_KEY_PATH='/all/stacks/steve-maintain-metadata/graphql-api-key'
# aws-vault exec testlibnd-superAdmin
# python -c 'from save_api_key_as_secure_string import *; test()'
def test():
""" test exection """
event = {}
event = run(event, {})
print("event = ", event)
|
(function() {
Dagaz.AI.AI_FRAME = 1000;
Dagaz.Model.showBlink = false;
var checkVersion = Dagaz.Model.checkVersion;
Dagaz.Model.checkVersion = function(design, name, value) {
if (name != "liuzi-chongqi-extension") {
checkVersion(design, name, value);
}
}
var checkGoals = Dagaz.Model.checkGoals;
Dagaz.AI.eval = function(design, params, board, player) {
var r = 0;
_.each(design.allPositions(), function(pos) {
var piece = board.getPiece(pos);
if (piece !== null) {
var v = 1;
if (piece.player != player) {
v = -v;
}
r += v;
}
});
return r;
}
var checkGoals = Dagaz.Model.checkGoals;
Dagaz.Model.checkGoals = function(design, board, player) {
var enemies = 0;
var friends = 0;
_.each(design.allPositions(), function(pos) {
var piece = board.getPiece(pos);
if (piece !== null) {
if (piece.player != player) {
enemies++;
} else {
friends++;
}
}
});
if (enemies < 1) {
return 1;
}
if (friends < 1) {
return -1;
}
return checkGoals(design, board, player);
}
Dagaz.AI.heuristic = function(ai, design, board, move) {
return move.actions.length;
}
var checkStep = function(design, board, player, pos, d, o, move) {
var p = design.navigate(player, pos, o);
if (p === null) return;
var piece = board.getPiece(p);
if (piece === null) return;
if (piece.player != player) return;
var q = design.navigate(player, p, o);
if (q !== null) {
piece = board.getPiece(q);
if ((piece !== null) && (piece.player == player)) return;
}
p = design.navigate(player, pos, d);
if (p === null) return;
piece = board.getPiece(p);
if (piece === null) return;
if (piece.player == player) return;
q = design.navigate(player, p, d);
if (q !== null) {
piece = board.getPiece(q);
if (piece !== null) return;
}
move.capturePiece(p);
}
var checkLeap = function(design, board, player, pos, d, o, move) {
var q = design.navigate(player, pos, o);
if (q !== null) {
var piece = board.getPiece(q);
if ((piece !== null) && (piece.player == player)) return;
}
var p = design.navigate(player, pos, d);
if (p === null) return;
piece = board.getPiece(p);
if (piece === null) return;
if (piece.player != player) return;
p = design.navigate(player, p, d);
if (p === null) return;
piece = board.getPiece(p);
if (piece === null) return;
if (piece.player == player) return;
q = design.navigate(player, p, d);
if (q !== null) {
piece = board.getPiece(q);
if (piece !== null) return;
}
move.capturePiece(p);
}
var checkDir = function(design, board, player, pos, dir) {
var p = design.navigate(player, pos, dir);
if (p === null) return false;
var piece = board.getPiece(p);
if (piece === null) return false;
if (piece.player == player) return false;
p = design.navigate(player, p, dir);
if (p === null) return true;
return board.getPiece(p) === null;
}
var checkMiddle = function(design, board, player, pos, d, o, move) {
if (!checkDir(design, board, player, pos, d)) return;
if (!checkDir(design, board, player, pos, o)) return;
var p = design.navigate(player, pos, d);
var q = design.navigate(player, pos, o);
if ((p === null) || (q === null)) return;
move.capturePiece(p);
move.capturePiece(q);
}
var CheckInvariants = Dagaz.Model.CheckInvariants;
Dagaz.Model.CheckInvariants = function(board) {
var design = Dagaz.Model.design;
_.each(board.moves, function(move) {
if (!move.isSimpleMove()) return;
var pos = move.actions[0][1][0];
var b = board.apply(move);
checkStep(design, b, board.player, pos, 0, 1, move);
checkStep(design, b, board.player, pos, 1, 0, move);
checkStep(design, b, board.player, pos, 2, 3, move);
checkStep(design, b, board.player, pos, 3, 2, move);
checkLeap(design, b, board.player, pos, 0, 1, move);
checkLeap(design, b, board.player, pos, 1, 0, move);
checkLeap(design, b, board.player, pos, 2, 3, move);
checkLeap(design, b, board.player, pos, 3, 2, move);
});
var c = 0;
_.each(design.allPositions(), function(pos) {
var piece = board.getPiece(pos);
if (piece === null) return;
if (piece.player != board.player) return;
c++;
});
if (c == 1) {
_.each(board.moves, function(move) {
if (!move.isSimpleMove()) return;
var pos = move.actions[0][1][0];
checkMiddle(design, board, board.player, pos, 0, 1, move);
checkMiddle(design, board, board.player, pos, 2, 3, move);
});
}
CheckInvariants(board);
}
})();
|
import React from 'react';
import ApiDocs from 'docs/src/modules/components/ApiDocs';
import mapApiTranslations, { parsePropsMarkdown } from 'docs/src/modules/utils/mapApiTranslations';
import jsonPageContent from './step-icon.json';
export default function Page({ pageContent }) {
return <ApiDocs pageContent={pageContent} />;
}
Page.getInitialProps = async () => {
const req1 = require.context('docs/translations', false, /component-descriptions.*.json$/);
const req2 = require.context('docs/translations', false, /prop-descriptions.*.json$/);
const req3 = require.context('docs/translations', false, /class-descriptions.*.json$/);
const componentDescription = mapApiTranslations(req1, 'StepIcon');
const propDescriptions = parsePropsMarkdown(mapApiTranslations(req2, 'StepIcon'));
const classDescriptions = mapApiTranslations(req3, 'StepIcon');
const pageContent = {
...jsonPageContent,
componentDescription,
propDescriptions,
classDescriptions,
};
return { pageContent };
};
|
"use strict"
const checkForSpam = function(str) {
const formatedString = str.toLowerCase();
return formatedString.includes('spam') || formatedString.includes('sale');
};
console.log(checkForSpam("Latest technology news"));
console.log(checkForSpam("JavaScript weekly newsletter"));
console.log(checkForSpam("Get best sale offers now!"));
console.log(checkForSpam("[SPAM] How to earn fast money?")); |
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import formControlState from '../FormControl/formControlState';
import useFormControl from '../FormControl/useFormControl';
import experimentalStyled from '../styles/experimentalStyled';
import capitalize from '../utils/capitalize';
import formHelperTextClasses, { getFormHelperTextUtilityClasses } from './formHelperTextClasses';
import useThemeProps from '../styles/useThemeProps';
const useUtilityClasses = (styleProps) => {
const { classes, contained, size, disabled, error, filled, focused, required } = styleProps;
const slots = {
root: [
'root',
disabled && 'disabled',
error && 'error',
size && `size${capitalize(size)}`,
contained && 'contained',
focused && 'focused',
filled && 'filled',
required && 'required',
],
};
return composeClasses(slots, getFormHelperTextUtilityClasses, classes);
};
const FormHelperTextRoot = experimentalStyled('p', {
name: 'MuiFormHelperText',
slot: 'Root',
overridesResolver: (props, styles) => {
const { styleProps } = props;
return {
...styles.root,
...(styleProps.size && styles[`size${capitalize(styleProps.size)}`]),
...(styleProps.contained && styles.contained),
...(styleProps.filled && styles.filled),
};
},
})(({ theme, styleProps }) => ({
color: theme.palette.text.secondary,
...theme.typography.caption,
textAlign: 'left',
marginTop: 3,
marginRight: 0,
marginBottom: 0,
marginLeft: 0,
[`&.${formHelperTextClasses.disabled}`]: {
color: theme.palette.text.disabled,
},
[`&.${formHelperTextClasses.error}`]: {
color: theme.palette.error.main,
},
...(styleProps.size === 'small' && {
marginTop: 4,
}),
...(styleProps.contained && {
marginLeft: 14,
marginRight: 14,
}),
}));
const FormHelperText = React.forwardRef(function FormHelperText(inProps, ref) {
const props = useThemeProps({ props: inProps, name: 'MuiFormHelperText' });
const {
children,
className,
component = 'p',
disabled,
error,
filled,
focused,
margin,
required,
variant,
...other
} = props;
const muiFormControl = useFormControl();
const fcs = formControlState({
props,
muiFormControl,
states: ['variant', 'size', 'disabled', 'error', 'filled', 'focused', 'required'],
});
const styleProps = {
...props,
component,
contained: fcs.variant === 'filled' || fcs.variant === 'outlined',
variant: fcs.variant,
size: fcs.size,
disabled: fcs.disabled,
error: fcs.error,
filled: fcs.filled,
focused: fcs.focused,
required: fcs.required,
};
const classes = useUtilityClasses(styleProps);
return (
<FormHelperTextRoot
as={component}
styleProps={styleProps}
className={clsx(classes.root, className)}
ref={ref}
{...other}
>
{children === ' ' ? (
// notranslate needed while Google Translate will not fix zero-width space issue
// eslint-disable-next-line react/no-danger
<span className="notranslate" dangerouslySetInnerHTML={{ __html: '​' }} />
) : (
children
)}
</FormHelperTextRoot>
);
});
FormHelperText.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*
* If `' '` is provided, the component reserves one line height for displaying a future message.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the helper text should be displayed in a disabled state.
*/
disabled: PropTypes.bool,
/**
* If `true`, helper text should be displayed in an error state.
*/
error: PropTypes.bool,
/**
* If `true`, the helper text should use filled classes key.
*/
filled: PropTypes.bool,
/**
* If `true`, the helper text should use focused classes key.
*/
focused: PropTypes.bool,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense']),
/**
* If `true`, the helper text should use required classes key.
*/
required: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard']),
};
export default FormHelperText;
|
import json
from urllib.parse import urlencode
from .oauth import OAuth1Test
class XingOAuth1Test(OAuth1Test):
backend_path = 'social_core.backends.xing.XingOAuth'
user_data_url = 'https://api.xing.com/v1/users/me.json'
expected_username = 'FooBar'
access_token_body = urlencode({
'access_token': 'foobar',
'token_type': 'bearer',
'user_id': '123456_abcdef',
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
'oauth_callback_confirmed': 'true'
})
user_data_body = json.dumps({
'users': [{
'id': '123456_abcdef',
'first_name': 'Foo',
'last_name': 'Bar',
'display_name': 'Foo Bar',
'page_name': 'Foo_Bar',
'permalink': 'https://www.xing.com/profile/Foo_Bar',
'gender': 'm',
'birth_date': {
'day': 12,
'month': 8,
'year': 1963
},
'active_email': '[email protected]',
'time_zone': {
'name': 'Europe/Copenhagen',
'utc_offset': 2.0
},
'premium_services': ['SEARCH', 'PRIVATEMESSAGES'],
'badges': ['PREMIUM', 'MODERATOR'],
'wants': 'Nothing',
'haves': 'Skills',
'interests': 'Foo Foo',
'organisation_member': 'ACM, GI',
'languages': {
'de': 'NATIVE',
'en': 'FLUENT',
'fr': None,
'zh': 'BASIC'
},
'private_address': {
'city': 'Foo',
'country': 'DE',
'zip_code': '20357',
'street': 'Bar',
'phone': '12|34|1234560',
'fax': '||',
'province': 'Foo',
'email': '[email protected]',
'mobile_phone': '12|3456|1234567'
},
'business_address': {
'city': 'Foo',
'country': 'DE',
'zip_code': '20357',
'street': 'Bar',
'phone': '12|34|1234569',
'fax': '12|34|1234561',
'province': 'Foo',
'email': '[email protected]',
'mobile_phone': '12|345|12345678'
},
'web_profiles': {
'qype': ['http://qype.de/users/foo'],
'google_plus': ['http://plus.google.com/foo'],
'blog': ['http://blog.example.org'],
'homepage': ['http://example.org', 'http://other-example.org']
},
'instant_messaging_accounts': {
'skype': 'foobar',
'googletalk': 'foobar'
},
'professional_experience': {
'primary_company': {
'name': 'XING AG',
'title': 'Softwareentwickler',
'company_size': '201-500',
'tag': None,
'url': 'http://www.xing.com',
'career_level': 'PROFESSIONAL_EXPERIENCED',
'begin_date': '2010-01',
'description': None,
'end_date': None,
'industry': 'AEROSPACE'
},
'non_primary_companies': [{
'name': 'Ninja Ltd.',
'title': 'DevOps',
'company_size': None,
'tag': 'NINJA',
'url': 'http://www.ninja-ltd.co.uk',
'career_level': None,
'begin_date': '2009-04',
'description': None,
'end_date': '2010-07',
'industry': 'ALTERNATIVE_MEDICINE'
}, {
'name': None,
'title': 'Wiss. Mitarbeiter',
'company_size': None,
'tag': 'OFFIS',
'url': 'http://www.uni.de',
'career_level': None,
'begin_date': '2007',
'description': None,
'end_date': '2008',
'industry': 'APPAREL_AND_FASHION'
}, {
'name': None,
'title': 'TEST NINJA',
'company_size': '201-500',
'tag': 'TESTCOMPANY',
'url': None,
'career_level': 'ENTRY_LEVEL',
'begin_date': '1998-12',
'description': None,
'end_date': '1999-05',
'industry': 'ARTS_AND_CRAFTS'
}],
'awards': [{
'name': 'Awesome Dude Of The Year',
'date_awarded': 2007,
'url': None
}]
},
'educational_background': {
'schools': [{
'name': 'Foo University',
'degree': 'MSc CE/CS',
'notes': None,
'subject': None,
'begin_date': '1998-08',
'end_date': '2005-02'
}],
'qualifications': ['TOEFLS', 'PADI AOWD']
},
'photo_urls': {
'large': 'http://www.xing.com/img/users/e/3/d/'
'f94ef165a.123456,1.140x185.jpg',
'mini_thumb': 'http://www.xing.com/img/users/e/3/d/'
'f94ef165a.123456,1.18x24.jpg',
'thumb': 'http://www.xing.com/img/users/e/3/d/'
'f94ef165a.123456,1.30x40.jpg',
'medium_thumb': 'http://www.xing.com/img/users/e/3/d/'
'f94ef165a.123456,1.57x75.jpg',
'maxi_thumb': 'http://www.xing.com/img/users/e/3/d/'
'f94ef165a.123456,1.70x93.jpg'
}
}]
})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
|
const zgRefc = document.querySelector('#customer_table');
fetch('https://loyalty-dot-techloft-173609.appspot.com/api/Customers')
.then(res => res.json())
.then(data => zgRefc.setData(data.data))
.catch(err => console.error('--- Error In Fetch Occurred ---', err));
function _exportDatasToCSV() {
const data = zgRefc.getData();
const csvData = Papa.unparse(data);
console.log('--- exporting data ----', data, csvData);
_downloadCSV('export-all.csv', csvData);
}
// Add event listener to button
reloadCBtn.addEventListener('click', () => {
zgRefc.refresh();
});
//ussd table
const zgRef = document.querySelector('#ussd-table');
fetch('https://loyalty-dot-techloft-173609.appspot.com/api/Registrations?filter=%7B%22where%22%3A%7B%22authenticated%22%3A%220%22%7D%2C%20%22order%22%3A%22id%20DESC%22%7D')
.then(res => res.json())
.then(data => zgRef.setData(data.data))
.catch(err => console.error('--- Error In Fetch Occurred ---', err));
function _exportDataToCSV() {
const data = zgRef.getData();
const csvData = Papa.unparse(data);
console.log('--- exporting data ----', data, csvData);
_downloadCSV('export-all.csv', csvData);
}
// use built in anchor tag functionality to download the csv through a blob
function _downloadCSV(fileName, data) {
const aRef = document.querySelector('#downloadAnchor');
let json = JSON.stringify(data),
blob = new Blob([data], {
type: "octet/stream"
}),
url = window.URL.createObjectURL(blob);
aRef.href = url;
aRef.download = fileName;
aRef.click();
window.URL.revokeObjectURL(url);
}
// zgRef.executeOnLoad(() => {
// Add event listener to button
reloadUBtn.addEventListener('click', () => {
zgRef.refresh();
});
// });
|
import config
import schemas
__all__ = ['api', 'config', 'crud', 'main', 'models', 'schemas', 'utils']
|
import React from 'react';
import { Container, Card, Col, Row } from 'react-bootstrap';
import { BsEnvelope } from 'react-icons/bs';
import { FiPhone } from 'react-icons/fi';
import { HiLink } from 'react-icons/hi'
function YourTeamCard({ user }) {
return (
<>
<Container>
<Card className='my-3 p-3 rounded' border='primary'>
<Card.Body>
<Row>
<Col xs={8} className='noPadding '>
<Card.Title>{user.accname}</Card.Title>
<Card.Text className='truncate'>
<BsEnvelope />: <a href={`mailto:${user.email}`}>{user.email}</a>
</Card.Text>
<Card.Text>
<FiPhone />: {user.contact || "N/A"}
</Card.Text>
<Card.Text>
<HiLink />: {user.link ? <span className='btn-link' onClick={() => {window.open("http://" + user.link)}}>{user.link}</span> : "N/A"}
</Card.Text>
</Col>
</Row>
</Card.Body>
</Card>
</Container>
</>
);
}
export default YourTeamCard;
|
module.exports={A:{A:{"2":"J C G E B A UB"},B:{"2":"D X g H L"},C:{"1":"m n o p q r w x v","2":"0 1 2 4 5 SB F I J C G E z t s QB PB","132":"L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l","164":"B A D X g H"},D:{"1":"0 1 4 5 8 h i j k l m n o p q r w x v z t s EB BB TB CB","2":"F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f","66":"K"},E:{"2":"9 F I J C G E B A DB FB GB HB IB JB KB"},F:{"1":"U V W u Y Z a b c d e f K h i j k l m n o p q r","2":"6 7 E A D H L M N O P Q R S T LB MB NB OB RB y"},G:{"2":"3 9 G A AB VB WB XB YB ZB aB bB cB"},H:{"2":"dB"},I:{"1":"s","2":"2 3 F eB fB gB hB iB jB"},J:{"2":"C B"},K:{"1":"K","2":"6 7 B A D y"},L:{"1":"8"},M:{"1":"t"},N:{"2":"B A"},O:{"132":"kB"},P:{"1":"F I"},Q:{"2":"lB"},R:{"1":"mB"}},B:4,C:"Battery Status API"};
|
const { includes, flatten, values, omit, find, get } = require("lodash/fp");
const { v4: uuidv4 } = require("uuid");
const getDefaultAnswerProperties = require("../../utils/defaultAnswerProperties");
const { answerTypeMap } = require("../../utils/defaultAnswerValidations");
const {
createDefaultValidationsForAnswer,
} = require("../../src/businessLogic/createValidation");
const { merge } = require("lodash");
module.exports = (answer, page) => {
let properties = getDefaultAnswerProperties(answer.type);
if (get("answers", page)) {
const existingAnswerTypes = page.answers.map((a) => a.type);
if (existingAnswerTypes.includes(answer.type)) {
const sharedProperties = find({ type: answer.type }, page.answers)
.properties;
properties = sharedProperties;
}
}
const validation = {};
if (includes(answer.type, flatten(values(answerTypeMap)))) {
const validations = createDefaultValidationsForAnswer(answer);
validations.map((v) => {
validation[v.validationType] = {
id: uuidv4(),
enabled: false,
...omit("config", v),
...v.config,
};
});
}
let defaultOptions;
if (answer.type === "Checkbox" || answer.type === "Radio") {
const createOption = require("./createOption");
defaultOptions = [];
defaultOptions.push(createOption());
if (answer.type === "Radio") {
defaultOptions.push(createOption());
}
}
return {
id: uuidv4(),
...merge(answer, {
properties,
validation,
options: defaultOptions,
}),
};
};
|
/**
* js/family/cash-flow-plans/show.js
*/
let $ = require('jquery');
let meta = require('Services/meta');
let urlParams = require('Services/urlParameters');
let jsCookie = require('js-cookie');
let cashFlowPlanId = false;
function getCashFlowPlanId() {
if (!cashFlowPlanId) {
cashFlowPlanId = meta.get('cash-flow-plan-id');
}
return cashFlowPlanId;
}
let cfpCookieName = 'cfp-id';
let scrollCookieName = 'cfp-scroll';
let expandedTargetsCookieName = 'cfp-targets';
$(function() {
let currentCookieCFP = jsCookie.get(cfpCookieName);
if (currentCookieCFP !== getCashFlowPlanId()) {
jsCookie.set(cfpCookieName, getCashFlowPlanId());
jsCookie.set(scrollCookieName, 0);
jsCookie.set(expandedTargetsCookieName, []);
}
let $window = $(window);
// Expand the sections that were expanded on the last request
// Make sure to toggle the buttons so the correct label is shown
if (jsCookie.getJSON(expandedTargetsCookieName)) {
$(jsCookie.getJSON(expandedTargetsCookieName)).each(function() {
$('#' + this).show();
$('#' + this + '_toggle-button .list-item-display-action').toggle();
});
}
// Scroll to the position the window was scrolled to on the last request
let shouldScroll = urlParams.has('scroll');
if (jsCookie.get(scrollCookieName) && shouldScroll) {
$window.scrollTop(jsCookie.get(scrollCookieName));
}
$window.scroll(() => {
jsCookie.set(scrollCookieName, $window.scrollTop());
});
$('.toggle-entries-list').click(function(e) {
e.preventDefault();
let $this = $(this);
let target = $this.data('toggleTarget');
let $target = $('#' + target);
// Maintain the open sections across requests
expandedTargets = jsCookie.getJSON(expandedTargetsCookieName);
if ($target.is(':visible')) {
expandedTargets.splice(expandedTargets.indexOf(target), 1);
} else {
expandedTargets.push(target);
}
jsCookie.set(expandedTargetsCookieName, expandedTargets);
$target.slideToggle(200);
$this.find('.list-item-display-action').toggle();
});
});
|
'use strict';
var url = require('url');
exports.port = process.env.PORT || 3002;
|
import React from 'react';
import AppContainer from 'components/app-container';
import {Linking} from 'react-native';
import {
Photo,
ContainerCentered,
Name,
Description,
ButtonIcon,
ButtonText,
LinkedInButton,
Source,
} from './styles';
const Profile = () => {
const openLinkedIn = () => {
Linking.openURL('www.linkedin.com/in/alisson-lima-silva');
};
return (
<AppContainer>
<ContainerCentered>
<Photo />
<Name>Alisson Lima</Name>
<Description>
Apaixonado por desenvolvimento Mobile e por React Native
</Description>
<LinkedInButton onPress={openLinkedIn}>
<ButtonIcon />
<ButtonText>Acessar LinkedIn</ButtonText>
</LinkedInButton>
</ContainerCentered>
<Source>Fonte: https://openweathermap.org</Source>
</AppContainer>
);
};
export {Profile};
|
// since v2.x amokjs includes all the dependencies like expressjs.
// you only need require the amokjs package
const amokjs = require('amokjs');
const port = process.env.PORT || 3000;
// by default amokjs will start the service on port 3000
// you can set the custom port number
amokjs.setPort(port);
// since v2.x amokjs allows plugins
// for example:
// amokjs.use(amokjs-local);
// start mock service
amokjs.start(); |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import CssInclusion from './CssInclusion';
describe('css inclusion', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<CssInclusion />, div);
});
});
|
import React, {Component} from 'react';
class SearchBar extends Component {
constructor(props){
super(props);
this.state = { term: ''};
}
render () {
return (
<div className="search-bar">
<input onChange={event => this.onInputChange(event.target.value)} />
</div>
)
}
onInputChange(term){
this.setState({term});
this.props.onSearchTermChange(term);
}
}
export default SearchBar;
|
webpackJsonp([30],{
/***/ 501:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PopupMenuListPageModule", function() { return PopupMenuListPageModule; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__popup_menu__ = __webpack_require__(596);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_ionic_angular__ = __webpack_require__(21);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var PopupMenuListPageModule = (function () {
function PopupMenuListPageModule() {
}
PopupMenuListPageModule = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_1__angular_core__["NgModule"])({
declarations: [
__WEBPACK_IMPORTED_MODULE_0__popup_menu__["a" /* PopupMenuListPage */],
],
imports: [
__WEBPACK_IMPORTED_MODULE_2_ionic_angular__["i" /* IonicPageModule */].forChild(__WEBPACK_IMPORTED_MODULE_0__popup_menu__["a" /* PopupMenuListPage */]),
],
exports: [
__WEBPACK_IMPORTED_MODULE_0__popup_menu__["a" /* PopupMenuListPage */]
]
})
], PopupMenuListPageModule);
return PopupMenuListPageModule;
}());
//# sourceMappingURL=popup-menu.module.js.map
/***/ }),
/***/ 596:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PopupMenuListPage; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(21);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var PopupMenuListPage = (function () {
function PopupMenuListPage(navCtrl, menu) {
this.navCtrl = navCtrl;
this.menu = menu;
this.items = [];
this.rootPage = PopupMenuListPage_1;
this.items = [
{
title: 'Type One',
page: 'PopupMenuOnePage'
},
{
title: 'Type Two',
page: 'PopupMenuTwoPage'
},
];
}
PopupMenuListPage_1 = PopupMenuListPage;
PopupMenuListPage.prototype.itemTapped = function (event, item) {
this.navCtrl.push(item.page);
};
PopupMenuListPage = PopupMenuListPage_1 = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({
selector: 'page-popup-menu',template:/*ion-inline-start:"/Users/dspl/Documents/ionic/example/ionic3-components/src/pages/popup-menu/popup-menu.html"*/'<ion-header>\n <ion-navbar>\n <button ion-button menuToggle>\n <ion-icon name="menu"></ion-icon>\n </button>\n <ion-title>Popup Menu</ion-title>\n </ion-navbar>\n</ion-header>\n\n<ion-content>\n <ion-list>\n <button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">\n {{item.title}}\n </button>\n </ion-list>\n</ion-content>'/*ion-inline-end:"/Users/dspl/Documents/ionic/example/ionic3-components/src/pages/popup-menu/popup-menu.html"*/
}),
__metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["n" /* NavController */], __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["k" /* MenuController */]])
], PopupMenuListPage);
return PopupMenuListPage;
var PopupMenuListPage_1;
}());
//# sourceMappingURL=popup-menu.js.map
/***/ })
});
//# sourceMappingURL=30.js.map |
# min_cost_path.py - 26-04-2020 09:11
from typing import List
# Video: https://www.youtube.com/watch?v=lBRtnuxg-gU
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
T = [[0] * n for _ in range(m)]
# First left top corner cost is same.
T[0][0] = grid[0][0]
# First row in T
for first_row_idx in range(1, n):
T[0][first_row_idx] = T[0][first_row_idx-1] + grid[0][first_row_idx]
# First col in T
for first_col_idx in range(1, m):
T[first_col_idx][0] = T[first_col_idx-1][0] + grid[first_col_idx][0]
# Fill in the rest of the 2D matrix for T.
for i in range(1, m):
for j in range(1, n):
T[i][j] = grid[i][j] + min(T[i-1][j], # top
T[i][j-1]) # left
# value to reach the right most end
return T[-1][-1]
if __name__ == '__main__':
s = Solution()
mat = [
[1, 3, 1],
[1, 5, 1],
[4, 2, 1]
]
print(s.minPathSum(mat))
|
import React from 'react';
const SvgBq = props => (
<svg width={props.width || 64} height={props.height || 64} {...props}>
<defs>
<linearGradient id="bq_svg__c" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stopColor="#FFF" stopOpacity={0.5} />
<stop offset="100%" stopOpacity={0.5} />
</linearGradient>
<circle id="bq_svg__b" cx={16} cy={15} r={15} />
<filter id="bq_svg__a" width="111.7%" height="111.7%" x="-5.8%" y="-4.2%" filterUnits="objectBoundingBox">
<feOffset dy={0.5} in="SourceAlpha" result="shadowOffsetOuter1" />
<feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation={0.5} />
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1" />
<feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.199473505 0" />
</filter>
<path
id="bq_svg__e"
d="M9.962 15.954a3.849 3.849 0 0 0 3.869 3.848c2.122-.013 3.846-1.716 3.847-3.8a3.834 3.834 0 0 0-3.858-3.869c-2.132.003-3.858 1.712-3.858 3.821m.004 4.14v1.273H8V7c.559.01 1.031.21 1.41.605.363.38.544.835.542 1.363-.005.947-.002 1.894-.002 2.886 1.373-1.147 2.902-1.712 4.683-1.44 1.765.27 3.12 1.158 4.044 2.677 1.395 2.295.943 5.226-1.078 7.05-1.971 1.78-5.246 2.056-7.633-.047zm6.359 1.247c.078-.047.119-.075.162-.097a5.713 5.713 0 0 0 1.65-1.222.528.528 0 0 1 .38-.179c1.67-.096 3.175-1.44 3.458-3.084.372-2.16-.94-4.066-3.11-4.48a1.282 1.282 0 0 1-.77-.42c-.4-.442-.886-.787-1.403-1.084-.044-.025-.086-.052-.158-.096.984-.27 1.943-.334 2.915-.113.967.219 1.8.693 2.58 1.34v-1.275H24V25a1.959 1.959 0 0 1-1.401-.602 1.902 1.902 0 0 1-.552-1.376v-2.87c-1.698 1.423-3.576 1.849-5.722 1.189z"
/>
<filter id="bq_svg__d" width="121.9%" height="119.4%" x="-10.9%" y="-6.9%" filterUnits="objectBoundingBox">
<feOffset dy={0.5} in="SourceAlpha" result="shadowOffsetOuter1" />
<feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation={0.5} />
<feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.204257246 0" />
</filter>
</defs>
<g fill="none" fillRule="evenodd">
<use fill="#000" filter="url(#bq_svg__a)" xlinkHref="#bq_svg__b" />
<use fill="#1D1D1D" xlinkHref="#bq_svg__b" />
<use
fill="url(#bq_svg__c)"
style={{
mixBlendMode: 'soft-light',
}}
xlinkHref="#bq_svg__b"
/>
<circle cx={16} cy={15} r={14.5} stroke="#000" strokeOpacity={0.097} />
<use fill="#000" filter="url(#bq_svg__d)" xlinkHref="#bq_svg__e" />
<use fill="#FFF" xlinkHref="#bq_svg__e" />
</g>
</svg>
);
export default SvgBq;
|
//função api
function ibgeApi(urli, cov, Select) {
const url = urli
const coverage = cov
const locSelect = Select
if (coverage == "states") {
fetch(url) //fetch no serviço
.then( (res) => { return res.json() }) //retorna a resposta em json
.then( states => { //dados do jason
for( const state of states ) { //adiciona uma option para cada Estado que retornou no json
locSelect.innerHTML += `<option value="${state.id}">${state.nome}</option>`
}
})
} else {
fetch(url) //fetch no serviço, com a url dinâmica
.then( (res) => { return res.json() }) //retorna a resposta em json
.then( cities => { //dados do jason
for( const city of cities ) { //adiciona uma option para cada Cidade que retornou no json
locSelect.innerHTML += `<option value="${city.nome}">${city.nome}</option>`
}
locSelect.disabled = false
})
}
}
//popular select com os estados
function populateUFs() {
const locSelect = document.querySelector("select[name=uf]") //seleciona a select uf
const url = "https://servicodados.ibge.gov.br/api/v1/localidades/estados"
const coverage = "states"
ibgeApi(url, coverage, locSelect)
}
populateUFs() //executa a funcao populateUFs
//popular select com as cidades
function getCities(event) {
const locSelect = document.querySelector("select[name=city]") //seleciona a select city
const stateInput = document.querySelector("input[name=state]") //seleciona o input state
const cityInput = document.querySelector("input[name=city]")
const ufValue = event.target.value //pega o valor da uf no target (select uf) do evento (mudar)
const indexOfSelectedState = event.target.selectedIndex //pega o index do evento (mudar estado)
stateInput.value = event.target.options[indexOfSelectedState].text //atualiza o valor de stateInput com o texto (nome do estado) quando houver mudança na select state
const url = `https://servicodados.ibge.gov.br/api/v1/localidades/estados/${ufValue}/municipios` //url dinâmica, interpola o serviço de cidades com o valor da uf
const coverage = "cities"
locSelect.innerHTML = "<option value>Selecione a Cidade</option>" //limpa o conteúdo da select city antes de carregar as cidades
locSelect.disabled = true
ibgeApi(url, coverage, locSelect)
}
document
.querySelector("select[name=uf]") //seleciona a select com name=uf
.addEventListener("change", getCities) //adiciona um ouvidor de eventos, quando mudar o valor da select, executa a função getCities (passada por referência) |
import Vue from 'vue'
import Vuex from 'vuex'
import {
state,
mutations
} from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
})
|
var e = getApp();
Component({
options: {
addGlobalClass: !0
},
data: {
iconList: [ {
icon: "/images/ticket.png",
color: "red",
badge: 120,
name: "门票预订"
}, {
icon: "/images/restaurant.png",
color: "red",
badge: 120,
name: "餐饮预订"
}, {
icon: "/images/hotel.png",
color: "orange",
badge: 1,
name: "酒店预订"
}, {
icon: "/images/characteristic.png",
color: "yellow",
badge: 0,
name: "主题商品"
} ],
gridCol: 4,
starCount: 0,
orderList: [ {
icon: "/images/order.png",
index: "0",
color: "red",
badge: 120,
name: "全部订单"
}, {
icon: "/images/pay.png",
index: "1",
color: "red",
badge: 120,
name: "待支付"
}, {
icon: "/images/use.png",
index: "2",
color: "orange",
badge: 1,
name: "待使用"
}, {
icon: "/images/refound.png",
index: "3",
color: "yellow",
badge: 0,
name: "退款/售后"
} ],
forksCount: 0,
visitTotal: 0,
nickName: "",
spotName: "",
englishName: "MINJIANG ZIPINGPU",
nickUrl: "/images/headPortrait.png",
languageType: ""
},
attached: function() {
this.getSpotName(), this.getuser(), this.setLanguage();
},
methods: {
setLanguage: function() {
"english" == e.globalData.language ? this.setData({
orderList: [ {
icon: "/images/order.png",
index: "0",
color: "red",
badge: 120,
name: "All orders"
}, {
icon: "/images/pay.png",
index: "1",
color: "red",
badge: 120,
name: "Unpaid"
}, {
icon: "/images/use.png",
index: "2",
color: "orange",
badge: 1,
name: "To be used"
}, {
icon: "/images/refound.png",
index: "3",
color: "yellow",
badge: 0,
name: "Refund"
} ],
languageType: "english"
}) : this.setData({
orderList: [ {
icon: "/images/order.png",
index: "0",
color: "red",
badge: 120,
name: "全部订单"
}, {
icon: "/images/pay.png",
index: "1",
color: "red",
badge: 120,
name: "待支付"
}, {
icon: "/images/use.png",
index: "2",
color: "orange",
badge: 1,
name: "待使用"
}, {
icon: "/images/refound.png",
index: "3",
color: "yellow",
badge: 0,
name: "退款/售后"
} ],
languageType: ""
});
},
getuser: function() {
var a = e.globalData.baseurl + "getUserInfo" + ("?applicationNo=" + e.globalData.applicationNo);
wx.showLoading({
title: "数据加载中",
mask: !0
});
var o = wx.getStorageSync("openId"), n = e.globalData.openId;
"" != o ? this.getNickName(a, o) : this.getNickName(a, n);
},
getSpotName: function() {
var a = this, o = e.globalData.baseurl + "getSpot" + ("?applicationNo=" + e.globalData.applicationNo);
wx.showLoading({
title: "加载中...",
mask: !0
}), wx.request({
url: o,
data: {
spotNo: "13056873"
},
method: "POST",
header: {
"content-type": "application/json;charset=utf-8"
},
success: function(e) {
wx.hideLoading(), "success" == e.data.status ? a.setData({
spotName: e.data.data.spotName
}) : wx.showModal({
title: "通知",
showCancel: !1,
content: "查询数据失败,请稍后重试...",
confirmText: "确认"
});
},
fail: function(e) {
wx.hideLoading(), wx.showModal({
title: "通知",
showCancel: !1,
content: "网络异常,请检查网络...",
confirmText: "确认"
});
}
});
},
getNickName: function(e, a) {
var o = this;
wx.request({
url: e,
data: {
openId: a
},
method: "POST",
header: {
"content-type": "application/json;charset=utf-8"
},
success: function(e) {
wx.hideLoading(), "success" == e.data.status ? o.setData({
nickName: e.data.data.nickName
}) : wx.showModal({
title: "通知",
showCancel: !1,
content: "查询数据失败,请稍后重试...",
confirmText: "确认"
});
},
fail: function() {
wx.hideLoading(), wx.showModal({
title: "通知",
showCancel: !1,
content: "网络异常,请检查网络...",
confirmText: "确认"
});
}
});
}
}
}); |
const {test} = require('tap');
const {getClosedChannels} = require('./../../');
const makeLnd = (err, override, response) => {
const channel = {
capacity: '1',
chan_id: '1',
channel_point: '00:1',
close_height: 1,
close_initiator: 'REMOTE',
closing_tx_hash: '00',
open_initiator: 'LOCAL',
remote_pubkey: 'b',
settled_balance: '1',
time_locked_balance: '1',
};
Object.keys(override || {}).forEach(key => channel[key] = override[key]);
const r = response !== undefined ? response : {channels: [channel]};
return {default: {closedChannels: ({}, cbk) => cbk(err, r)}};
};
const makeArgs = ({override}) => {
const args = {
is_breach_close: false,
is_cooperative_close: false,
is_funding_cancel: false,
is_local_force_close: false,
is_remote_force_close: false,
lnd: makeLnd(),
};
Object.keys(override || {}).forEach(key => args[key] = override[key]);
return args;
};
const makeExpectedChannel = ({override}) => {
const expected = {
capacity: 1,
close_balance_vout: undefined,
close_balance_spent_by: undefined,
close_confirm_height: 1,
close_payments: [],
close_transaction_id: '00',
final_local_balance: 1,
final_time_locked_balance: 1,
id: '0x0x1',
is_breach_close: false,
is_cooperative_close: false,
is_funding_cancel: false,
is_local_force_close: false,
is_partner_closed: true,
is_partner_initiated: false,
is_remote_force_close: false,
partner_public_key: 'b',
transaction_id: '00',
transaction_vout: 1,
};
Object.keys(override || {}).forEach(key => expected[key] = override[key]);
return expected;
};
const tests = [
{
args: makeArgs({override: {lnd: undefined}}),
description: 'LND is required',
error: [400, 'ExpectedLndApiForGetClosedChannelsRequest'],
},
{
args: makeArgs({override: {lnd: makeLnd('err')}}),
description: 'Errors are passed back',
error: [503, 'FailedToRetrieveClosedChannels', {err: 'err'}],
},
{
args: makeArgs({override: {lnd: makeLnd(null, null, false)}}),
description: 'A response is expected',
error: [503, 'ExpectedResponseToGetCloseChannels'],
},
{
args: makeArgs({override: {lnd: makeLnd(null, null, {})}}),
description: 'A response with channels is expected',
error: [503, 'ExpectedChannels'],
},
{
args: makeArgs({override: {lnd: makeLnd(null, {capacity: undefined})}}),
description: 'Capacity is expected',
error: [503, 'ExpectedCloseChannelCapacity'],
},
{
args: makeArgs({override: {lnd: makeLnd(null, {chan_id: undefined})}}),
description: 'Channel id is expected',
error: [503, 'ExpectedChannelIdOfClosedChannel'],
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {channel_point: undefined})},
}),
description: 'A channel point is expected',
error: [503, 'ExpectedCloseChannelOutpoint'],
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {close_height: undefined})}
}),
description: 'Channel cloes height is expected',
error: [503, 'ExpectedChannelCloseHeight'],
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {closing_tx_hash: undefined})},
}),
description: 'Closing TX hash is expected',
error: [503, 'ExpectedClosingTransactionId'],
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {remote_pubkey: undefined})},
}),
description: 'A remote public key is expected',
error: [503, 'ExpectedCloseRemotePublicKey'],
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {settled_balance: undefined})},
}),
description: 'Settled balance is required',
error: [503, 'ExpectedFinalSettledBalance'],
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {time_locked_balance: undefined})},
}),
description: 'Time locked balance is required',
error: [503, 'ExpectedFinalTimeLockedBalanceForClosedChan'],
},
{
args: makeArgs({}),
description: 'Closed channels are returned',
expected: {channels: [makeExpectedChannel({})]},
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {close_type: 'REMOTE_FORCE_CLOSE'})},
}),
description: 'Remote force close channel is returned',
expected: {
channels: [
makeExpectedChannel({
override: {is_partner_closed: true, is_remote_force_close: true},
}),
],
},
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {close_type: 'LOCAL_FORCE_CLOSE'})},
}),
description: 'Local force close channel is returned',
expected: {
channels: [
makeExpectedChannel({
override: {is_partner_closed: false, is_local_force_close: true},
}),
],
},
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {close_initiator: 'LOCAL'})},
}),
description: 'Local close initiator is returned',
expected: {
channels: [
makeExpectedChannel({
override: {is_partner_closed: false, is_local_force_close: false},
}),
],
},
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {close_initiator: 'UNKNOWN'})},
}),
description: 'Unknown close initiator is returned as undefined',
expected: {
channels: [
makeExpectedChannel({override: {is_partner_closed: undefined}}),
],
},
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {open_initiator: 'UNKNOWN'})},
}),
description: 'Unknown open initiator is returned as undefined',
expected: {
channels: [
makeExpectedChannel({override: {is_partner_initiated: undefined}}),
],
},
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {close_initiator: 'REMOTE'})},
}),
description: 'Remote close initiator is returned',
expected: {
channels: [makeExpectedChannel({override: {is_partner_closed: true}})],
},
},
{
args: makeArgs({
override: {lnd: makeLnd(null, {open_initiator: 'REMOTE'})},
}),
description: 'Open initiator is returned',
expected: {
channels: [
makeExpectedChannel({override: {is_partner_initiated: true}}),
],
},
},
{
args: makeArgs({
override: {
lnd: makeLnd(null, {
closing_tx_hash: Buffer.alloc(32).toString('hex'),
}),
},
}),
description: 'An empty closing tx hash is returned as undefined',
expected: {
channels: [
makeExpectedChannel({override: {close_transaction_id: undefined}}),
],
},
},
{
args: makeArgs({override: {lnd: makeLnd(null, {chan_id: '0'})}}),
description: 'Empty chan id is returned as undefined',
expected: {channels: [makeExpectedChannel({override: {id: undefined}})]},
},
{
args: makeArgs({override: {lnd: makeLnd(null, {close_height: 0})}}),
description: 'Missing close height is returned as undefined',
expected: {
channels: [
makeExpectedChannel({override: {close_confirm_height: undefined}}),
],
},
},
];
tests.forEach(({args, description, error, expected}) => {
return test(description, async ({deepIs, end, rejects}) => {
if (!!error) {
await rejects(getClosedChannels(args), error, 'Got expected error');
} else {
const {channels} = await getClosedChannels(args);
deepIs(channels, expected.channels, 'Got expected channels');
}
return end();
});
});
|
import base64
import os
from io import BytesIO
import numpy as np
from yt.fields.derived_field import ValidateSpatial
from yt.units.yt_array import YTArray, YTQuantity
from yt.utilities.logger import ytLogger as mylog
from yt.utilities.on_demand_imports import _astropy
def _make_counts(emin, emax):
def _counts(field, data):
e = data[("all", "event_energy")].in_units("keV")
mask = np.logical_and(e >= emin, e < emax)
x = data[("all", "event_x")][mask]
y = data[("all", "event_y")][mask]
z = np.ones(x.shape)
pos = np.array([x, y, z]).transpose()
img = data.deposit(pos, method="count")
if data.has_field_parameter("sigma"):
sigma = data.get_field_parameter("sigma")
else:
sigma = None
if sigma is not None and sigma > 0.0:
kern = _astropy.conv.Gaussian2DKernel(stddev=sigma)
img[:, :, 0] = _astropy.conv.convolve(img[:, :, 0], kern)
return data.ds.arr(img, "counts/pixel")
return _counts
def setup_counts_fields(ds, ebounds, ftype="gas"):
r"""
Create deposited image fields from X-ray count data in energy bands.
Parameters
----------
ds : ~yt.data_objects.static_output.Dataset
The FITS events file dataset to add the counts fields to.
ebounds : list of tuples
A list of tuples, one for each field, with (emin, emax) as the
energy bounds for the image.
ftype : string, optional
The field type of the resulting field. Defaults to "gas".
Examples
--------
>>> ds = yt.load("evt.fits")
>>> ebounds = [(0.1,2.0),(2.0,3.0)]
>>> setup_counts_fields(ds, ebounds)
"""
for (emin, emax) in ebounds:
cfunc = _make_counts(emin, emax)
fname = f"counts_{emin}-{emax}"
mylog.info("Creating counts field %s.", fname)
ds.add_field(
(ftype, fname),
sampling_type="cell",
function=cfunc,
units="counts/pixel",
validators=[ValidateSpatial()],
display_name=f"Counts ({emin}-{emax} keV)",
)
def create_spectral_slabs(filename, slab_centers, slab_width, **kwargs):
r"""
Given a dictionary of spectral slab centers and a width in
spectral units, extract data from a spectral cube at these slab
centers and return a `FITSDataset` instance containing the different
slabs as separate yt fields. Useful for extracting individual
lines from a spectral cube and separating them out as different fields.
Requires the SpectralCube (https://spectral-cube.readthedocs.io/en/latest/)
library.
All keyword arguments will be passed on to the `FITSDataset` constructor.
Parameters
----------
filename : string
The spectral cube FITS file to extract the data from.
slab_centers : dict of (float, string) tuples or YTQuantities
The centers of the slabs, where the keys are the names
of the new fields and the values are (float, string) tuples or
YTQuantities, specifying a value for each center and its unit.
slab_width : YTQuantity or (float, string) tuple
The width of the slab along the spectral axis.
Examples
--------
>>> slab_centers = {'13CN': (218.03117, 'GHz'),
... 'CH3CH2CHO': (218.284256, 'GHz'),
... 'CH3NH2': (218.40956, 'GHz')}
>>> slab_width = (0.05, "GHz")
>>> ds = create_spectral_slabs("intensity_cube.fits",
... slab_centers, slab_width,
... nan_mask=0.0)
"""
from spectral_cube import SpectralCube
from yt.frontends.fits.api import FITSDataset
from yt.visualization.fits_image import FITSImageData
cube = SpectralCube.read(filename)
if not isinstance(slab_width, YTQuantity):
slab_width = YTQuantity(slab_width[0], slab_width[1])
slab_data = {}
field_units = cube.header.get("bunit", "dimensionless")
for k, v in slab_centers.items():
if not isinstance(v, YTQuantity):
slab_center = YTQuantity(v[0], v[1])
else:
slab_center = v
mylog.info("Adding slab field %s at %g %s", k, slab_center.v, slab_center.units)
slab_lo = (slab_center - 0.5 * slab_width).to_astropy()
slab_hi = (slab_center + 0.5 * slab_width).to_astropy()
subcube = cube.spectral_slab(slab_lo, slab_hi)
slab_data[k] = YTArray(subcube.filled_data[:, :, :], field_units)
width = subcube.header["naxis3"] * cube.header["cdelt3"]
w = subcube.wcs.copy()
w.wcs.crpix[-1] = 0.5
w.wcs.crval[-1] = -0.5 * width
fid = FITSImageData(slab_data, wcs=w)
for hdu in fid:
hdu.header.pop("RESTFREQ", None)
hdu.header.pop("RESTFRQ", None)
ds = FITSDataset(fid, **kwargs)
return ds
def ds9_region(ds, reg, obj=None, field_parameters=None):
r"""
Create a data container from a ds9 region file. Requires the pyregion
package (https://pyregion.readthedocs.io/en/latest/) to be installed.
Parameters
----------
ds : FITSDataset
The Dataset to create the region from.
reg : string
The filename of the ds9 region, or a region string to be parsed.
obj : data container, optional
The data container that will be used to create the new region.
Defaults to ds.all_data.
field_parameters : dictionary, optional
A set of field parameters to apply to the region.
Examples
--------
>>> ds = yt.load("m33_hi.fits")
>>> circle_region = ds9_region(ds, "circle.reg")
>>> print(circle_region.quantities.extrema("flux"))
"""
import pyregion
from yt.frontends.fits.api import EventsFITSDataset
if os.path.exists(reg):
r = pyregion.open(reg)
else:
r = pyregion.parse(reg)
reg_name = reg
header = ds.wcs_2d.to_header()
# The FITS header only contains WCS-related keywords
header["NAXIS1"] = nx = ds.domain_dimensions[ds.lon_axis]
header["NAXIS2"] = ny = ds.domain_dimensions[ds.lat_axis]
filter = r.get_filter(header=header)
mask = filter.mask((ny, nx)).transpose()
if isinstance(ds, EventsFITSDataset):
prefix = "event_"
else:
prefix = ""
def _reg_field(field, data):
i = data[prefix + "xyz"[ds.lon_axis]].d.astype("int") - 1
j = data[prefix + "xyz"[ds.lat_axis]].d.astype("int") - 1
new_mask = mask[i, j]
ret = np.zeros(data[prefix + "x"].shape)
ret[new_mask] = 1.0
return ret
ds.add_field(("gas", reg_name), sampling_type="cell", function=_reg_field)
if obj is None:
obj = ds.all_data()
if field_parameters is not None:
for k, v in field_parameters.items():
obj.set_field_parameter(k, v)
return obj.cut_region([f"obj['{reg_name}'] > 0"])
class PlotWindowWCS:
r"""
Use AstroPy's WCSAxes class to plot celestial coordinates on the axes of a
on-axis PlotWindow plot. See
http://docs.astropy.org/en/stable/visualization/wcsaxes/ for more details
on how it works under the hood. This functionality requires a version of
AstroPy >= 1.3.
Parameters
----------
pw : on-axis PlotWindow instance
The PlotWindow instance to add celestial axes to.
"""
def __init__(self, pw):
WCSAxes = _astropy.wcsaxes.WCSAxes
if pw.oblique:
raise NotImplementedError("WCS axes are not implemented for oblique plots.")
if not hasattr(pw.ds, "wcs_2d"):
raise NotImplementedError("WCS axes are not implemented for this dataset.")
if pw.data_source.axis != pw.ds.spec_axis:
raise NotImplementedError("WCS axes are not implemented for this axis.")
self.plots = {}
self.pw = pw
for f in pw.plots:
rect = pw.plots[f]._get_best_layout()[1]
fig = pw.plots[f].figure
ax = fig.axes[0]
wcs_ax = WCSAxes(fig, rect, wcs=pw.ds.wcs_2d, frameon=False)
fig.add_axes(wcs_ax)
wcs = pw.ds.wcs_2d.wcs
xax = pw.ds.coordinates.x_axis[pw.data_source.axis]
yax = pw.ds.coordinates.y_axis[pw.data_source.axis]
xlabel = f"{wcs.ctype[xax].split('-')[0]} ({wcs.cunit[xax]})"
ylabel = f"{wcs.ctype[yax].split('-')[0]} ({wcs.cunit[yax]})"
fp = pw._font_properties
wcs_ax.coords[0].set_axislabel(xlabel, fontproperties=fp, minpad=0.5)
wcs_ax.coords[1].set_axislabel(ylabel, fontproperties=fp, minpad=0.4)
wcs_ax.coords[0].ticklabels.set_fontproperties(fp)
wcs_ax.coords[1].ticklabels.set_fontproperties(fp)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
wcs_ax.set_xlim(pw.xlim[0].value, pw.xlim[1].value)
wcs_ax.set_ylim(pw.ylim[0].value, pw.ylim[1].value)
wcs_ax.coords.frame._update_cache = []
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
self.plots[f] = fig
def keys(self):
return self.plots.keys()
def values(self):
return self.plots.values()
def items(self):
return self.plots.items()
def __getitem__(self, key):
for k in self.keys():
if k[1] == key:
return self.plots[k]
def show(self):
return self
def save(self, name=None, mpl_kwargs=None):
if mpl_kwargs is None:
mpl_kwargs = {}
mpl_kwargs["bbox_inches"] = "tight"
self.pw.save(name=name, mpl_kwargs=mpl_kwargs)
def _repr_html_(self):
from yt.visualization._mpl_imports import FigureCanvasAgg
ret = ""
for v in self.plots.values():
canvas = FigureCanvasAgg(v)
f = BytesIO()
canvas.print_figure(f)
f.seek(0)
img = base64.b64encode(f.read()).decode()
ret += (
r'<img style="max-width:100%%;max-height:100%%;" '
r'src="data:image/png;base64,%s"><br>' % img
)
return ret
|
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
import 'bootstrap-social/bootstrap-social.css';
import './index.css'; // This comes after so we can override bootstrap
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
|
'use strict';
var should = require('chai').should();
var EventEmitter = require('events').EventEmitter;
var path = require('path');
var sinon = require('sinon');
var proxyquire = require('proxyquire');
var start = require('../../lib/scaffold/start');
describe('#start', function() {
describe('#checkConfigVersion2', function() {
var sandbox = sinon.sandbox.create();
beforeEach(function() {
sandbox.stub(console, 'warn');
});
afterEach(function() {
sandbox.restore();
});
it('will give true with "datadir" at root', function() {
var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;
var v2 = checkConfigVersion2({datadir: '/home/user/.ioncore/data', services: []});
v2.should.equal(true);
});
it('will give true with "address" service enabled', function() {
var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;
var v2 = checkConfigVersion2({services: ['address']});
v2.should.equal(true);
});
it('will give true with "db" service enabled', function() {
var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;
var v2 = checkConfigVersion2({services: ['db']});
v2.should.equal(true);
});
it('will give false without "datadir" at root and "address", "db" services disabled', function() {
var checkConfigVersion2 = proxyquire('../../lib/scaffold/start', {}).checkConfigVersion2;
var v2 = checkConfigVersion2({services: []});
v2.should.equal(false);
});
});
describe('#setupServices', function() {
var cwd = process.cwd();
var setupServices = proxyquire('../../lib/scaffold/start', {}).setupServices;
it('will require an internal module', function() {
function InternalService() {}
InternalService.dependencies = [];
InternalService.prototype.start = sinon.stub();
InternalService.prototype.stop = sinon.stub();
var expectedPath = path.resolve(__dirname, '../../lib/services/internal');
var testRequire = function(p) {
p.should.equal(expectedPath);
return InternalService;
};
var config = {
services: ['internal'],
servicesConfig: {
internal: {
param: 'value'
}
}
};
var services = setupServices(testRequire, cwd, config);
services[0].name.should.equal('internal');
services[0].config.should.deep.equal({param: 'value'});
services[0].module.should.equal(InternalService);
});
it('will require a local module', function() {
function LocalService() {}
LocalService.dependencies = [];
LocalService.prototype.start = sinon.stub();
LocalService.prototype.stop = sinon.stub();
var notfoundPath = path.resolve(__dirname, '../../lib/services/local');
var testRequire = function(p) {
if (p === notfoundPath) {
throw new Error();
} else if (p === 'local') {
return LocalService;
} else if (p === 'local/package.json') {
return {
name: 'local'
};
}
};
var config = {
services: ['local']
};
var services = setupServices(testRequire, cwd, config);
services[0].name.should.equal('local');
services[0].module.should.equal(LocalService);
});
it('will require a local module with "ioncoreNode" in package.json', function() {
function LocalService() {}
LocalService.dependencies = [];
LocalService.prototype.start = sinon.stub();
LocalService.prototype.stop = sinon.stub();
var notfoundPath = path.resolve(__dirname, '../../lib/services/local');
var testRequire = function(p) {
if (p === notfoundPath) {
throw new Error();
} else if (p === 'local/package.json') {
return {
name: 'local',
ioncoreNode: 'lib/ioncoreNode.js'
};
} else if (p === 'local/lib/ioncoreNode.js') {
return LocalService;
}
};
var config = {
services: ['local']
};
var services = setupServices(testRequire, cwd, config);
services[0].name.should.equal('local');
services[0].module.should.equal(LocalService);
});
it('will throw error if module is incompatible', function() {
var internal = {};
var testRequire = function() {
return internal;
};
var config = {
services: ['bitcoind']
};
(function() {
setupServices(testRequire, cwd, config);
}).should.throw('Could not load service');
});
});
describe('#cleanShutdown', function() {
it('will call node stop and process exit', function() {
var log = {
info: sinon.stub(),
error: sinon.stub()
};
var cleanShutdown = proxyquire('../../lib/scaffold/start', {
'../': {
log: log
}
}).cleanShutdown;
var node = {
stop: sinon.stub().callsArg(0)
};
var _process = {
exit: sinon.stub()
};
cleanShutdown(_process, node);
setImmediate(function() {
node.stop.callCount.should.equal(1);
_process.exit.callCount.should.equal(1);
_process.exit.args[0][0].should.equal(0);
});
});
it('will log error during shutdown and exit with status 1', function() {
var log = {
info: sinon.stub(),
error: sinon.stub()
};
var cleanShutdown = proxyquire('../../lib/scaffold/start', {
'../': {
log: log
}
}).cleanShutdown;
var node = {
stop: sinon.stub().callsArgWith(0, new Error('test'))
};
var _process = {
exit: sinon.stub()
};
cleanShutdown(_process, node);
setImmediate(function() {
node.stop.callCount.should.equal(1);
log.error.callCount.should.equal(1);
_process.exit.callCount.should.equal(1);
_process.exit.args[0][0].should.equal(1);
});
});
});
describe('#registerExitHandlers', function() {
var log = {
info: sinon.stub(),
error: sinon.stub()
};
var registerExitHandlers = proxyquire('../../lib/scaffold/start', {
'../': {
log: log
}
}).registerExitHandlers;
it('log, stop and exit with an `uncaughtException`', function(done) {
var proc = new EventEmitter();
proc.exit = sinon.stub();
var node = {
stop: sinon.stub().callsArg(0)
};
registerExitHandlers(proc, node);
proc.emit('uncaughtException', new Error('test'));
setImmediate(function() {
node.stop.callCount.should.equal(1);
proc.exit.callCount.should.equal(1);
done();
});
});
it('stop and exit on `SIGINT`', function(done) {
var proc = new EventEmitter();
proc.exit = sinon.stub();
var node = {
stop: sinon.stub().callsArg(0)
};
registerExitHandlers(proc, node);
proc.emit('SIGINT');
setImmediate(function() {
node.stop.callCount.should.equal(1);
proc.exit.callCount.should.equal(1);
done();
});
});
});
describe('#registerExitHandlers', function() {
var stub;
var registerExitHandlers = require('../../lib/scaffold/start').registerExitHandlers;
before(function() {
stub = sinon.stub(process, 'on');
});
after(function() {
stub.restore();
});
it('should setup two listeners on process when registering exit handlers', function() {
registerExitHandlers(process, {});
stub.callCount.should.equal(2);
});
describe('#exitHandler', function() {
var sandbox;
var cleanShutdown;
var exitHandler;
var logStub;
before(function() {
sandbox = sinon.sandbox.create();
var start = require('../../lib/scaffold/start');
var log = require('../../lib').log;
logStub = sandbox.stub(log, 'error');
cleanShutdown = sandbox.stub(start, 'cleanShutdown', function() {});
exitHandler = require('../../lib/scaffold/start').exitHandler;
});
after(function() {
sandbox.restore();
});
it('should replace the listener for SIGINT after the first SIGINT is handled', function() {
var options = { sigint: true };
var node = {};
exitHandler(options, process, node);
cleanShutdown.callCount.should.equal(1);
exitHandler(options, process, node);
cleanShutdown.callCount.should.equal(1);
});
it('should log all errors and stops the services nonetheless', function() {
var options = { sigint: true };
var stop = sinon.stub();
var node = {
stop: stop
};
exitHandler(options, process, node, new Error('some error'));
logStub.callCount.should.equal(2);
stop.callCount.should.equal(1);
});
});
});
});
|
import Container from '../container';
import SectionHeader from '../section-header';
import Wifi from './svg/wifi';
export default () => (
<Container wide center>
<SectionHeader
anchor="offline-support"
title="Offline Support"
margin="4rem 0 0 0"
/>
<div className="content">
<p>
Unreliable network connections are an unavoidable reality on the mobile
web. But that doesn't mean they need to disrupt your users. Progressive
web apps leverage modern web technologies to provide offline support so
your app never goes down.
</p>
</div>
<div className="device">
<amp-img
src="/static/svg/offline-support.svg"
alt="Offline support"
width={632}
height={204}
/>
<div className="wifi">
<Wifi />
</div>
</div>
<style jsx>{`
a {
display: none;
margin: 0 0 0 0;
}
.content {
margin: 1rem 0 1.5rem;
max-width: 44rem;
margin: 0 auto;
padding: 0 2rem;
}
.device {
position: relative;
justify-content: center;
display: flex;
}
.wifi {
position: absolute;
bottom: 0;
}
`}</style>
</Container>
);
|
#bind = "192.168.0.11:5000"
bind = "unix:/tmp/jackcast.sock"
unmask = 7
worker_class = 'gevent'
threads = 2
|
// @flow strict
import { type Node } from 'react';
import { Box, Flex, Text } from 'gestalt';
import { type sidebarIndexType } from './sidebarIndex.js';
import SidebarSectionLink from './SidebarSectionLink.js';
export default function SidebarSection({ section }: {| section: sidebarIndexType |}): Node {
return (
<Box role="list">
<Box role="listitem" padding={2} marginTop={4}>
<Flex justifyContent="between">
<Text size="100">{section.sectionName}</Text>
</Flex>
</Box>
{section.pages.map((componentName, i) => (
<SidebarSectionLink key={`${componentName}--${i}`} componentName={componentName} />
))}
</Box>
);
}
|
const mongoose = require("mongoose") |
import io
from ._common import *
from piexif import _webp
def remove(src, new_file=None):
"""
py:function:: piexif.remove(filename)
Remove exif from JPEG.
:param str filename: JPEG
"""
output_is_file = False
if src[0:2] == b"\xff\xd8":
src_data = src
file_type = "jpeg"
elif src[0:4] == b"RIFF" and src[8:12] == b"WEBP":
src_data = src
file_type = "webp"
else:
with open(src, 'rb') as f:
src_data = f.read()
output_is_file = True
if src_data[0:2] == b"\xff\xd8":
file_type = "jpeg"
elif src_data[0:4] == b"RIFF" and src_data[8:12] == b"WEBP":
file_type = "webp"
if file_type == "jpeg":
segments = split_into_segments(src_data)
exif = get_exif_seg(segments)
if exif:
new_data = src_data.replace(exif, b"")
else:
new_data = src_data
elif file_type == "webp":
try:
new_data = _webp.remove(src_data)
except ValueError:
new_data = src_data
except e:
print(e.args)
raise ValueError("Error ocured.")
if isinstance(new_file, io.BytesIO):
new_file.write(new_data)
new_file.seek(0)
elif new_file:
with open(new_file, "wb+") as f:
f.write(new_data)
elif output_is_file:
with open(src, "wb+") as f:
f.write(new_data)
else:
raise ValueError("Give a second argment to 'remove' to output file") |
'use strict';
var APPLICATION_JSON = 'application/json';
var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
var JSON_START = /^\[|^\{(?!\{)/;
var JSON_ENDS = {
'[': /]$/,
'{': /}$/
};
var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
function defaultHttpResponseTransform(data, headers) {
if (isString(data)) {
// Strip json vulnerability protection prefix and trim whitespace
var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
data = fromJson(tempData);
}
}
}
return data;
}
function isJsonLike(str) {
var jsonStart = str.match(JSON_START);
return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = createMap(), key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers HTTP headers getter fn.
* @param {number} status HTTP status code of the response.
* @param {(Function|Array.<Function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, status, fns) {
if (isFunction(fns))
return fns(data, headers, status);
forEach(fns, function(fn) {
data = fn(data, headers, status);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
/**
* @ngdoc provider
* @name $httpProvider
* @description
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
* */
function $HttpProvider() {
/**
* @ngdoc property
* @name $httpProvider#defaults
* @description
*
* Object containing default values for all {@link ng.$http $http} requests.
*
* - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
* that will provide the cache for all requests who set their `cache` property to `true`.
* If you set the `default.cache = false` then only requests that specify their own custom
* cache object will be cached. See {@link $http#caching $http Caching} for more information.
*
* - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
* Defaults value is `'XSRF-TOKEN'`.
*
* - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
* XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
*
* - **`defaults.headers`** - {Object} - Default headers for all $http requests.
* Refer to {@link ng.$http#setting-http-headers $http} for documentation on
* setting default headers.
* - **`defaults.headers.common`**
* - **`defaults.headers.post`**
* - **`defaults.headers.put`**
* - **`defaults.headers.patch`**
*
**/
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [defaultHttpResponseTransform],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
var useApplyAsync = false;
/**
* @ngdoc method
* @name $httpProvider#useApplyAsync
* @description
*
* Configure $http service to combine processing of multiple http responses received at around
* the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
* significant performance improvement for bigger applications that make many HTTP requests
* concurrently (common during application bootstrap).
*
* Defaults to false. If no value is specifed, returns the current configured value.
*
* @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
* "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
* to load and share the same digest cycle.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useApplyAsync = function(value) {
if (isDefined(value)) {
useApplyAsync = !!value;
return this;
}
return useApplyAsync;
};
/**
* @ngdoc property
* @name $httpProvider#interceptors
* @description
*
* Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
* pre-processing of request or postprocessing of responses.
*
* These service factories are ordered by request, i.e. they are applied in the same order as the
* array, on request, but reverse order, on response.
*
* {@link ng.$http#interceptors Interceptors detailed info}
**/
var interceptorFactories = this.interceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http');
/**
* Interceptors stored in reverse order. Inner interceptors before outer interceptors.
* The reversal is needed so that we can build up the interception chain around the
* server request.
*/
var reversedInterceptors = [];
forEach(interceptorFactories, function(interceptorFactory) {
reversedInterceptors.unshift(isString(interceptorFactory)
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});
/**
* @ngdoc service
* @kind function
* @name $http
* @requires ng.$httpBackend
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
* object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* ## General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* ```js
* // Simple GET request example :
* $http.get('/someUrl').
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
* ```js
* // Simple POST request example (passing data) :
* $http.post('/someUrl', {msg:'hello word!'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
*
* Since the returned value of calling the $http function is a `promise`, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the API signature and type info below for more
* details.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* ## Writing Unit Tests that use $http
* When unit testing (using {@link ngMock ngMock}), it is necessary to call
* {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
* request using trained responses.
*
* ```
* $httpBackend.expectGET(...);
* $http.get(...);
* $httpBackend.flush();
* ```
*
* ## Shortcut methods
*
* Shortcut methods are also available. All shortcut methods require passing in the URL, and
* request data must be passed in for POST/PUT requests.
*
* ```js
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* ```
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
* - {@link ng.$http#patch $http.patch}
*
*
* ## Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
*
* The defaults can also be set at runtime via the `$http.defaults` object in the same
* fashion. For example:
*
* ```
* module.run(function($http) {
* $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
* });
* ```
*
* In addition, you can supply a `headers` property in the config object passed when
* calling `$http(config)`, which overrides the defaults without changing them globally.
*
* To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
* Use the `headers` property, setting the desired header to `undefined`. For example:
*
* ```js
* var req = {
* method: 'POST',
* url: 'http://example.com',
* headers: {
* 'Content-Type': undefined
* },
* data: { test: 'test' },
* }
*
* $http(req).success(function(){...}).error(function(){...});
* ```
*
* ## Transforming Requests and Responses
*
* Both requests and responses can be transformed using transformation functions: `transformRequest`
* and `transformResponse`. These properties can be a single function that returns
* the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
* which allows you to `push` or `unshift` a new transformation function into the transformation chain.
*
* ### Default Transformations
*
* The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
* `defaults.transformResponse` properties. If a request does not provide its own transformations
* then these will be applied.
*
* You can augment or replace the default transformations by modifying these properties by adding to or
* replacing the array.
*
* Angular provides the following default transformations:
*
* Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
*
* - If the `data` property of the request configuration object contains an object, serialize it
* into JSON format.
*
* Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
*
* ### Overriding the Default Transformations Per Request
*
* If you wish override the request/response transformations only for a single request then provide
* `transformRequest` and/or `transformResponse` properties on the configuration object passed
* into `$http`.
*
* Note that if you provide these properties on the config object the default transformations will be
* overwritten. If you wish to augment the default transformations then you must include them in your
* local transformation array.
*
* The following code demonstrates adding a new response transformation to be run after the default response
* transformations have been run.
*
* ```js
* function appendTransform(defaults, transform) {
*
* // We can't guarantee that the default transformation is an array
* defaults = angular.isArray(defaults) ? defaults : [defaults];
*
* // Append the new transformation to the defaults
* return defaults.concat(transform);
* }
*
* $http({
* url: '...',
* method: 'GET',
* transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
* return doTransform(value);
* })
* });
* ```
*
*
* ## Caching
*
* To enable caching, set the request configuration `cache` property to `true` (to use default
* cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
* When the cache is enabled, `$http` stores the response from the server in the specified
* cache. The next time the same request is made, the response is served from the cache without
* sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
* You can change the default cache to a new object (built with
* {@link ng.$cacheFactory `$cacheFactory`}) by updating the
* {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
* their `cache` property to `true` will now use this cache object.
*
* If you set the default cache to `false` then only requests that specify their own custom
* cache object will be cached.
*
* ## Interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication, or any kind of synchronous or
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
* able to intercept requests before they are handed to the server and
* responses before they are handed over to the application code that
* initiated these requests. The interceptors leverage the {@link ng.$q
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
*
* The interceptors are service factories that are registered with the `$httpProvider` by
* adding them to the `$httpProvider.interceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor.
*
* There are two kinds of interceptors (and two kinds of rejection interceptors):
*
* * `request`: interceptors get called with a http `config` object. The function is free to
* modify the `config` object or create a new one. The function needs to return the `config`
* object directly, or a promise containing the `config` or a new `config` object.
* * `requestError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
* * `response`: interceptors get called with http `response` object. The function is free to
* modify the `response` object or create a new one. The function needs to return the `response`
* object directly, or as a promise containing the `response` or a new `response` object.
* * `responseError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
*
*
* ```js
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return {
* // optional method
* 'request': function(config) {
* // do something on success
* return config;
* },
*
* // optional method
* 'requestError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* },
*
*
*
* // optional method
* 'response': function(response) {
* // do something on success
* return response;
* },
*
* // optional method
* 'responseError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* }
* };
* });
*
* $httpProvider.interceptors.push('myHttpInterceptor');
*
*
* // alternatively, register the interceptor via an anonymous factory
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
* return {
* 'request': function(config) {
* // same as above
* },
*
* 'response': function(response) {
* // same as above
* }
* };
* });
* ```
*
* ## Security Considerations
*
* When designing web applications, consider security threats from:
*
* - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ### JSON Vulnerability Protection
*
* A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* allows third party website to turn your JSON resource URL into
* [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* ```js
* ['one','two']
* ```
*
* which is vulnerable to attack, your server can return:
* ```js
* )]}',
* ['one','two']
* ```
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ### Cross Site Request Forgery (XSRF) Protection
*
* [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
* JavaScript that runs on your domain could read the cookie, your server can be assured that
* the XHR came from JavaScript running on your domain. The header will not be set for
* cross-domain requests.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
* making up its own tokens). We recommend that the token is a digest of your site's
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
* for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
* or the per-request config object.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
* to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
* JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings or functions which return strings representing
* HTTP headers to send to the server. If the return value of a function is null, the
* header will not be sent. Functions accept a config object as an argument.
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
* - **transformRequest** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default Transformations}
* - **transformResponse** –
* `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body, headers and status and returns its transformed (typically deserialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default Transformations}
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
* that should abort the request when resolved.
* - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
* for more information.
* - **responseType** - `{string}` - see
* [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform
* functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
* - **statusText** – `{string}` – HTTP status text of the response.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example module="httpExample">
<file name="index.html">
<div ng-controller="FetchController">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button id="fetchbtn" ng-click="fetch()">fetch</button><br>
<button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button id="samplejsonpbtn"
ng-click="updateModel('JSONP',
'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button id="invalidjsonpbtn"
ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}]);
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="protractor.js" type="protractor">
var status = element(by.binding('status'));
var data = element(by.binding('data'));
var fetchBtn = element(by.id('fetchbtn'));
var sampleGetBtn = element(by.id('samplegetbtn'));
var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
it('should make an xhr GET request', function() {
sampleGetBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('200');
expect(data.getText()).toMatch(/Hello, \$http!/);
});
// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
// sampleJsonpBtn.click();
// fetchBtn.click();
// expect(status.getText()).toMatch('200');
// expect(data.getText()).toMatch(/Super Hero!/);
// });
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
invalidJsonpBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('0');
expect(data.getText()).toMatch('Request failed');
});
</file>
</example>
*/
function $http(requestConfig) {
if (!angular.isObject(requestConfig)) {
throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
}
var config = extend({
method: 'get',
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse
}, requestConfig);
config.headers = mergeHeaders(requestConfig);
config.method = uppercase(config.method);
var serverRequest = function(config) {
var headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
// strip content-type if data is undefined
if (isUndefined(reqData)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
}
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
}
// send request
return sendReq(config, reqData).then(transformResponse, transformResponse);
};
var chain = [serverRequest, undefined];
var promise = $q.when(config);
// apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
chain.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
chain.push(interceptor.response, interceptor.responseError);
}
});
while (chain.length) {
var thenFn = chain.shift();
var rejectFn = chain.shift();
promise = promise.then(thenFn, rejectFn);
}
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response);
if (!response.data) {
resp.data = response.data;
} else {
resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
}
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
function executeHeaderFns(headers, config) {
var headerContent, processedHeaders = {};
forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn(config);
if (headerContent != null) {
processedHeaders[header] = headerContent;
}
} else {
processedHeaders[header] = headerFn;
}
});
return processedHeaders;
}
function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
// execute if header value is a function for merged headers
return executeHeaderFns(reqHeaders, shallowCopy(config));
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name $http#get
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#delete
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#head
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#jsonp
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* The name of the callback should be the string `JSON_CALLBACK`.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name $http#post
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#put
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#patch
*
* @description
* Shortcut method to perform `PATCH` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put', 'patch');
/**
* @ngdoc property
* @name $http#defaults
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers, withCredentials as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = defaults;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
reqHeaders = config.headers,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = isObject(config.cache) ? config.cache
: isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (isDefined(cachedResp)) {
if (isPromiseLike(cachedResp)) {
// cached request has already been sent, but there is no response yet
cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
} else {
resolvePromise(cachedResp, 200, {}, 'OK');
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, set the xsrf headers and
// send the request to the backend
if (isUndefined(cachedResp)) {
var xsrfValue = urlIsSameOrigin(config.url)
? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials, config.responseType);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString, statusText) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString), statusText]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
function resolveHttpPromise() {
resolvePromise(response, status, headersString, statusText);
}
if (useApplyAsync) {
$rootScope.$applyAsync(resolveHttpPromise);
} else {
resolveHttpPromise();
if (!$rootScope.$$phase) $rootScope.$apply();
}
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers, statusText) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config,
statusText: statusText
});
}
function resolvePromiseWithResult(result) {
resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
}
function removePendingReq() {
var idx = $http.pendingRequests.indexOf(config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value === null || isUndefined(value)) return;
if (!isArray(value)) value = [value];
forEach(value, function(v) {
if (isObject(v)) {
if (isDate(v)) {
v = v.toISOString();
} else {
v = toJson(v);
}
}
parts.push(encodeUriQuery(key) + '=' +
encodeUriQuery(v));
});
});
if (parts.length > 0) {
url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
return url;
}
}];
}
|
import { useI18n } from 'vue-i18n'
export function useLocale() {
const { t, availableLocales, getLocaleMessage, setLocaleMessage } = useI18n({ useScope: 'global' })
// await import('src/i18n/' + state.localInfo.locale).then((messages) => {
// i18n.global.setLocaleMessage(state.localInfo.locale, messages.default)
// })
// availableLocales.forEach((locale) => {
// console.log(`${locale} locale messages`, getLocaleMessage(locale))
// })
return {
t,
}
}
|
import functools
from ometa.grammar import OMeta
from ometa.runtime import ParseError, EOFError, OMetaBase
from terml.parser import parseTerm as term
from terml.quasiterm import quasiterm
__version__ = '1.3'
def wrapGrammar(g, tracefunc=None):
def makeParser(input):
"""
Creates a parser for the given input, with methods for
invoking each rule.
:param input: The string you want to parse.
"""
parser = g(input)
if tracefunc:
parser._trace = tracefunc
return _GrammarWrapper(parser, input)
makeParser._grammarClass = g
return makeParser
def makeGrammar(source, bindings, name='Grammar', unwrap=False,
extends=wrapGrammar(OMetaBase), tracefunc=None):
"""
Create a class from a Parsley grammar.
:param source: A grammar, as a string.
:param bindings: A mapping of variable names to objects.
:param name: Name used for the generated class.
:param unwrap: If True, return a parser class suitable for
subclassing. If False, return a wrapper with the
friendly API.
:param extends: The superclass for the generated parser class.
:param tracefunc: A 3-arg function which takes a fragment of grammar
source, the start/end indexes in the grammar of this
fragment, and a position in the input. Invoked for
terminals and rule applications.
"""
g = OMeta.makeGrammar(source, name).createParserClass(
unwrapGrammar(extends), bindings)
if unwrap:
return g
else:
return wrapGrammar(g, tracefunc=tracefunc)
def unwrapGrammar(w):
"""
Access the internal parser class for a Parsley grammar object.
"""
return getattr(w, '_grammarClass', None) or w
class _GrammarWrapper(object):
"""
A wrapper for Parsley grammar instances.
To invoke a Parsley rule, invoke a method with that name -- this
turns x(input).foo() calls into grammar.apply("foo") calls.
"""
def __init__(self, grammar, input):
self._grammar = grammar
self._input = input
#so pydoc doesn't get trapped in the __getattr__
self.__name__ = _GrammarWrapper.__name__
def __getattr__(self, name):
"""
Return a function that will instantiate a grammar and invoke the named
rule.
:param name: Rule name.
"""
def invokeRule(*args, **kwargs):
"""
Invoke a Parsley rule. Passes any positional args to the rule.
"""
try:
ret, err = self._grammar.apply(name, *args)
except ParseError as e:
self._grammar.considerError(e)
err = self._grammar.currentError
else:
try:
extra, _ = self._grammar.input.head()
except EOFError:
return ret
else:
# problem is that input remains, so:
err = ParseError(err.input, err.position + 1,
[["message", "expected EOF"]], err.trail)
raise err
return invokeRule
def makeProtocol(source, senderFactory, receiverFactory, bindings=None,
name='Grammar'):
"""
Create a Twisted ``Protocol`` factory from a Parsley grammar.
:param source: A grammar, as a string.
:param senderFactory: A one-argument callable that takes a twisted
``Transport`` and returns a :ref:`sender <senders>`.
:param receiverFactory: A one-argument callable that takes the sender
returned by the ``senderFactory`` and returns a :ref:`receiver
<receivers>`.
:param bindings: A mapping of variable names to objects which will be
accessible from python code in the grammar.
:param name: The name used for the generated grammar class.
:returns: A nullary callable which will return an instance of
:class:`~.ParserProtocol`.
"""
from ometa.protocol import ParserProtocol
if bindings is None:
bindings = {}
grammar = OMeta(source).parseGrammar(name)
return functools.partial(
ParserProtocol, grammar, senderFactory, receiverFactory, bindings)
def stack(*wrappers):
"""
Stack some senders or receivers for ease of wrapping.
``stack(x, y, z)`` will return a factory usable as a sender or receiver
factory which will, when called with a transport or sender as an argument,
return ``x(y(z(argument)))``.
"""
if not wrappers:
raise TypeError('at least one argument is required')
def factory(arg):
ret = wrappers[-1](arg)
for wrapper in wrappers[-2::-1]:
ret = wrapper(ret)
return ret
return factory
__all__ = [
'makeGrammar', 'wrapGrammar', 'unwrapGrammar', 'term', 'quasiterm',
'makeProtocol', 'stack',
]
|
import React from "react";
import Card from '@material-ui/core/Card';
import { connect } from 'react-redux';
import Grid from '@material-ui/core/Grid';
import './IndividualProfile.css';
class IndividualProfile extends React.Component{
render(){
const photo = this.props.data && this.props.data.photo
const name = this.props.data && this.props.data.name
const details = this.props.data && this.props.data.details
return(
<Card>
<div>
{this.props.fetched?
<div>
<Grid container>
<Grid item xs={12} sm={12} lg={12} md={12} style={{textAlign: "center"}} justify="center" align="center" >
<div>
<p class="paras"></p>
</div>
<div class="card-blocks">
<p class="white-texts"> <img src={photo} height="150" width="150" className="rounded-circles"/></p>
<h3>{name}</h3>
</div>
</Grid>
</Grid>
<div className="gridcard">
<Grid container >
{details.map((val)=>{
return(
<Grid xs={12} sm={4} lg={4} md={4} style={{textAlign: "center"}} justify="center" align="center" className="profiledetailcard" >
<div>
<Card>
{ <div><img src={val.logo
} height={150} width={150}/></div> }
<span><h4 className="profilesubject">{val.subject
}</h4></span>
<hr/>
<div className="userdetails">
<span className="userdetail">Attempted<h6>{val.attempted
}</h6></span>
<span className="userdetail">Right<h6>{val.right
}</h6></span>
<span className="userdetail">Accuracy<h6>{Math.round(val.accuracy * 100) / 100
}%</h6></span>
</div>
</Card>
</div>
</Grid>
)
})}
{/* {details.map((val) => {
<Grid item xs={12} sm={12} lg={12} md={12} style={{textAlign: "center"}} justify="center" align="center" className="profilepersonname" >
{val.subject}
{val.logo}
{val.attempted}
{val.right}
{val.accuracy}
</Grid>
})} */}
</Grid>
</div>
</div>
: <div>Loading... </div>
}
</div>
</Card>
)
}
}
const mapStateToProps = state => {
return {
data: state.maindashboard.individualprofile,
fetched : state.maindashboard.fetchedindividualprofile,
};
};
export default connect(mapStateToProps , {})(IndividualProfile); |
const { Command } = require("../../../index");
module.exports = class extends Command {
constructor(...args) {
super(...args, {
runIn: ["text"],
cooldown: 10,
aliases: ["twm", "togglewelcomemessages"],
permissionLevel: 6,
requiredPermissions: ["USE_EXTERNAL_EMOJIS"],
description: language => language.get("COMMAND_TOGGLE_WELCOME_DESCRPTION"),
extendedHelp: "No extended help available."
});
}
async run(msg) {
if (!msg.guild.settings.get("toggles.joinmsg")) {
if (!msg.guild.channels.cache.get(msg.guild.settings.get("channels.join"))) { await msg.guild.settings.update("channels.join", msg.channel.id); }
if (!msg.guild.settings.get("messages.join")) await msg.guild.settings.update("messages.join", "Welcome {MENTION} to {SERVER}, we hope you enjoy your stay!", { action: "add" });
return msg.guild.settings.update("toggles.joinmsg", true).then(() => {
msg.sendMessage(`${this.client.emotes.check} ***${msg.language.get("MESSAGE_WLCM_ENABLED")}***`);
});
} else {
return msg.guild.settings.update("toggles.joinmsg", false).then(() => {
msg.sendMessage(`${this.client.emotes.cross} ***${msg.language.get("MESSAGE_WLCM_DISABLED")}***`);
});
}
}
};
|
import React from 'react';
export default class Svg extends React.Component {
constructor(props) {
super(props);
}
render() {
const {
children,
version = '1.1',
xmlns = 'http://www.w3.org/2000/svg',
...others
} = this.props;
return (
<svg version={version} xmlns={xmlns} {...others}>
{children}
</svg>
);
}
} |
define(['knockout', 'gc/gc'], function (ko, gc) {
return {
getCouponPromotion: function(id) {
self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.get({
url: '/api/v1/coupon-promotions/' + id,
fields: [ '-attribute', '-productLists' ],
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
cloneCouponPromotion: function(id) {
self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.get({
url: '/api/v1/coupon-promotions/clone/' + id,
fields: [ '-attribute' ],
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
getCouponPromotions: function() {
self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.get({
url: '/api/v1/coupon-promotions/',
fields: [ '-attribute' ],
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
getCoupons: function() {
self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.get({
url: '/api/v1/coupon-promotions/coupons',
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
createCouponPromotion: function(couponPromotion) {
var self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.post({
url : '/api/v1/coupon-promotions',
data: couponPromotion,
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
updateCouponPromotion: function(id, updateModel) {
self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.put({
url: '/api/v1/coupon-promotions/' + id,
data: updateModel.data(),
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
removeCouponPromotion: function(id) {
var self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.del({
url : '/api/v1/coupon-promotions/' + id,
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
addProductListToPromotion: function(promotionId, productListId) {
var self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.put({
url : '/api/v1/coupon-promotions/' + promotionId + '/product-list/' + productListId,
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
removeProductListFromPromotion: function(promotionId, productListId) {
var self = this;
var deferred = new $.Deferred();
var promise = deferred.promise();
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.done;
gc.rest.del({
url : '/api/v1/coupon-promotions/' + promotionId + '/product-list/' + productListId,
success : function(data, status, xhr) {
if (self._onload) {
self._onload(data, status, xhr);
}
deferred.resolve(data, status, xhr);
},
error : function(jqXHR, status, error) {
if (self._onerror) {
self._onerror(jqXHR, status, error);
}
deferred.reject(jqXHR, status, error);
},
complete : function(data, status, xhr) {
if (self._oncomplete) {
self._oncomplete(data, status, xhr);
}
deferred.resolve(data, status, xhr);
}
});
return promise;
},
getProductListPagingOptions: function(couponPromotionId, pagingOptions) {
pagingOptions = pagingOptions || {};
return {
url: '/api/v1/coupon-promotions/' + couponPromotionId + '/notPromotionProductLists',
filter: pagingOptions.filter || {},
// Only load specific fields for better performance.
fields: pagingOptions.fields || ['key', 'label'],
// Optionally pre-sort the results.
sort: pagingOptions.sort || ['key'],
columns: pagingOptions.columns,
// Returns an array that the pager can add to the
// ko.observableArray.
getArray: function(data) {
return data.productLists;
}
}
},
getPagingOptions: function(pagingOptions) {
pagingOptions = pagingOptions || {};
return {
url: '/api/v1/coupon-promotions/',
filter: pagingOptions.filter || {},
// Only load specific fields for better performance.
fields: pagingOptions.fields || ['id', 'label', 'enabled'],
// Optionally pre-sort the results.
sort: pagingOptions.sort || ['id'],
columns: pagingOptions.columns,
// Returns an array that the pager can add to the
// ko.observableArray.
getArray: function(data) {
return data.couponPromotions;
}
// ----------------------------------------------------------------
// Mapping used by the ko.mapping plugin.
// ----------------------------------------------------------------
}
}
}
}); |
from .object import Object, ExtensibleObject
from .bootstrap import createFile, initModule
from .frozendict import FrozenDict
from . import typemixins
__all__ = ['Object', 'ExtensibleObject', 'Codec', 'typemixins']
|
#
# This class is automatically generated by mig. DO NOT EDIT THIS FILE.
# This class implements a Python interface to the 'ReadToastVersionCmdMsg'
# message type.
#
from tinyos.message.Message import Message
# The default size of this message type in bytes.
DEFAULT_MESSAGE_SIZE = 1
# The Active Message type associated with this message.
AM_TYPE = 168
class ReadToastVersionCmdMsg(Message):
# Create a new ReadToastVersionCmdMsg of size 1.
def __init__(self, data="", addr=None, gid=None, base_offset=0, data_length=1):
Message.__init__(self, data, addr, gid, base_offset, data_length)
self.amTypeSet(AM_TYPE)
self.set_tag(0x02)
# Get AM_TYPE
def get_amType(cls):
return AM_TYPE
get_amType = classmethod(get_amType)
#
# Return a String representation of this message. Includes the
# message type name and the non-indexed field values.
#
def __str__(self):
s = "Message <ReadToastVersionCmdMsg> \n"
try:
s += " [tag=0x%x]\n" % (self.get_tag())
except:
pass
return s
# Message-type-specific access methods appear below.
#
# Accessor methods for field: tag
# Field type: short
# Offset (bits): 0
# Size (bits): 8
#
#
# Return whether the field 'tag' is signed (False).
#
def isSigned_tag(self):
return False
#
# Return whether the field 'tag' is an array (False).
#
def isArray_tag(self):
return False
#
# Return the offset (in bytes) of the field 'tag'
#
def offset_tag(self):
return (0 / 8)
#
# Return the offset (in bits) of the field 'tag'
#
def offsetBits_tag(self):
return 0
#
# Return the value (as a short) of the field 'tag'
#
def get_tag(self):
return self.getUIntElement(self.offsetBits_tag(), 8, 1)
#
# Set the value of the field 'tag'
#
def set_tag(self, value):
self.setUIntElement(self.offsetBits_tag(), 8, value, 1)
#
# Return the size, in bytes, of the field 'tag'
#
def size_tag(self):
return (8 / 8)
#
# Return the size, in bits, of the field 'tag'
#
def sizeBits_tag(self):
return 8
|
function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
var quotes = [
["You only live once, but if you do it right, once is enough.","Mae West"],
["Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.","Albert Einstein"],
["The most beautiful experience we can have is the mysterious. It is the fundamental emotion that stands at the cradle of true art and true science.","Albert Einstein"],
["It is our choices, Harry, that show what we truly are, far more than our abilities.","J.K. Rowling, Harry Potter and the Chamber of Secrets"],
["Trust yourself. You know more than you think you do.","Benjamin Spock"],
["To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment.","Ralph Waldo Emerson"],
["Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore. Dream. Discover.","H. Jackson Brown Jr., P.S. I Love You"],
["Genius is 1% inspiration and 99% perspiration.","Thomas Edison"],
["Intelligence is the ability to adapt to change.","Stephen Hawking"],
["God not only plays dice, He also sometimes throws the dice where they cannot be seen.","Stephen Hawking"],
["The secret of getting ahead is getting started.","Mark Twain"],
["Keep your eyes on the star, and your feet on the ground.","Theodore Roosevelt"],
["Do the difficult things while they are easy and do the great things while they are small. A journey of a thousand miles must begin with a single step.","Lao Tzu"],
["Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it.", "Steve Jobs"]
];
var currentQuote = "";
var currentAuthor = "";
var randomquote = "";
function getQuote() {
randomquote = Math.floor(Math.random() * quotes.length);
currentQuote = quotes[randomquote][0];
currentAuthor = quotes[randomquote][1];
if (inIframe()) {
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=aLamm&text=' + encodeURIComponent('"' + currentQuote + '" ' + currentAuthor));
}
$(document).ready(function () {
$('#quotetext').animate({ opacity: 0 }, 500, function () {
$(this).animate({ opacity: 1 }, 500);
$(this).text(currentQuote);
});
$('#quotesource').animate({ opacity: 0 }, 500, function () {
$(this).animate({ opacity: 1 }, 500);
$(this).text(currentAuthor);
});
});
}
getQuote();
$(document).ready(function () {
setInterval("getQuote()", 10000); // Time in milliseconds
});
|
import os
from codecs import open
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
os.chdir(here)
version_contents = {}
with open(os.path.join(here, "firstclasspostcodes", "version.py"), encoding="utf-8") as f:
exec(f.read(), version_contents)
setup(
name='firstclasspostcodes',
version=version_contents["VERSION"],
url='https://github.com/firstclasspostcodes/firstclasspostcodes-python',
license='MIT',
keywords="firstclasspostcodes postcode uk api",
author='Firstclasspostcodes',
author_email='[email protected]',
description="Python bindings for the Firstclasspostcodes API",
packages=find_packages(exclude=['tests', 'tests.*']),
long_description=open('README.md').read(),
install_requires=[
'requests >= 2.20; python_version >= "3.0"',
'requests[security] >= 2.20; python_version < "3.0"',
],
project_urls={
"Bug Tracker": "https://github.com/firstclasspostcodes/firstclasspostcodes-python/issues",
"Documentation": "https://github.com/firstclasspostcodes/firstclasspostcodes-python",
"Source Code": "https://github.com/firstclasspostcodes/firstclasspostcodes-python",
},
zip_safe=False
)
|
import { css } from "@emotion/react";
export const UnitStyle = (theme) => css`
font-size: 0.8em;
color: ${theme.color.heavyGrey};
`;
|
/**
* @author Ichen.chu
* created on 01.03.2018
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.myInput', [
])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
}
})();
|
import request from 'request';
import xss from 'xss';
const fetchLyricsPage = (title, artist) =>
new Promise((resolve, reject) => {
const search = `http://www.lyricsfreak.com/search.php?a=search&type=song&q=${title.replace(/ /g, '+')}`;
request(search, (err, resp) => {
try {
if (err) return reject(err);
const HTML = JSON.stringify(resp.body);
let lyricsTable = HTML.split('tbody')[1];
lyricsTable = lyricsTable.replace(/\\r/g, '');
const trackRegEx = /<tr>[\s\S]+?><a[\s\S]+?·[ ]+(.+?)<[\s\S]+?<a href=\\"(.+?)\\"[\s\S]+?>(.+?) lyrics<\/a>[\s\S]+?<\/tr>/g;
let match = trackRegEx.exec(lyricsTable);
const tracks = [];
while (match !== null) {
const track = {
artist: match[1].trim(),
url: `http://www.lyricsfreak.com${match[2].trim()}`,
track: match[3].trim(),
};
tracks.push(track);
match = trackRegEx.exec(lyricsTable);
}
for (let i = 0; i < tracks.length; i++) {
const track = tracks[i];
if (track.artist.toLowerCase() === artist.toLowerCase()) {
return resolve(track.url);
}
}
} catch (e) {
// Who cares
}
return reject('Could not find track');
});
});
const fetchLyrics = (track, artist) =>
fetchLyricsPage(track, artist)
.then((url) =>
new Promise((resolve, reject) => {
request(url, (err, resp) => {
if (err) return reject(err);
try {
let lyrics = /<div id='content[\s\S]+?>([\s\S]+?)<\/div>/g.exec(resp.body)[1];
lyrics = lyrics.replace(/<br>/gi, '\n');
resolve(xss(lyrics, {
whiteList: { br: [], i: [], b: [], strong: [], em: [] },
stripIgnoreTag: true,
stripIgnoreTagBody: ['script'],
}));
} catch (e) {
reject(e);
}
});
})
);
export default fetchLyrics;
|
import validateHttpStatus from '../validate-http-status';
/**
* @description
* Validate HTTP Status code 401 type CLIENT ERROR
*
* @param {Integer} statusCode - The HTTP Status code
* @return {Boolean}
* @throws {HTTPStatusError} When the statusCode is different then 401
*/
function isUnauthorized(statusCode) {
return validateHttpStatus(statusCode, 401);
}
export default isUnauthorized;
|
#!/usr/bin/env node
const os = require('os');
const program = require('commander');
const path = require('path');
const fse = require('fs-extra');
const fs = require('fs');
const Registry = require('./registry').Registry;
const DockerRegistry = require('./registry').DockerRegistry;
const appLayerCreator = require('./appLayerCreator');
const fileutil = require('./fileutil');
const tarExporter = require('./tarExporter');
const logger = require('./logger');
const possibleArgs = {
'--fromImage <name:tag>' : 'Required: Image name of base image - [path/]image:tag',
'--toImage <name:tag>' : 'Required: Image name of target image - [path/]image:tag',
'--folder <full path>' : 'Required: Base folder of node application (contains package.json)',
'--fromRegistry <registry url>' : 'Optional: URL of registry to pull base image from - Default: https://registry-1.docker.io/v2/',
'--fromToken <token>' : 'Optional: Authentication token for from registry',
'--toRegistry <registry url>' : 'Optional: URL of registry to push base image to - Default: https://registry-1.docker.io/v2/',
'--toToken <token>' : 'Optional: Authentication token for target registry',
'--toTar <path>' : 'Optional: Export to tar file',
'--registry <path>' : 'Optional: Convenience argument for setting both from and to registry',
'--token <path>' : 'Optional: Convenience argument for setting token for both from and to registry',
'--user <user>' : 'Optional: User account to run process in container - default: 1000',
'--workdir <directory>' : 'Optional: Workdir where node app will be added and run from - default: /app',
'--entrypoint <entrypoint>' : 'Optional: Entrypoint when starting container - default: npm start',
'--labels <labels>' : 'Optional: Comma-separated list of key value pairs to use as labels',
'--label <label>' : 'Optional: Single label (name=value). This option can be used multiple times.',
'--setTimeStamp <timestamp>' : 'Optional: Set a specific ISO 8601 timestamp on all entries (e.g. git commit hash). Default: 1970 in tar files, and current time on manifest/config',
'--verbose' : 'Verbose logging',
'--allowInsecureRegistries' : 'Allow insecure registries (with self-signed/untrusted cert)',
'--customContent <dirs/files>' : 'Optional: Skip normal node_modules and applayer and include specified root folder files/directories instead',
'--extraContent <dirs/files>' : 'Optional: Add specific content. Specify as local-path:absolute-container-path,local-path2:absolute-container-path2 etc',
'--layerOwner <gid:uid>' : 'Optional: Set specific gid and uid on files in the added layers',
'--buildFolder <path>' : 'Optional: Use a specific build folder when creating the image',
};
const keys = Object.keys(possibleArgs)
.map(k => k.split(' ')[0].replace('--', ''));
let labels = {};
program.on('option:label', (ops) => {
//Can't use split here, because = might be in the label value
let splitPoint = ops.indexOf("=");
labels[ops.substr(0, splitPoint)] = ops.substring(splitPoint+1);
});
Object.keys(possibleArgs)
.reduce((program, k) => program.option(k, possibleArgs[k]), program)
.parse(process.argv);
let options = {
workdir : '/app',
user: '1000',
entrypoint: 'npm start'
};
keys.map(k => options[k] = program[k] || options[k]);
delete options["label"];
function splitLabelsIntoObject(labelsString) {
let labels = {};
labelsString.split(',').map(l => l.split('=')).map(l => labels[l[0]] = l[1]);
return labels;
}
let labelsOpt = options.labels ? splitLabelsIntoObject(options.labels) : {};
Object.keys(labels).map(k => labelsOpt[k] = labels[k]);
options.labels = labelsOpt;
function exitWithErrorIf(check, error) {
if (check) {
logger.error('ERROR: ' + error);
program.outputHelp();
process.exit(1);
}
}
if (options.verbose) logger.enableDebug();
if (options.allowInsecureRegistries) process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
exitWithErrorIf(options.registry && options.fromRegistry, 'Do not set both --registry and --fromRegistry');
exitWithErrorIf(options.registry && options.toRegistry, 'Do not set both --registry and --toRegistry');
exitWithErrorIf(options.token && options.fromToken, 'Do not set both --token and --fromToken');
exitWithErrorIf(options.token && options.toToken, 'Do not set both --token and --toToken');
if (options.setTimeStamp) {
try {
options.setTimeStamp = new Date(options.setTimeStamp);
} catch(e) {
exitWithErrorIf(true, 'Failed to parse date: ' + e);
}
logger.info('Setting all dates to: ' + options.setTimeStamp);
}
if (options.layerOwner) {
if (!options.layerOwner.match("^[0-9]+:[0-9]+$")) {
exitWithErrorIf(true, 'layerOwner should be on format <number>:<number> (e.g. 1000:1000) but was: ' + options.layerOwner);
}
}
if (options.registry) {
options.fromRegistry = options.registry;
options.toRegistry = options.registry;
}
if (options.token) {
options.fromToken = options.token;
options.toToken = options.token;
}
exitWithErrorIf(!options.folder, '--folder must be specified');
exitWithErrorIf(!options.fromImage, '--fromImage must be specified');
exitWithErrorIf(!options.toImage, '--toImage must be specified');
exitWithErrorIf(!options.toRegistry && !options.toTar, 'Must specify either --toTar or --toRegistry');
exitWithErrorIf(!options.toRegistry && !options.toToken && !options.toTar, 'A token must be given when uploading to docker hub');
if(options.toRegistry && options.toRegistry.substr(-1) != '/') options.toRegistry += '/';
if(options.fromRegistry && options.fromRegistry.substr(-1) != '/') options.fromRegistry += '/';
if (!options.fromRegistry && !options.fromImage.split(':')[0].includes('/')) {
options.fromImage = 'library/' + options.fromImage;
}
if (options.customContent) {
options.customContent = options.customContent.split(",");
options.customContent.forEach(p => {
exitWithErrorIf(!fs.existsSync(p), 'Could not find ' + p + ' in the base folder ' + options.folder)
});
}
if (options.extraContent) {
options.extraContent = options.extraContent.split(",").map(x => x.split(":"));
options.extraContent.forEach(p => {
exitWithErrorIf(p.length != 2, 'Invalid extraContent - use comma between files/dirs, and : to separate local path and container path')
exitWithErrorIf(!fs.existsSync(p[0]), 'Could not find ' + p[0] + ' in the base folder ' + options.folder)
});
}
async function run(options) {
if (!(await fse.pathExists(options.folder))) throw new Error('No such folder: ' + options.folder);
const tmpdir = require('fs').mkdtempSync(path.join(os.tmpdir(),'doqr-'));
logger.debug('Using ' + tmpdir);
let fromdir = await fileutil.ensureEmptyDir(path.join(tmpdir, 'from'));
let todir = await fileutil.ensureEmptyDir(path.join(tmpdir, 'to'));
let fromRegistry = options.fromRegistry ? new Registry(options.fromRegistry, options.fromToken) : new DockerRegistry(options.fromToken);
await fromRegistry.download(options.fromImage, fromdir);
await appLayerCreator.addLayers(tmpdir, fromdir, todir, options);
if (options.toTar) {
await tarExporter.saveToTar(todir, tmpdir, options.toTar, options.toImage, options);
}
if (options.toRegistry) {
let toRegistry = new Registry(options.toRegistry, options.toToken);
await toRegistry.upload(options.toImage, todir);
}
logger.debug('Deleting ' + tmpdir + ' ...');
await fse.remove(tmpdir);
logger.debug('Done');
}
run(options).then(() => {
logger.info('Done!');
process.exit(0);
}).catch(error => {
logger.error(error);
process.exit(1);
});
|
# Copyright (c) 2020, NVIDIA CORPORATION.
# Copyright (c) 2021 PaddlePaddle Authors. 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.
import time
import os
import numpy as np
import paddle
from paddle.io import DataLoader, Dataset
from paddlenlp.data import Stack, Tuple, Pad
from paddlenlp.utils.log import logger
def construct_samples_and_shuffle_data(name, data_prefix, documents, sizes,
num_samples, seq_length, seed,
build_data_file):
"""
documents: document index from 0 to len(docs)
sizes: the length list of all docs.
num_samples: total step*bs iterations of data.
seq_length: the sequence length.
sum(sizes) = tokens_per_epoch
data_nums = num_samples * micro_batch_size
num_epochs = (data_nums + 1) // sum(sizes)
len(doc_idx) = num_epochs * sum(sizes)
"""
# Number of tokens in each epoch and number of required epochs.
tokens_per_epoch = _num_tokens(documents, sizes)
num_epochs = _num_epochs(tokens_per_epoch, seq_length, num_samples)
# Rng state
np_rng = np.random.RandomState(seed=seed)
# Filename of the index mappings.
_filename = data_prefix
_filename += '_{}_indexmap'.format(name)
_filename += '_{}ns'.format(num_samples)
_filename += '_{}sl'.format(seq_length)
doc_idx_filename = _filename + '_doc_idx.npy'
sample_idx_filename = _filename + '_sample_idx.npy'
shuffle_idx_filename = _filename + '_shuffle_idx.npy'
# Build the indexed mapping if not exist.
if build_data_file:
if (not os.path.isfile(doc_idx_filename)) or \
(not os.path.isfile(sample_idx_filename)) or \
(not os.path.isfile(shuffle_idx_filename)):
if num_epochs == 1:
separate_last_epoch = False
else:
num_samples_from_epochs_minus_one = (
(num_epochs - 1) * tokens_per_epoch - 1) // seq_length
last_epoch_num_samples = num_samples - \
num_samples_from_epochs_minus_one
assert last_epoch_num_samples >= 0, \
'last epoch number of samples should be non-negative.'
num_samples_per_epoch = (tokens_per_epoch - 1) // seq_length
assert last_epoch_num_samples < (num_samples_per_epoch + 1), \
'last epoch number of samples exceeded max value.'
separate_last_epoch = (
last_epoch_num_samples < int(0.80 * num_samples_per_epoch))
# Note. len(doc_idx) = num_epochs * len(doc)
doc_idx = _build_doc_idx(documents, num_epochs, np_rng,
separate_last_epoch)
np.save(doc_idx_filename, doc_idx, allow_pickle=True)
# sample-idx. pos of each seq_len of data.
assert doc_idx.dtype == np.int32
sample_idx = _build_sample_idx(sizes, doc_idx, seq_length,
num_epochs, tokens_per_epoch)
np.save(sample_idx_filename, sample_idx, allow_pickle=True)
if separate_last_epoch:
num_samples_ = num_samples_from_epochs_minus_one
else:
num_samples_ = sample_idx.shape[0] - 1
# Shuffle all seq len data.
shuffle_idx = _build_shuffle_idx(num_samples_,
sample_idx.shape[0] - 1, np_rng)
np.save(shuffle_idx_filename, shuffle_idx, allow_pickle=True)
else:
while True:
if (not os.path.isfile(doc_idx_filename)) or \
(not os.path.isfile(sample_idx_filename)) or \
(not os.path.isfile(shuffle_idx_filename)):
time.sleep(3)
else:
break
# Load mappings.
doc_idx = np.load(doc_idx_filename, allow_pickle=True, mmap_mode='r')
sample_idx = np.load(sample_idx_filename, allow_pickle=True, mmap_mode='r')
shuffle_idx = np.load(
shuffle_idx_filename, allow_pickle=True, mmap_mode='r')
return doc_idx, sample_idx, shuffle_idx
def _num_tokens(documents, lens):
"""Total number of tokens in the dataset."""
return np.sum(lens[documents])
def _num_epochs(tokens_per_epoch, seq_length, num_samples):
"""Based on number of samples and sequence lenght, calculate how many
epochs will be needed."""
num_epochs = 0
total_tokens = 0
while True:
num_epochs += 1
total_tokens += tokens_per_epoch
if ((total_tokens - 1) // seq_length) >= num_samples:
return num_epochs
def _build_doc_idx(documents, num_epochs, np_rng, separate_last_epoch):
"""
Build an array with length = number-of-epochs * number-of-documents.
Each index is mapped to a corresponding document.
"""
if not separate_last_epoch or num_epochs == 1:
doc_idx = np.mgrid[0:num_epochs, 0:len(documents)][1]
doc_idx[:] = documents
# The documents repeat num_epochs times.
doc_idx = doc_idx.reshape(-1)
doc_idx = doc_idx.astype(np.int32)
return doc_idx
doc_idx_first = _build_doc_idx(documents, num_epochs - 1, np_rng, False)
doc_idx_last = _build_doc_idx(documents, 1, np_rng, False)
return np.concatenate((doc_idx_first, doc_idx_last))
def _build_sample_idx(sizes, doc_idx, seq_length, num_epochs, tokens_per_epoch):
"""
num_samples + 1, pos of bs data
the distance between two points for sample idx is bs tokens.
"""
num_samples = (num_epochs * tokens_per_epoch - 1) // seq_length
sample_idx = np.zeros([int(num_samples) + 1, 2], dtype=np.int32)
sample_index = 0
doc_idx_index = 0
doc_offset = 0
sample_idx[sample_index][0] = doc_idx_index
sample_idx[sample_index][1] = doc_offset
sample_index += 1
while sample_index <= num_samples:
remaining_seq_length = seq_length + 1
while remaining_seq_length != 0:
doc_id = doc_idx[doc_idx_index]
doc_length = sizes[doc_id] - doc_offset
remaining_seq_length -= doc_length
if remaining_seq_length <= 0:
doc_offset += (remaining_seq_length + doc_length - 1)
remaining_seq_length = 0
else:
doc_idx_index += 1
doc_offset = 0
sample_idx[sample_index][0] = doc_idx_index
sample_idx[sample_index][1] = doc_offset
sample_index += 1
return sample_idx
def _build_shuffle_idx(num_samples, total_size, np_rng):
dtype_ = np.uint32
if total_size >= (np.iinfo(np.uint32).max - 1):
dtype_ = np.int64
shuffle_idx_first = np.arange(
start=0, stop=num_samples, step=1, dtype=dtype_)
np_rng.shuffle(shuffle_idx_first)
if num_samples == total_size:
return shuffle_idx_first
shuffle_idx_last = np.arange(
start=num_samples, stop=total_size, step=1, dtype=dtype_)
np_rng.shuffle(shuffle_idx_last)
return np.concatenate((shuffle_idx_first, shuffle_idx_last))
def get_train_valid_test_split_(splits_string, size):
""" Get dataset splits from comma or '/' separated string list."""
splits = []
if splits_string.find(',') != -1:
splits = [float(s) for s in splits_string.split(',')]
elif splits_string.find('/') != -1:
splits = [float(s) for s in splits_string.split('/')]
else:
splits = [float(splits_string)]
while len(splits) < 3:
splits.append(0.)
splits = splits[:3]
splits_sum = sum(splits)
assert splits_sum > 0.0
splits = [split / splits_sum for split in splits]
splits_index = [0]
for index, split in enumerate(splits):
splits_index.append(splits_index[index] + int(
round(split * float(size))))
diff = splits_index[-1] - size
for index in range(1, len(splits_index)):
splits_index[index] -= diff
assert len(splits_index) == 4
assert splits_index[-1] == size
return splits_index
def create_pretrained_dataset(
args,
input_path,
data_world_rank,
data_world_size,
eos_id,
worker_init=None,
max_seq_len=1024,
places=None,
data_holders=None,
pipeline_mode=False, ):
device_world_size = paddle.distributed.get_world_size()
device_world_rank = paddle.distributed.get_rank()
logger.info(
"The distributed run, total device num:{}, distinct dataflow num:{}.".
format(device_world_size, data_world_size))
process_datas = np.load(input_path, mmap_mode="r+", allow_pickle=True)
# All documment ids, extend as 1-D array.
sample_ids = process_datas["ids"]
# The len(sample_lens) num of docs
# The sum(sample_lens) should equal len(sample_ids)
sample_lens = process_datas["lens"]
splits = get_train_valid_test_split_(args.split, len(sample_lens))
assert len(sample_lens) >= splits[
-1], "The document nums should larger than max of splits, but %s < %s" % (
len(sample_lens), splits[-1])
def build_dataset(index, name, num_samples):
dataset = GPTDataset(
file_path=input_path,
build_data_file=device_world_rank == 0,
micro_batch_size=args.micro_batch_size,
name="gpt_" + name,
max_seq_len=max_seq_len,
num_samples=num_samples,
documents=np.arange(splits[index], splits[index + 1]),
sample_ids=sample_ids,
sample_lens=sample_lens,
eos_id=eos_id,
seed=args.seed)
batch_sampler = paddle.io.DistributedBatchSampler(
dataset,
batch_size=args.micro_batch_size,
num_replicas=data_world_size,
rank=data_world_rank,
shuffle=False,
drop_last=True)
if pipeline_mode:
def data_gen():
for data in dataset:
yield tuple(
[np.expand_dims(
np.array(x), axis=0) for x in data])
data_loader = paddle.fluid.io.DataLoader.from_generator(
feed_list=data_holders, capacity=70, iterable=False)
data_loader.set_batch_generator(data_gen, places)
else:
data_loader = DataLoader(
dataset=dataset,
places=places,
feed_list=data_holders,
batch_sampler=batch_sampler,
num_workers=0,
worker_init_fn=worker_init,
collate_fn=Tuple(Stack(), Stack(), Stack(), Stack(), Stack()),
return_list=False)
return data_loader
# Note, data should be broardcast to all devices.
# for train, valid, test, the distinct data num is data_world_size
train_data_loader = build_dataset(0, "train", args.micro_batch_size *
args.max_steps * data_world_size)
if pipeline_mode:
valid_data_loader, test_data_loader = None, None
else:
valid_data_loader = build_dataset(1, "valid", args.micro_batch_size *
(args.max_steps // args.eval_freq + 1)
* args.eval_iters * data_world_size)
test_data_loader = build_dataset(2, "test", args.micro_batch_size *
args.test_iters * data_world_size)
return train_data_loader, valid_data_loader, test_data_loader
class GPTDataset(paddle.io.Dataset):
def __init__(self,
file_path,
micro_batch_size,
num_samples,
eos_id,
sample_ids,
sample_lens,
documents=None,
build_data_file=False,
name="gpt",
max_seq_len=1024,
seed=1234):
self.file_path = file_path
self.max_seq_len = max_seq_len
self.name = name
self.eos_id = eos_id
self.sample_ids = sample_ids
self.sample_lens = sample_lens
self.micro_batch_size = micro_batch_size
if documents is None:
document_ids = np.arange(0, self.sample_lens.shape[0])
else:
document_ids = documents
self.doc_idx, self.sample_idx, self.shuffle_idx = \
construct_samples_and_shuffle_data(self.name, self.file_path, document_ids,\
self.sample_lens, num_samples, max_seq_len, seed, build_data_file)
# The doc cumsum start pos
self.start_pos = [0] + np.cumsum(self.sample_lens).tolist()
def _construct_sample(self, tokens):
tokens = np.array(tokens).astype("int64").tolist()
labels = tokens[1:]
tokens = tokens[:-1]
seq_length = len(tokens)
# Attention mask for the attention calulate
attention_mask = np.tri(seq_length, seq_length).reshape((1, seq_length,
seq_length))
# The pad and eos tokens do not contribute the loss
loss_mask = np.ones(seq_length, dtype="float32")
loss_mask[np.where(np.array(tokens) == self.eos_id)] = 0.0
position_ids = np.arange(0, seq_length, dtype="int64")
attention_mask = (attention_mask - 1.0) * 1e9
attention_mask = attention_mask.astype("float32")
return [tokens, loss_mask, attention_mask, position_ids, labels]
def _get_single_sample_from_idx(self, doc_index_f, doc_index_l, offset_f,
offset_l):
"""
The input means:
doc_index_f: data from the first doc.
doc_index_l: data from the last doc.
offset_f: offset of the first doc.
offset_l: offset of the last doc.
"""
# Data from the sample doc. just select the needed ids.
if doc_index_f == doc_index_l:
current_start_pos = self.start_pos[self.doc_idx[doc_index_f]]
return self.sample_ids[current_start_pos+offset_f:\
current_start_pos+offset_l+1].tolist()
# Data from multi docs.
else:
current_start_pos = self.start_pos[self.doc_idx[doc_index_f]]
next_start_pos = self.start_pos[self.doc_idx[doc_index_f] + 1]
tokens = self.sample_ids[current_start_pos + offset_f:
next_start_pos].tolist()
for i in range(doc_index_f + 1, doc_index_l):
current_start_pos = self.start_pos[self.doc_idx[i]]
next_start_pos = self.start_pos[self.doc_idx[i] + 1]
tokens.extend(self.sample_ids[current_start_pos:next_start_pos]
.tolist())
last_start_pos = self.start_pos[self.doc_idx[doc_index_l]]
tokens.extend(self.sample_ids[last_start_pos:last_start_pos +
offset_l + 1].tolist())
return tokens
def __getitem__(self, index):
idx = self.shuffle_idx[index]
# Start and end documents and offsets.
doc_index_f = self.sample_idx[idx][0]
doc_index_l = self.sample_idx[idx + 1][0]
offset_f = self.sample_idx[idx][1]
offset_l = self.sample_idx[idx + 1][1]
tokens = self._get_single_sample_from_idx(doc_index_f, doc_index_l,
offset_f, offset_l)
return self._construct_sample(tokens)
def __len__(self):
return self.sample_idx.shape[0] - 1
|
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Plugins:
| 1- Leaflet: Interactive maps
|--------------------------------------------------------------------------
*/
mix.styles('node_modules/leaflet/dist/leaflet.css', 'public/plugins/leaflet/leaflet.min.css');
mix.scripts('node_modules/leaflet/dist/leaflet.js', 'public/plugins/leaflet/leaflet.min.js');
mix.copy('node_modules/leaflet/dist/images', 'public/plugins/leaflet/images');
/*
|--------------------------------------------------------------------------
| bootstrap, font-awesome
|--------------------------------------------------------------------------
*/
mix.styles('node_modules/font-awesome/css/font-awesome.min.css', 'public/css/font-awesome.min.css');
mix.styles('node_modules/bootstrap/dist/css/bootstrap.min.css', 'public/css/bootstrap.min.css');
mix.copy('node_modules/bootstrap/dist/fonts', 'public/fonts');
mix.copy('node_modules/font-awesome/fonts', 'public/fonts');
mix.copy('node_modules/ionicons/fonts', 'public/fonts');
mix.copy('node_modules/et-line/fonts', 'public/fonts');
mix.copy('resources/assets/images', 'public/images');
mix.styles('resources/assets/css/style.css', 'public/css/style.min.css');
mix.styles('resources/assets/css/plugin.css', 'public/css/plugin.min.css');
mix.styles('resources/assets/css/pricing.css', 'public/css/pricing.min.css');
mix.styles('resources/assets/css/error.css', 'public/css/error.min.css');
mix.scripts('node_modules/jquery/dist/jquery.min.js', 'public/js/jquery.min.js');
mix.scripts('node_modules/bootstrap/dist/js/bootstrap.min.js', 'public/js/bootstrap.min.js');
mix.scripts('resources/assets/js/plugin.js', 'public/js/plugin.min.js');
mix.scripts('resources/assets/js/main.js', 'public/js/main.min.js');
mix.scripts('resources/assets/js/custom-mixitup.js', 'public/js/custom-mixitup.min.js');
mix.scripts('resources/assets/js/custom-map.js', 'public/js/custom-map.min.js');
mix.scripts('resources/assets/js/custom-video.js', 'public/js/custom-video.min.js');
mix.scripts('resources/assets/js/custom-whatsapp.js', 'public/js/custom-whatsapp.min.js');
|
SystemJS.config({
paths: {
"github:": "jspm_packages/github/",
"npm:": "jspm_packages/npm/"
}
});
|
!function(){"use strict";angular.module("as.sortable",[]).constant("sortableConfig",{itemClass:"as-sortable-item",handleClass:"as-sortable-item-handle",placeHolderClass:"as-sortable-placeholder",dragClass:"as-sortable-drag",hiddenClass:"as-sortable-hidden",dragging:"as-sortable-dragging"})}(),function(){"use strict";var mainModule=angular.module("as.sortable");mainModule.factory("$helper",["$document","$window",function($document,$window){return{height:function(element){return element[0].getBoundingClientRect().height},width:function(element){return element[0].getBoundingClientRect().width},offset:function(element,scrollableContainer){var boundingClientRect=element[0].getBoundingClientRect();return scrollableContainer||(scrollableContainer=$document[0].documentElement),{width:boundingClientRect.width||element.prop("offsetWidth"),height:boundingClientRect.height||element.prop("offsetHeight"),top:boundingClientRect.top+($window.pageYOffset||scrollableContainer.scrollTop-scrollableContainer.offsetTop),left:boundingClientRect.left+($window.pageXOffset||scrollableContainer.scrollLeft-scrollableContainer.offsetLeft)}},eventObj:function(event){var obj=event;return void 0!==event.targetTouches?obj=event.targetTouches.item(0):void 0!==event.originalEvent&&void 0!==event.originalEvent.targetTouches&&(obj=event.originalEvent.targetTouches.item(0)),obj},isTouchInvalid:function(event){var touchInvalid=!1;return void 0!==event.touches&&event.touches.length>1?touchInvalid=!0:void 0!==event.originalEvent&&void 0!==event.originalEvent.touches&&event.originalEvent.touches.length>1&&(touchInvalid=!0),touchInvalid},positionStarted:function(event,target,scrollableContainer){var pos={};return pos.offsetX=event.pageX-this.offset(target,scrollableContainer).left,pos.offsetY=event.pageY-this.offset(target,scrollableContainer).top,pos.startX=pos.lastX=event.pageX,pos.startY=pos.lastY=event.pageY,pos.nowX=pos.nowY=pos.distX=pos.distY=pos.dirAx=0,pos.dirX=pos.dirY=pos.lastDirX=pos.lastDirY=pos.distAxX=pos.distAxY=0,pos},calculatePosition:function(pos,event){pos.lastX=pos.nowX,pos.lastY=pos.nowY,pos.nowX=event.pageX,pos.nowY=event.pageY,pos.distX=pos.nowX-pos.lastX,pos.distY=pos.nowY-pos.lastY,pos.lastDirX=pos.dirX,pos.lastDirY=pos.dirY,pos.dirX=0===pos.distX?0:pos.distX>0?1:-1,pos.dirY=0===pos.distY?0:pos.distY>0?1:-1;var newAx=Math.abs(pos.distX)>Math.abs(pos.distY)?1:0;pos.dirAx!==newAx?(pos.distAxX=0,pos.distAxY=0):(pos.distAxX+=Math.abs(pos.distX),0!==pos.dirX&&pos.dirX!==pos.lastDirX&&(pos.distAxX=0),pos.distAxY+=Math.abs(pos.distY),0!==pos.dirY&&pos.dirY!==pos.lastDirY&&(pos.distAxY=0)),pos.dirAx=newAx},movePosition:function(event,element,pos,container,containerPositioning,scrollableContainer){var bounds,useRelative="relative"===containerPositioning;element.x=event.pageX-pos.offsetX,element.y=event.pageY-pos.offsetY,container&&(bounds=this.offset(container,scrollableContainer),useRelative&&(element.x-=bounds.left,element.y-=bounds.top,bounds.left=0,bounds.top=0),element.x<bounds.left?element.x=bounds.left:element.x>=bounds.width+bounds.left-this.offset(element).width&&(element.x=bounds.width+bounds.left-this.offset(element).width),element.y<bounds.top?element.y=bounds.top:element.y>=bounds.height+bounds.top-this.offset(element).height&&(element.y=bounds.height+bounds.top-this.offset(element).height)),element.css({left:element.x+"px",top:element.y+"px"}),this.calculatePosition(pos,event)},dragItem:function(item){return{index:item.index(),parent:item.sortableScope,source:item,sourceInfo:{index:item.index(),itemScope:item.itemScope,sortableScope:item.sortableScope},moveTo:function(parent,index){this.parent=parent,this.isSameParent()&&this.source.index()<index&&(index-=1),this.index=index},isSameParent:function(){return this.parent.element===this.sourceInfo.sortableScope.element},isOrderChanged:function(){return this.index!==this.sourceInfo.index},eventArgs:function(){return{source:this.sourceInfo,dest:{index:this.index,sortableScope:this.parent}}},apply:function(){this.sourceInfo.sortableScope.options.clone||this.sourceInfo.sortableScope.removeItem(this.sourceInfo.index),(this.parent.options.allowDuplicates||this.parent.modelValue.indexOf(this.source.modelValue)<0)&&this.parent.insertItem(this.index,this.source.modelValue)}}},noDrag:function(element){return void 0!==element.attr("no-drag")||void 0!==element.attr("data-no-drag")},findAncestor:function(el,selector){el=el[0];for(var matches=Element.matches||Element.prototype.mozMatchesSelector||Element.prototype.msMatchesSelector||Element.prototype.oMatchesSelector||Element.prototype.webkitMatchesSelector;(el=el.parentElement)&&!matches.call(el,selector););return el?angular.element(el):angular.element(document.body)}}}])}(),function(){"use strict";var mainModule=angular.module("as.sortable");mainModule.controller("as.sortable.sortableController",["$scope",function($scope){this.scope=$scope,$scope.modelValue=null,$scope.callbacks=null,$scope.type="sortable",$scope.options={},$scope.isDisabled=!1,$scope.insertItem=function(index,itemData){$scope.options.allowDuplicates?$scope.modelValue.splice(index,0,angular.copy(itemData)):$scope.modelValue.splice(index,0,itemData)},$scope.removeItem=function(index){var removedItem=null;return index>-1&&(removedItem=$scope.modelValue.splice(index,1)[0]),removedItem},$scope.isEmpty=function(){return $scope.modelValue&&0===$scope.modelValue.length},$scope.accept=function(sourceItemHandleScope,destScope,destItemScope){return $scope.callbacks.accept(sourceItemHandleScope,destScope,destItemScope)}}]),mainModule.directive("asSortable",function(){return{require:"ngModel",restrict:"A",scope:!0,controller:"as.sortable.sortableController",link:function(scope,element,attrs,ngModelController){var ngModel,callbacks;ngModel=ngModelController,ngModel&&(ngModel.$render=function(){scope.modelValue=ngModel.$modelValue},scope.element=element,element.data("_scope",scope),callbacks={accept:null,orderChanged:null,itemMoved:null,dragStart:null,dragMove:null,dragCancel:null,dragEnd:null},callbacks.accept=function(sourceItemHandleScope,destSortableScope,destItemScope){return!0},callbacks.orderChanged=function(event){},callbacks.itemMoved=function(event){},callbacks.dragStart=function(event){},callbacks.dragMove=angular.noop,callbacks.dragCancel=function(event){},callbacks.dragEnd=function(event){},scope.$watch(attrs.asSortable,function(newVal,oldVal){angular.forEach(newVal,function(value,key){callbacks[key]?"function"==typeof value&&(callbacks[key]=value):scope.options[key]=value}),scope.callbacks=callbacks},!0),angular.isDefined(attrs.isDisabled)&&scope.$watch(attrs.isDisabled,function(newVal,oldVal){angular.isUndefined(newVal)||(scope.isDisabled=newVal)},!0))}}})}(),function(){"use strict";function isParent(possibleParent,elem){return elem&&"HTML"!==elem.nodeName?elem.parentNode===possibleParent?!0:isParent(possibleParent,elem.parentNode):!1}var mainModule=angular.module("as.sortable");mainModule.controller("as.sortable.sortableItemHandleController",["$scope",function($scope){this.scope=$scope,$scope.itemScope=null,$scope.type="handle"}]),mainModule.directive("asSortableItemHandle",["sortableConfig","$helper","$window","$document",function(sortableConfig,$helper,$window,$document){return{require:"^asSortableItem",scope:!0,restrict:"A",controller:"as.sortable.sortableItemHandleController",link:function(scope,element,attrs,itemController){function insertBefore(targetElement,targetScope){"table-row"!==placeHolder.css("display")&&placeHolder.css("display","block"),targetScope.sortableScope.options.clone||(targetElement[0].parentNode.insertBefore(placeHolder[0],targetElement[0]),dragItemInfo.moveTo(targetScope.sortableScope,targetScope.index()))}function insertAfter(targetElement,targetScope){"table-row"!==placeHolder.css("display")&&placeHolder.css("display","block"),targetScope.sortableScope.options.clone||(targetElement.after(placeHolder),dragItemInfo.moveTo(targetScope.sortableScope,targetScope.index()+1))}function fetchScope(element){for(var scope;!scope&&element.length;)scope=element.data("_scope"),scope||(element=element.parent());return scope}function rollbackDragChanges(){placeElement.replaceWith(scope.itemScope.element),placeHolder.remove(),dragElement.remove(),dragElement=null,dragHandled=!1,containment.css("cursor",""),containment.removeClass("as-sortable-un-selectable")}var dragElement,placeHolder,placeElement,itemPosition,dragItemInfo,containment,containerPositioning,dragListen,scrollableContainer,dragStart,dragMove,dragEnd,dragCancel,isDraggable,placeHolderIndex,bindDrag,unbindDrag,bindEvents,unBindEvents,hasTouch,dragHandled,createPlaceholder,isPlaceHolderPresent,escapeListen,isDisabled=!1;hasTouch=$window.hasOwnProperty("ontouchstart"),sortableConfig.handleClass&&element.addClass(sortableConfig.handleClass),scope.itemScope=itemController.scope,element.data("_scope",scope),scope.$watch("sortableScope.isDisabled",function(newVal){isDisabled!==newVal&&(isDisabled=newVal,isDisabled?unbindDrag():bindDrag())}),scope.$on("$destroy",function(){angular.element($document[0].body).unbind("keydown",escapeListen)}),createPlaceholder=function(itemScope){return"function"==typeof scope.sortableScope.options.placeholder?angular.element(scope.sortableScope.options.placeholder(itemScope)):"string"==typeof scope.sortableScope.options.placeholder?angular.element(scope.sortableScope.options.placeholder):angular.element($document[0].createElement(itemScope.element.prop("tagName")))},dragListen=function(event){var startPosition,unbindMoveListen=function(){angular.element($document).unbind("mousemove",moveListen),angular.element($document).unbind("touchmove",moveListen),element.unbind("mouseup",unbindMoveListen),element.unbind("touchend",unbindMoveListen),element.unbind("touchcancel",unbindMoveListen)},moveListen=function(e){e.preventDefault();var eventObj=$helper.eventObj(e);startPosition||(startPosition={clientX:eventObj.clientX,clientY:eventObj.clientY}),Math.abs(eventObj.clientX-startPosition.clientX)+Math.abs(eventObj.clientY-startPosition.clientY)>10&&(unbindMoveListen(),dragStart(event))};angular.element($document).bind("mousemove",moveListen),angular.element($document).bind("touchmove",moveListen),element.bind("mouseup",unbindMoveListen),element.bind("touchend",unbindMoveListen),element.bind("touchcancel",unbindMoveListen)},dragStart=function(event){var eventObj,tagName;(hasTouch||2!==event.button&&3!==event.which)&&(hasTouch&&$helper.isTouchInvalid(event)||!dragHandled&&isDraggable(event)&&(dragHandled=!0,event.preventDefault(),eventObj=$helper.eventObj(event),scope.sortableScope=scope.sortableScope||scope.itemScope.sortableScope,scope.callbacks=scope.callbacks||scope.itemScope.callbacks,scrollableContainer=angular.element($document[0].querySelector(scope.sortableScope.options.scrollableContainer)).length>0?$document[0].querySelector(scope.sortableScope.options.scrollableContainer):$document[0].documentElement,containment=scope.sortableScope.options.containment?$helper.findAncestor(element,scope.sortableScope.options.containment):angular.element($document[0].body),containment.css("cursor","move"),containment.css("cursor","-webkit-grabbing"),containment.css("cursor","-moz-grabbing"),containment.addClass("as-sortable-un-selectable"),containerPositioning=scope.sortableScope.options.containerPositioning||"absolute",dragItemInfo=$helper.dragItem(scope),tagName=scope.itemScope.element.prop("tagName"),dragElement=angular.element($document[0].createElement(scope.sortableScope.element.prop("tagName"))).addClass(scope.sortableScope.element.attr("class")).addClass(sortableConfig.dragClass),dragElement.css("width",$helper.width(scope.itemScope.element)+"px"),dragElement.css("height",$helper.height(scope.itemScope.element)+"px"),placeHolder=createPlaceholder(scope.itemScope).addClass(sortableConfig.placeHolderClass).addClass(scope.sortableScope.options.additionalPlaceholderClass),placeHolder.css("width",$helper.width(scope.itemScope.element)+"px"),placeHolder.css("height",$helper.height(scope.itemScope.element)+"px"),placeElement=angular.element($document[0].createElement(tagName)),sortableConfig.hiddenClass&&placeElement.addClass(sortableConfig.hiddenClass),itemPosition=$helper.positionStarted(eventObj,scope.itemScope.element,scrollableContainer),scope.itemScope.sortableScope.options.clone||scope.itemScope.element.after(placeHolder),scope.itemScope.element.after(placeElement),scope.itemScope.sortableScope.options.clone?dragElement.append(scope.itemScope.element.clone()):dragElement.append(scope.itemScope.element),containment.append(dragElement),$helper.movePosition(eventObj,dragElement,itemPosition,containment,containerPositioning,scrollableContainer),scope.sortableScope.$apply(function(){scope.callbacks.dragStart(dragItemInfo.eventArgs())}),bindEvents()))},isDraggable=function(event){var elementClicked,sourceScope,isDraggable;for(elementClicked=angular.element(event.target),sourceScope=fetchScope(elementClicked),isDraggable=sourceScope&&"handle"===sourceScope.type;isDraggable&&elementClicked[0]!==element[0];)$helper.noDrag(elementClicked)&&(isDraggable=!1),elementClicked=elementClicked.parent();return isDraggable},dragMove=function(event){var eventObj,targetX,targetY,targetScope,targetElement;if((!hasTouch||!$helper.isTouchInvalid(event))&&dragHandled&&dragElement){if(event.preventDefault(),eventObj=$helper.eventObj(event),scope.callbacks.dragMove!==angular.noop&&scope.sortableScope.$apply(function(){scope.callbacks.dragMove(itemPosition,containment,eventObj)}),$helper.movePosition(eventObj,dragElement,itemPosition,containment,containerPositioning,scrollableContainer),targetX=eventObj.pageX-$document[0].documentElement.scrollLeft,targetY=eventObj.pageY-($window.pageYOffset||$document[0].documentElement.scrollTop),dragElement.addClass(sortableConfig.hiddenClass),$document[0].elementFromPoint(targetX,targetY),targetElement=angular.element($document[0].elementFromPoint(targetX,targetY)),dragElement.removeClass(sortableConfig.hiddenClass),dragElement.addClass(sortableConfig.dragging),targetScope=fetchScope(targetElement),!targetScope||!targetScope.type)return;if("handle"===targetScope.type&&(targetScope=targetScope.itemScope),"item"!==targetScope.type&&"sortable"!==targetScope.type)return;if("item"===targetScope.type&&targetScope.accept(scope,targetScope.sortableScope,targetScope)){targetElement=targetScope.element;var placeholderIndex=placeHolderIndex(targetScope.sortableScope.element);0>placeholderIndex?insertBefore(targetElement,targetScope):placeholderIndex<=targetScope.index()?insertAfter(targetElement,targetScope):insertBefore(targetElement,targetScope)}"sortable"===targetScope.type&&targetScope.accept(scope,targetScope)&&!isParent(targetScope.element[0],targetElement[0])&&(isPlaceHolderPresent(targetElement)||targetScope.options.clone||(targetElement[0].appendChild(placeHolder[0]),dragItemInfo.moveTo(targetScope,targetScope.modelValue.length)))}},placeHolderIndex=function(targetElement){var itemElements,i;if(targetElement.hasClass(sortableConfig.placeHolderClass))return 0;for(itemElements=targetElement.children(),i=0;i<itemElements.length;i+=1)if(angular.element(itemElements[i]).hasClass(sortableConfig.placeHolderClass))return i;return-1},isPlaceHolderPresent=function(targetElement){return placeHolderIndex(targetElement)>=0},dragEnd=function(event){dragHandled&&(event.preventDefault(),dragElement&&(rollbackDragChanges(),dragItemInfo.apply(),scope.sortableScope.$apply(function(){dragItemInfo.isSameParent()?dragItemInfo.isOrderChanged()&&scope.callbacks.orderChanged(dragItemInfo.eventArgs()):scope.callbacks.itemMoved(dragItemInfo.eventArgs())}),scope.sortableScope.$apply(function(){scope.callbacks.dragEnd(dragItemInfo.eventArgs())}),dragItemInfo=null),unBindEvents())},dragCancel=function(event){dragHandled&&(event.preventDefault(),dragElement&&(rollbackDragChanges(),scope.sortableScope.$apply(function(){scope.callbacks.dragCancel(dragItemInfo.eventArgs())}),dragItemInfo=null),unBindEvents())},bindDrag=function(){element.bind("touchstart",dragListen),element.bind("mousedown",dragListen)},unbindDrag=function(){element.unbind("touchstart",dragListen),element.unbind("mousedown",dragListen)},bindDrag(),escapeListen=function(event){27===event.keyCode&&dragCancel(event)},angular.element($document[0].body).bind("keydown",escapeListen),bindEvents=function(){angular.element($document).bind("touchmove",dragMove),angular.element($document).bind("touchend",dragEnd),angular.element($document).bind("touchcancel",dragCancel),angular.element($document).bind("mousemove",dragMove),angular.element($document).bind("mouseup",dragEnd)},unBindEvents=function(){angular.element($document).unbind("touchend",dragEnd),angular.element($document).unbind("touchcancel",dragCancel),angular.element($document).unbind("touchmove",dragMove),angular.element($document).unbind("mouseup",dragEnd),angular.element($document).unbind("mousemove",dragMove)}}}}])}(),function(){"use strict";var mainModule=angular.module("as.sortable");mainModule.controller("as.sortable.sortableItemController",["$scope",function($scope){this.scope=$scope,$scope.sortableScope=null,$scope.modelValue=null,$scope.type="item",$scope.index=function(){return $scope.$index},$scope.itemData=function(){return $scope.sortableScope.modelValue[$scope.$index]}}]),mainModule.directive("asSortableItem",["sortableConfig",function(sortableConfig){return{require:["^asSortable","?ngModel"],restrict:"A",controller:"as.sortable.sortableItemController",link:function(scope,element,attrs,ctrl){var sortableController=ctrl[0],ngModelController=ctrl[1];sortableConfig.itemClass&&element.addClass(sortableConfig.itemClass),scope.sortableScope=sortableController.scope,ngModelController?ngModelController.$render=function(){scope.modelValue=ngModelController.$modelValue}:scope.modelValue=sortableController.scope.modelValue[scope.$index],scope.element=element,element.data("_scope",scope)}}}])}(); |
// Compiled by ClojureScript 1.9.14 {:target :nodejs}
goog.provide('instaparse.reduction');
goog.require('cljs.core');
goog.require('instaparse.auto_flatten_seq');
instaparse.reduction.singleton_QMARK_ = (function instaparse$reduction$singleton_QMARK_(s){
return (cljs.core.seq.call(null,s)) && (cljs.core.not.call(null,cljs.core.next.call(null,s)));
});
instaparse.reduction.red = (function instaparse$reduction$red(parser,f){
return cljs.core.assoc.call(null,parser,new cljs.core.Keyword(null,"red","red",-969428204),f);
});
instaparse.reduction.raw_non_terminal_reduction = new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"reduction-type","reduction-type",-488293450),new cljs.core.Keyword(null,"raw","raw",1604651272)], null);
instaparse.reduction.HiccupNonTerminalReduction = (function instaparse$reduction$HiccupNonTerminalReduction(key){
return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"reduction-type","reduction-type",-488293450),new cljs.core.Keyword(null,"hiccup","hiccup",1218876238),new cljs.core.Keyword(null,"key","key",-1516042587),key], null);
});
instaparse.reduction.EnliveNonTerminalReduction = (function instaparse$reduction$EnliveNonTerminalReduction(key){
return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"reduction-type","reduction-type",-488293450),new cljs.core.Keyword(null,"enlive","enlive",1679023921),new cljs.core.Keyword(null,"key","key",-1516042587),key], null);
});
instaparse.reduction.reduction_types = new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"hiccup","hiccup",1218876238),instaparse.reduction.HiccupNonTerminalReduction,new cljs.core.Keyword(null,"enlive","enlive",1679023921),instaparse.reduction.EnliveNonTerminalReduction], null);
instaparse.reduction.node_builders = new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"enlive","enlive",1679023921),(function (tag,item){
return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"tag","tag",-1290361223),tag,new cljs.core.Keyword(null,"content","content",15833224),(function (){var x__7050__auto__ = item;
return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__7050__auto__);
})()], null);
}),new cljs.core.Keyword(null,"hiccup","hiccup",1218876238),(function (tag,item){
return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [tag,item], null);
})], null);
instaparse.reduction.standard_non_terminal_reduction = new cljs.core.Keyword(null,"hiccup","hiccup",1218876238);
instaparse.reduction.apply_reduction = (function instaparse$reduction$apply_reduction(f,result){
var G__15811 = (((new cljs.core.Keyword(null,"reduction-type","reduction-type",-488293450).cljs$core$IFn$_invoke$arity$1(f) instanceof cljs.core.Keyword))?new cljs.core.Keyword(null,"reduction-type","reduction-type",-488293450).cljs$core$IFn$_invoke$arity$1(f).fqn:null);
switch (G__15811) {
case "raw":
return instaparse.auto_flatten_seq.conj_flat.call(null,instaparse.auto_flatten_seq.EMPTY,result);
break;
case "hiccup":
return instaparse.auto_flatten_seq.convert_afs_to_vec.call(null,instaparse.auto_flatten_seq.conj_flat.call(null,instaparse.auto_flatten_seq.auto_flatten_seq.call(null,new cljs.core.PersistentVector(null, 1, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Keyword(null,"key","key",-1516042587).cljs$core$IFn$_invoke$arity$1(f)], null)),result));
break;
case "enlive":
var content = instaparse.auto_flatten_seq.conj_flat.call(null,instaparse.auto_flatten_seq.EMPTY,result);
return new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword(null,"tag","tag",-1290361223),new cljs.core.Keyword(null,"key","key",-1516042587).cljs$core$IFn$_invoke$arity$1(f),new cljs.core.Keyword(null,"content","content",15833224),(((cljs.core.count.call(null,content) === (0)))?null:content)], null);
break;
default:
return f.call(null,result);
}
});
instaparse.reduction.apply_standard_reductions = (function instaparse$reduction$apply_standard_reductions(var_args){
var args15813 = [];
var len__7291__auto___15824 = arguments.length;
var i__7292__auto___15825 = (0);
while(true){
if((i__7292__auto___15825 < len__7291__auto___15824)){
args15813.push((arguments[i__7292__auto___15825]));
var G__15826 = (i__7292__auto___15825 + (1));
i__7292__auto___15825 = G__15826;
continue;
} else {
}
break;
}
var G__15815 = args15813.length;
switch (G__15815) {
case 1:
return instaparse.reduction.apply_standard_reductions.cljs$core$IFn$_invoke$arity$1((arguments[(0)]));
break;
case 2:
return instaparse.reduction.apply_standard_reductions.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)]));
break;
default:
throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args15813.length)].join('')));
}
});
instaparse.reduction.apply_standard_reductions.cljs$core$IFn$_invoke$arity$1 = (function (grammar){
return instaparse.reduction.apply_standard_reductions.call(null,instaparse.reduction.standard_non_terminal_reduction,grammar);
});
instaparse.reduction.apply_standard_reductions.cljs$core$IFn$_invoke$arity$2 = (function (reduction_type,grammar){
var temp__4655__auto__ = instaparse.reduction.reduction_types.call(null,reduction_type);
if(cljs.core.truth_(temp__4655__auto__)){
var reduction = temp__4655__auto__;
return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,(function (){var iter__6996__auto__ = ((function (reduction,temp__4655__auto__){
return (function instaparse$reduction$iter__15816(s__15817){
return (new cljs.core.LazySeq(null,((function (reduction,temp__4655__auto__){
return (function (){
var s__15817__$1 = s__15817;
while(true){
var temp__4657__auto__ = cljs.core.seq.call(null,s__15817__$1);
if(temp__4657__auto__){
var s__15817__$2 = temp__4657__auto__;
if(cljs.core.chunked_seq_QMARK_.call(null,s__15817__$2)){
var c__6994__auto__ = cljs.core.chunk_first.call(null,s__15817__$2);
var size__6995__auto__ = cljs.core.count.call(null,c__6994__auto__);
var b__15819 = cljs.core.chunk_buffer.call(null,size__6995__auto__);
if((function (){var i__15818 = (0);
while(true){
if((i__15818 < size__6995__auto__)){
var vec__15822 = cljs.core._nth.call(null,c__6994__auto__,i__15818);
var k = cljs.core.nth.call(null,vec__15822,(0),null);
var v = cljs.core.nth.call(null,vec__15822,(1),null);
cljs.core.chunk_append.call(null,b__15819,(cljs.core.truth_(new cljs.core.Keyword(null,"red","red",-969428204).cljs$core$IFn$_invoke$arity$1(v))?new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [k,v], null):new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [k,cljs.core.assoc.call(null,v,new cljs.core.Keyword(null,"red","red",-969428204),reduction.call(null,k))], null)));
var G__15828 = (i__15818 + (1));
i__15818 = G__15828;
continue;
} else {
return true;
}
break;
}
})()){
return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__15819),instaparse$reduction$iter__15816.call(null,cljs.core.chunk_rest.call(null,s__15817__$2)));
} else {
return cljs.core.chunk_cons.call(null,cljs.core.chunk.call(null,b__15819),null);
}
} else {
var vec__15823 = cljs.core.first.call(null,s__15817__$2);
var k = cljs.core.nth.call(null,vec__15823,(0),null);
var v = cljs.core.nth.call(null,vec__15823,(1),null);
return cljs.core.cons.call(null,(cljs.core.truth_(new cljs.core.Keyword(null,"red","red",-969428204).cljs$core$IFn$_invoke$arity$1(v))?new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [k,v], null):new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [k,cljs.core.assoc.call(null,v,new cljs.core.Keyword(null,"red","red",-969428204),reduction.call(null,k))], null)),instaparse$reduction$iter__15816.call(null,cljs.core.rest.call(null,s__15817__$2)));
}
} else {
return null;
}
break;
}
});})(reduction,temp__4655__auto__))
,null,null));
});})(reduction,temp__4655__auto__))
;
return iter__6996__auto__.call(null,grammar);
})());
} else {
throw [cljs.core.str("Invalid output format"),cljs.core.str(reduction_type),cljs.core.str(". Use :enlive or :hiccup.")].join('');
}
});
instaparse.reduction.apply_standard_reductions.cljs$lang$maxFixedArity = 2;
//# sourceMappingURL=reduction.js.map?rel=1475748717713 |
import React from 'react'
import PropTypes from 'prop-types'
import { isFeatureEnabled } from 'lib/featureUtils'
import { PROFILE_PAGE_TABS } from 'locations'
import {
Menu,
Container,
Card,
Pagination,
Loader,
Label
} from 'semantic-ui-react'
import AddressBlock from 'components/AddressBlock'
import ParcelCard from 'components/ParcelCard'
import Contribution from './Contribution'
import { parcelType, contributionType, estateType } from 'components/types'
import { t } from 'modules/translation/utils'
import { buildUrl } from './utils'
import { shortenAddress } from 'lib/utils'
import './ProfilePage.css'
import EstateCard from 'components/EstateCard'
export default class ProfilePage extends React.PureComponent {
static propTypes = {
address: PropTypes.string,
parcels: PropTypes.arrayOf(parcelType),
estates: PropTypes.arrayOf(estateType),
contributions: PropTypes.arrayOf(contributionType),
publishedParcels: PropTypes.arrayOf(parcelType),
mortgagedParcels: PropTypes.arrayOf(parcelType),
grid: PropTypes.arrayOf(
PropTypes.oneOfType([parcelType, contributionType])
),
tab: PropTypes.string,
page: PropTypes.number.isRequired,
pages: PropTypes.number.isRequired,
isLoading: PropTypes.bool,
isEmpty: PropTypes.bool,
isOwner: PropTypes.bool,
isConnecting: PropTypes.bool,
onNavigate: PropTypes.func.isRequired
}
componentWillMount() {
this.props.onFetchAddress()
}
handlePageChange = (event, data) => {
const { address, tab, onNavigate } = this.props
const url = buildUrl({
page: data.activePage,
address,
tab
})
onNavigate(url)
}
renderLoading() {
return <Loader active size="huge" />
}
renderEmpty() {
const { tab } = this.props
return (
<div className="empty">
<p>
{t('profile_page.empty', {
content: t(`global.${tab}`).toLowerCase()
})}
</p>
</div>
)
}
renderGrid() {
const { grid, tab } = this.props
switch (tab) {
case PROFILE_PAGE_TABS.parcels: {
return (
<Card.Group stackable={true}>
{grid.map(parcel => <ParcelCard key={parcel.id} parcel={parcel} />)}
</Card.Group>
)
}
case PROFILE_PAGE_TABS.contributions: {
return (
<Card.Group stackable={true}>
{grid.map(contribution => (
<Contribution
key={contribution.district_id}
contribution={contribution}
/>
))}
</Card.Group>
)
}
case PROFILE_PAGE_TABS.publications: {
return (
<Card.Group stackable={true}>
{grid.map(parcel => (
<ParcelCard
key={parcel.id}
parcel={parcel}
isOwnerVisible={false}
/>
))}
</Card.Group>
)
}
case PROFILE_PAGE_TABS.estates: {
return (
<Card.Group stackable={true}>
{grid.map(estate => <EstateCard key={estate.id} estate={estate} />)}
</Card.Group>
)
}
case PROFILE_PAGE_TABS.mortgages: {
return (
<Card.Group stackable={true}>
{grid.map(parcel => (
<ParcelCard
key={parcel.id}
parcel={parcel}
isOwnerVisible={false}
showMortgage={true}
/>
))}
</Card.Group>
)
}
default:
return null
}
}
isActive(tab) {
return tab === this.props.tab
}
renderBadge(array, tab) {
if (array.length === 0) {
return null
}
return (
<Label className={this.isActive(tab) ? 'active' : ''} size="tiny">
{array.length}
</Label>
)
}
handleItemClick = (event, { name }) => {
const { address, onNavigate } = this.props
const url = buildUrl({
page: 1,
address,
tab: name
})
onNavigate(url)
}
render() {
const {
address,
page,
pages,
isLoading,
isEmpty,
parcels,
contributions,
publishedParcels,
estates,
mortgagedParcels,
isOwner,
isConnecting
} = this.props
return (
<div className="ProfilePage">
{isOwner || isConnecting ? null : (
<Container className="profile-header">
<div>
<AddressBlock scale={16} address={address} hasTooltip={false} />
<span className="profile-address">{shortenAddress(address)}</span>
</div>
</Container>
)}
<Container className="profile-menu">
<Menu pointing secondary stackable>
<Menu.Item
name={PROFILE_PAGE_TABS.parcels}
active={this.isActive(PROFILE_PAGE_TABS.parcels)}
onClick={this.handleItemClick}
>
{t('global.parcels')}
{this.renderBadge(parcels, PROFILE_PAGE_TABS.parcels)}
</Menu.Item>
<Menu.Item
name={PROFILE_PAGE_TABS.contributions}
active={this.isActive(PROFILE_PAGE_TABS.contributions)}
onClick={this.handleItemClick}
>
{t('global.contributions')}
{this.renderBadge(contributions, PROFILE_PAGE_TABS.contributions)}
</Menu.Item>
<Menu.Item
name={PROFILE_PAGE_TABS.publications}
active={this.isActive(PROFILE_PAGE_TABS.publications)}
onClick={this.handleItemClick}
>
{t('profile_page.on_sale')}
{this.renderBadge(
publishedParcels,
PROFILE_PAGE_TABS.publications
)}
</Menu.Item>
{isFeatureEnabled('ESTATES') && (
<Menu.Item
name={PROFILE_PAGE_TABS.estates}
active={this.isActive(PROFILE_PAGE_TABS.estates)}
onClick={this.handleItemClick}
>
{t('global.estates')}
{this.renderBadge(estates, PROFILE_PAGE_TABS.estates)}
</Menu.Item>
) /* Estate Feature */}
{isFeatureEnabled('MORTGAGES') &&
isOwner && (
<Menu.Item
name={PROFILE_PAGE_TABS.mortgages}
active={this.isActive(PROFILE_PAGE_TABS.mortgages)}
onClick={this.handleItemClick}
>
{t('global.mortgages')}
{this.renderBadge(
mortgagedParcels,
PROFILE_PAGE_TABS.mortgages
)}
</Menu.Item>
) /* Mortgage Feature */}
</Menu>
</Container>
<Container className="profile-grid">
{isEmpty && !isLoading ? this.renderEmpty() : null}
{isLoading ? this.renderLoading() : this.renderGrid()}
</Container>
<Container textAlign="center" className="pagination">
{isEmpty || pages <= 1 ? null : (
<Pagination
activePage={page}
firstItem={null}
lastItem={null}
prevItem={null}
nextItem={null}
pointing
secondary
totalPages={pages}
onPageChange={this.handlePageChange}
boundaryRange={1}
siblingRange={1}
/>
)}
</Container>
</div>
)
}
}
|
# Copyright (c) 2005 Alexey Pakhunov.
# Copyright (c) 2011 Juraj Ivancic
#
# Use, modification and distribution is subject to the Boost Software
# License Version 1.0. (See accompanying file LICENSE_1_0.txt or
# http://www.boost.org/LICENSE_1_0.txt)
# Microsoft Interface Definition Language (MIDL) related routines
from b2.build import scanner, type
from b2.build.toolset import flags
from b2.build.feature import feature
from b2.manager import get_manager
from b2.tools import builtin, common
from b2.util import regex, utility
def init():
pass
type.register('IDL', ['idl'])
# A type library (.tlb) is generated by MIDL compiler and can be included
# to resources of an application (.rc). In order to be found by a resource
# compiler its target type should be derived from 'H' - otherwise
# the property '<implicit-dependency>' will be ignored.
type.register('MSTYPELIB', ['tlb'], 'H')
# Register scanner for MIDL files
class MidlScanner(scanner.Scanner):
def __init__ (self, includes=[]):
scanner.Scanner.__init__(self)
self.includes = includes
# List of quoted strings
re_strings = "[ \t]*\"([^\"]*)\"([ \t]*,[ \t]*\"([^\"]*)\")*[ \t]*" ;
# 'import' and 'importlib' directives
self.re_import = "import" + re_strings + "[ \t]*;" ;
self.re_importlib = "importlib[ \t]*[(]" + re_strings + "[)][ \t]*;" ;
# C preprocessor 'include' directive
self.re_include_angle = "#[ \t]*include[ \t]*<(.*)>" ;
self.re_include_quoted = "#[ \t]*include[ \t]*\"(.*)\"" ;
def pattern():
# Match '#include', 'import' and 'importlib' directives
return "((#[ \t]*include|import(lib)?).+(<(.*)>|\"(.*)\").+)"
def process(self, target, matches, binding):
included_angle = regex.transform(matches, self.re_include_angle)
included_quoted = regex.transform(matches, self.re_include_quoted)
imported = regex.transform(matches, self.re_import, [1, 3])
imported_tlbs = regex.transform(matches, self.re_importlib, [1, 3])
# CONSIDER: the new scoping rule seem to defeat "on target" variables.
g = bjam.call('get-target-variable', target, 'HDRGRIST')[0]
b = os.path.normpath(os.path.dirname(binding))
# Attach binding of including file to included targets.
# When target is directly created from virtual target
# this extra information is unnecessary. But in other
# cases, it allows to distinguish between two headers of the
# same name included from different places.
g2 = g + "#" + b
g = "<" + g + ">"
g2 = "<" + g2 + ">"
included_angle = [ g + x for x in included_angle ]
included_quoted = [ g + x for x in included_quoted ]
imported = [ g + x for x in imported ]
imported_tlbs = [ g + x for x in imported_tlbs ]
all = included_angle + included_quoted + imported
bjam.call('INCLUDES', [target], all)
bjam.call('DEPENDS', [target], imported_tlbs)
bjam.call('NOCARE', all + imported_tlbs)
engine.set_target_variable(included_angle , 'SEARCH', [utility.get_value(inc) for inc in self.includes])
engine.set_target_variable(included_quoted, 'SEARCH', [utility.get_value(inc) for inc in self.includes])
engine.set_target_variable(imported , 'SEARCH', [utility.get_value(inc) for inc in self.includes])
engine.set_target_variable(imported_tlbs , 'SEARCH', [utility.get_value(inc) for inc in self.includes])
get_manager().scanners().propagate(type.get_scanner('CPP', PropertySet(self.includes)), included_angle + included_quoted)
get_manager().scanners().propagate(self, imported)
scanner.register(MidlScanner, 'include')
type.set_scanner('IDL', MidlScanner)
# Command line options
feature('midl-stubless-proxy', ['yes', 'no'], ['propagated'] )
feature('midl-robust', ['yes', 'no'], ['propagated'] )
flags('midl.compile.idl', 'MIDLFLAGS', ['<midl-stubless-proxy>yes'], ['/Oicf' ])
flags('midl.compile.idl', 'MIDLFLAGS', ['<midl-stubless-proxy>no' ], ['/Oic' ])
flags('midl.compile.idl', 'MIDLFLAGS', ['<midl-robust>yes' ], ['/robust' ])
flags('midl.compile.idl', 'MIDLFLAGS', ['<midl-robust>no' ], ['/no_robust'])
# Architecture-specific options
architecture_x86 = ['<architecture>' , '<architecture>x86']
address_model_32 = ['<address-model>', '<address-model>32']
address_model_64 = ['<address-model>', '<address-model>64']
flags('midl.compile.idl', 'MIDLFLAGS', [ar + '/' + m for ar in architecture_x86 for m in address_model_32 ], ['/win32'])
flags('midl.compile.idl', 'MIDLFLAGS', [ar + '/<address-model>64' for ar in architecture_x86], ['/x64'])
flags('midl.compile.idl', 'MIDLFLAGS', ['<architecture>ia64/' + m for m in address_model_64], ['/ia64'])
flags('midl.compile.idl', 'DEFINES', [], ['<define>'])
flags('midl.compile.idl', 'UNDEFS', [], ['<undef>'])
flags('midl.compile.idl', 'INCLUDES', [], ['<include>'])
builtin.register_c_compiler('midl.compile.idl', ['IDL'], ['MSTYPELIB', 'H', 'C(%_i)', 'C(%_proxy)', 'C(%_dlldata)'], [])
# MIDL does not always generate '%_proxy.c' and '%_dlldata.c'. This behavior
# depends on contents of the source IDL file. Calling TOUCH_FILE below ensures
# that both files will be created so bjam will not try to recreate them
# constantly.
get_manager().engine().register_action(
'midl.compile.idl',
'''midl /nologo @"@($(<[1]:W).rsp:E=
"$(>:W)"
-D$(DEFINES)
"-I$(INCLUDES)"
-U$(UNDEFS)
$(MIDLFLAGS)
/tlb "$(<[1]:W)"
/h "$(<[2]:W)"
/iid "$(<[3]:W)"
/proxy "$(<[4]:W)"
/dlldata "$(<[5]:W)")"
{touch} "$(<[4]:W)"
{touch} "$(<[5]:W)"'''.format(touch=common.file_creation_command()))
|
// Libs
import React from 'react';
import { render } from 'enzyme';
import { expect } from 'chai';
// Component
import UserImage from './UserImage';
describe('<UserImage />', () => {
it('should have a <div /> element with .gh-widget-photo class', () => {
const wrapper = render(<UserImage />);
expect(wrapper.attr('class')).to.equal('gh-widget-photo');
});
});
|
"""
:Created: 5 May 2015
:Author: Lucas Connors
"""
from django.db import models
class Table(models.Model):
number = models.CharField(max_length=60)
def __str__(self):
return self.number
|
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import matplotlib.pyplot as plt
import numpy as np
import odrive
import tensorflow as tf
import time
cpr = 8192
v_lim = 400000
#v_target = 50000
v_target = 0
#v_roll_ave = 5
v_roll_ave = 1
c_lim = 10
#c_launch = 1.3
c_launch = .4
t_run = 5
vel_max = 600000
cur_max = 10.000001
T_max = 1000
# torques normalized between 0 and 1 with a zero value at 0.5
#T_target = 0.5039
#T_target = 0.5045
T_target = 0.505
#model = tf.keras.models.load_model("data/tmp/model_tmp.h5")
model = tf.keras.models.load_model("data/model1.h5")
print("Connecting...")
d = odrive.find_any()
print("Connected")
x = d.axis0
t_buf = []
v_buf = []
p_buf = []
v_his = [v_target] * v_roll_ave
v_x_lim = 3
v_x_buf = []
p_last = x.encoder.pos_cpr
t_start = time.time()
t_last = t_start
print("Start loop...")
#x.controller.config.control_mode = 2
#x.controller.vel_setpoint = v_target
x.controller.config.control_mode = 1
x.controller.current_setpoint = c_launch
time.sleep(0.1)
#x.controller.config.control_mode = 1
while t_last - t_start < t_run:
p = x.encoder.pos_cpr
t = time.time()
t_diff = t - t_last
p_diff = p - p_last
if abs(p_diff) > cpr/2:
if p_diff < 0:
p_diff += cpr
else:
p_diff -= cpr
v = (p_diff) / t_diff
print("p: %d\tp_diff: %d\tv: %d" % (int(p), int(p_diff), int(v)))
if v > v_lim or v < v_lim * -1:
v_x_buf.append(v)
if len(v_x_buf) > v_x_lim:
x.controller.current_setpoint = 0
print(" Overspeed - abort. %.f" % (sum(v_x_buf)/len(v_x_buf)))
break
else:
v_x_buf = []
p_last = p
t_last = t
t_buf.append(t)
v_his.pop(0)
v_his.append(v)
v_buf.append(sum(v_his)/len(v_his))
p_buf.append(p + 50000)
#v = v_target
p_ = p/cpr
v_ = (1 + v/vel_max)/2
t_ = T_target
buf = []
buf.append(p_)
buf.append(v_)
buf.append(t_)
sample = np.array([buf])
pred = model.predict(sample)
c_set = pred[0][0]
#c_set = (c_set - 0.5) * 2 * cur_max * -1
c_set = (c_set - 0.5) * 2 * cur_max
if c_set > c_lim or c_set < c_lim * -1:
print(" Overcurrent prediction: %f" % (c_set))
c_set = c_lim
x.controller.current_setpoint = c_set
x.controller.current_setpoint = 0
#plt.plot(t_buf, p_buf)
plt.plot(t_buf, v_buf)
plt.show() |
/*
* Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
!function(e,define){define([],e)}(function(){return kendo.ui.FlatColorPicker&&(kendo.ui.FlatColorPicker.prototype.options.messages=$.extend(!0,kendo.ui.FlatColorPicker.prototype.options.messages,{apply:"Apply",cancel:"Cancel"})),kendo.ui.ColorPicker&&(kendo.ui.ColorPicker.prototype.options.messages=$.extend(!0,kendo.ui.ColorPicker.prototype.options.messages,{apply:"Apply",cancel:"Cancel"})),kendo.ui.ColumnMenu&&(kendo.ui.ColumnMenu.prototype.options.messages=$.extend(!0,kendo.ui.ColumnMenu.prototype.options.messages,{sortAscending:"Sort Ascending",sortDescending:"Sort Descending",filter:"Filter",columns:"Columns",done:"Done",settings:"Column Settings",lock:"Lock",unlock:"Unlock"})),kendo.ui.Editor&&(kendo.ui.Editor.prototype.options.messages=$.extend(!0,kendo.ui.Editor.prototype.options.messages,{bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",superscript:"Superscript",subscript:"Subscript",justifyCenter:"Center text",justifyLeft:"Align text left",justifyRight:"Align text right",justifyFull:"Justify",insertUnorderedList:"Insert unordered list",insertOrderedList:"Insert ordered list",indent:"Indent",outdent:"Outdent",createLink:"Insert hyperlink",unlink:"Remove hyperlink",insertImage:"Insert image",insertFile:"Insert file",insertHtml:"Insert HTML",viewHtml:"View HTML",fontName:"Select font family",fontNameInherit:"(inherited font)",fontSize:"Select font size",fontSizeInherit:"(inherited size)",formatBlock:"Format",formatting:"Format",foreColor:"Color",backColor:"Background color",style:"Styles",emptyFolder:"Empty Folder",uploadFile:"Upload",orderBy:"Arrange by:",orderBySize:"Size",orderByName:"Name",invalidFileType:'The selected file "{0}" is not valid. Supported file types are {1}.',deleteFile:'Are you sure you want to delete "{0}"?',overwriteFile:'A file with name "{0}" already exists in the current directory. Do you want to overwrite it?',directoryNotFound:"A directory with this name was not found.",imageWebAddress:"Web address",imageAltText:"Alternate text",imageWidth:"Width (px)",imageHeight:"Height (px)",fileWebAddress:"Web address",fileTitle:"Title",linkWebAddress:"Web address",linkText:"Text",linkToolTip:"ToolTip",linkOpenInNewWindow:"Open link in new window",dialogUpdate:"Update",dialogInsert:"Insert",dialogButtonSeparator:"or",dialogCancel:"Cancel",createTable:"Create table",addColumnLeft:"Add column on the left",addColumnRight:"Add column on the right",addRowAbove:"Add row above",addRowBelow:"Add row below",deleteRow:"Delete row",deleteColumn:"Delete column"})),kendo.ui.FileBrowser&&(kendo.ui.FileBrowser.prototype.options.messages=$.extend(!0,kendo.ui.FileBrowser.prototype.options.messages,{uploadFile:"Upload",orderBy:"Arrange by",orderByName:"Name",orderBySize:"Size",directoryNotFound:"A directory with this name was not found.",emptyFolder:"Empty Folder",deleteFile:'Are you sure you want to delete "{0}"?',invalidFileType:'The selected file "{0}" is not valid. Supported file types are {1}.',overwriteFile:'A file with name "{0}" already exists in the current directory. Do you want to overwrite it?',dropFilesHere:"drop file here to upload",search:"Search"})),kendo.ui.FilterCell&&(kendo.ui.FilterCell.prototype.options.messages=$.extend(!0,kendo.ui.FilterCell.prototype.options.messages,{isTrue:"is true",isFalse:"is false",filter:"Filter",clear:"Clear",operator:"Operator"})),kendo.ui.FilterMenu&&(kendo.ui.FilterMenu.prototype.options.messages=$.extend(!0,kendo.ui.FilterMenu.prototype.options.messages,{info:"Show items with value that:",isTrue:"is true",isFalse:"is false",filter:"Filter",clear:"Clear",and:"And",or:"Or",selectValue:"-Select value-",operator:"Operator",value:"Value",cancel:"Cancel"})),kendo.ui.FilterMenu&&(kendo.ui.FilterMenu.prototype.options.operators=$.extend(!0,kendo.ui.FilterMenu.prototype.options.operators,{string:{eq:"Is equal to",neq:"Is not equal to",startswith:"Starts with",contains:"Contains",doesnotcontain:"Does not contain",endswith:"Ends with"},number:{eq:"Is equal to",neq:"Is not equal to",gte:"Is greater than or equal to",gt:"Is greater than",lte:"Is less than or equal to",lt:"Is less than"},date:{eq:"Is equal to",neq:"Is not equal to",gte:"Is after or equal to",gt:"Is after",lte:"Is before or equal to",lt:"Is before"},enums:{eq:"Is equal to",neq:"Is not equal to"}})),kendo.ui.Gantt&&(kendo.ui.Gantt.prototype.options.messages=$.extend(!0,kendo.ui.Gantt.prototype.options.messages,{views:{day:"Day",week:"Week",month:"Month"},actions:{append:"Add Task",addChild:"Add Child",insertBefore:"Add Above",insertAfter:"Add Below"}})),kendo.ui.Grid&&(kendo.ui.Grid.prototype.options.messages=$.extend(!0,kendo.ui.Grid.prototype.options.messages,{commands:{cancel:"Cancel changes",canceledit:"Cancel",create:"Add new record",destroy:"Delete",edit:"Edit",save:"Save changes",select:"Select",update:"Update"},editable:{cancelDelete:"Cancel",confirmation:"Are you sure you want to delete this record?",confirmDelete:"Delete"}})),kendo.ui.Groupable&&(kendo.ui.Groupable.prototype.options.messages=$.extend(!0,kendo.ui.Groupable.prototype.options.messages,{empty:"Drag a column header and drop it here to group by that column"})),kendo.ui.NumericTextBox&&(kendo.ui.NumericTextBox.prototype.options=$.extend(!0,kendo.ui.NumericTextBox.prototype.options,{upArrowText:"Increase value",downArrowText:"Decreate value"})),kendo.ui.Pager&&(kendo.ui.Pager.prototype.options.messages=$.extend(!0,kendo.ui.Pager.prototype.options.messages,{display:"{0} - {1} of {2} items",empty:"No items to display",page:"Page",of:"of {0}",itemsPerPage:"items per page",first:"Go to the first page",previous:"Go to the previous page",next:"Go to the next page",last:"Go to the last page",refresh:"Refresh",morePages:"More pages"})),kendo.ui.PivotGrid&&(kendo.ui.PivotGrid.prototype.options.messages=$.extend(!0,kendo.ui.PivotGrid.prototype.options.messages,{measureFields:"Drop Data Fields Here",columnFields:"Drop Column Fields Here",rowFields:"Drop Rows Fields Here"})),kendo.ui.PivotFieldMenu&&(kendo.ui.PivotFieldMenu.prototype.options.messages=$.extend(!0,kendo.ui.PivotFieldMenu.prototype.options.messages,{info:"Show items with value that:",filterFields:"Fields Filter",filter:"Filter",include:"Include Fields...",title:"Fields to include",clear:"Clear",ok:"Ok",cancel:"Cancel",operators:{contains:"Contains",doesnotcontain:"Does not contain",startswith:"Starts with",endswith:"Ends with",eq:"Is equal to",neq:"Is not equal to"}})),kendo.ui.RecurrenceEditor&&(kendo.ui.RecurrenceEditor.prototype.options.messages=$.extend(!0,kendo.ui.RecurrenceEditor.prototype.options.messages,{frequencies:{never:"Never",hourly:"Hourly",daily:"Daily",weekly:"Weekly",monthly:"Monthly",yearly:"Yearly"},hourly:{repeatEvery:"Repeat every: ",interval:" hour(s)"},daily:{repeatEvery:"Repeat every: ",interval:" day(s)"},weekly:{interval:" week(s)",repeatEvery:"Repeat every: ",repeatOn:"Repeat on: "},monthly:{repeatEvery:"Repeat every: ",repeatOn:"Repeat on: ",interval:" month(s)",day:"Day "},yearly:{repeatEvery:"Repeat every: ",repeatOn:"Repeat on: ",interval:" year(s)",of:" of "},end:{label:"End:",mobileLabel:"Ends",never:"Never",after:"After ",occurrence:" occurrence(s)",on:"On "},offsetPositions:{first:"first",second:"second",third:"third",fourth:"fourth",last:"last"},weekdays:{day:"day",weekday:"weekday",weekend:"weekend day"}})),kendo.ui.Scheduler&&(kendo.ui.Scheduler.prototype.options.messages=$.extend(!0,kendo.ui.Scheduler.prototype.options.messages,{allDay:"all day",date:"Date",event:"Event",time:"Time",showFullDay:"Show full day",showWorkDay:"Show business hours",today:"Today",save:"Save",cancel:"Cancel",destroy:"Delete",deleteWindowTitle:"Delete event",ariaSlotLabel:"Selected from {0:t} to {1:t}",ariaEventLabel:"{0} on {1:D} at {2:t}",confirmation:"Are you sure you want to delete this event?",views:{day:"Day",week:"Week",workWeek:"Work Week",agenda:"Agenda",month:"Month"},recurrenceMessages:{deleteWindowTitle:"Delete Recurring Item",deleteWindowOccurrence:"Delete current occurrence",deleteWindowSeries:"Delete the series",editWindowTitle:"Edit Recurring Item",editWindowOccurrence:"Edit current occurrence",editWindowSeries:"Edit the series",deleteRecurring:"Do you want to delete only this event occurrence or the whole series?",editRecurring:"Do you want to edit only this event occurrence or the whole series?"},editor:{title:"Title",start:"Start",end:"End",allDayEvent:"All day event",description:"Description",repeat:"Repeat",timezone:" ",startTimezone:"Start timezone",endTimezone:"End timezone",separateTimezones:"Use separate start and end time zones",timezoneEditorTitle:"Timezones",timezoneEditorButton:"Time zone",timezoneTitle:"Time zones",noTimezone:"No timezone",editorTitle:"Event"}})),kendo.ui.Slider&&(kendo.ui.Slider.prototype.options=$.extend(!0,kendo.ui.Slider.prototype.options,{increaseButtonTitle:"Increase",decreaseButtonTitle:"Decrease"})),kendo.ui.TreeView&&(kendo.ui.TreeView.prototype.options.messages=$.extend(!0,kendo.ui.TreeView.prototype.options.messages,{loading:"Loading...",requestFailed:"Request failed.",retry:"Retry"})),kendo.ui.Upload&&(kendo.ui.Upload.prototype.options.localization=$.extend(!0,kendo.ui.Upload.prototype.options.localization,{select:"Select files...",cancel:"Cancel",retry:"Retry",remove:"Remove",uploadSelectedFiles:"Upload files",dropFilesHere:"drop files here to upload",statusUploading:"uploading",statusUploaded:"uploaded",statusWarning:"warning",statusFailed:"failed",headerStatusUploading:"Uploading...",headerStatusUploaded:"Done"})),kendo.ui.Validator&&(kendo.ui.Validator.prototype.options.messages=$.extend(!0,kendo.ui.Validator.prototype.options.messages,{required:"{0} is required",pattern:"{0} is not valid",min:"{0} should be greater than or equal to {1}",max:"{0} should be smaller than or equal to {1}",step:"{0} is not valid",email:"{0} is not valid email",url:"{0} is not valid URL",date:"{0} is not valid date"})),window.kendo},"function"==typeof define&&define.amd?define:function(e,t){t()}); |
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
import expect from 'expect.js';
import { UiNavLink } from '../ui_nav_link';
describe('UiNavLink', () => {
describe('constructor', () => {
it('initializes the object properties as expected', () => {
const spec = {
id: 'kibana:discover',
title: 'Discover',
order: -1003,
url: '/app/kibana#/discover',
icon: 'plugins/kibana/assets/discover.svg',
euiIconType: 'discoverApp',
hidden: true,
disabled: true
};
const link = new UiNavLink(spec);
expect(link.toJSON()).to.eql({
id: spec.id,
title: spec.title,
order: spec.order,
url: spec.url,
subUrlBase: spec.url,
icon: spec.icon,
euiIconType: spec.euiIconType,
hidden: spec.hidden,
disabled: spec.disabled,
// defaults
linkToLastSubUrl: true,
tooltip: ''
});
});
it('initializes the order property to 0 when order is not specified in the spec', () => {
const spec = {
id: 'kibana:discover',
title: 'Discover',
url: '/app/kibana#/discover',
icon: 'plugins/kibana/assets/discover.svg',
};
const link = new UiNavLink(spec);
expect(link.toJSON()).to.have.property('order', 0);
});
it('initializes the linkToLastSubUrl property to false when false is specified in the spec', () => {
const spec = {
id: 'kibana:discover',
title: 'Discover',
order: -1003,
url: '/app/kibana#/discover',
icon: 'plugins/kibana/assets/discover.svg',
linkToLastSubUrl: false
};
const link = new UiNavLink(spec);
expect(link.toJSON()).to.have.property('linkToLastSubUrl', false);
});
it('initializes the linkToLastSubUrl property to true by default', () => {
const spec = {
id: 'kibana:discover',
title: 'Discover',
order: -1003,
url: '/app/kibana#/discover',
icon: 'plugins/kibana/assets/discover.svg',
};
const link = new UiNavLink(spec);
expect(link.toJSON()).to.have.property('linkToLastSubUrl', true);
});
it('initializes the hidden property to false by default', () => {
const spec = {
id: 'kibana:discover',
title: 'Discover',
order: -1003,
url: '/app/kibana#/discover',
icon: 'plugins/kibana/assets/discover.svg',
};
const link = new UiNavLink(spec);
expect(link.toJSON()).to.have.property('hidden', false);
});
it('initializes the disabled property to false by default', () => {
const spec = {
id: 'kibana:discover',
title: 'Discover',
order: -1003,
url: '/app/kibana#/discover',
icon: 'plugins/kibana/assets/discover.svg',
};
const link = new UiNavLink(spec);
expect(link.toJSON()).to.have.property('disabled', false);
});
it('initializes the tooltip property to an empty string by default', () => {
const spec = {
id: 'kibana:discover',
title: 'Discover',
order: -1003,
url: '/app/kibana#/discover',
icon: 'plugins/kibana/assets/discover.svg',
};
const link = new UiNavLink(spec);
expect(link.toJSON()).to.have.property('tooltip', '');
});
});
});
|
"""This script performs image scraping from the Tuni Service website located
at https://www.tunisport.es/.
"""
import os
import os.path
import re
import csv
import sys
import time
import logging
import logging.handlers
import requests
from bs4 import BeautifulSoup
import xlsxwriter
from PIL import Image
# Directory name for saving log files
LOG_FOLDER = 'logs'
# Log file name
LOG_NAME = 'scraper.log'
# Full path to the log file
LOG_PATH = os.path.join(LOG_FOLDER, LOG_NAME)
# Maximum log file size
LOG_SIZE = 2 * 1024 * 1024
# Log files count for cyclic rotation
LOG_BACKUPS = 2
# Timeout for web server response (seconds)
TIMEOUT = 5
# Maximum retries count for executing request if an error occurred
MAX_RETRIES = 3
# The delay after executing an HTTP request (seconds)
SLEEP_TIME = 2
# Host URL for the Tuni Service site
HOST_URL = 'https://www.tunisport.es'
# URL for brands list
BRANDS_URL = HOST_URL + '/catalog/chip-tuning'
# HTTP headers for making the scraper more "human-like"
HEADERS = {
'User-Agent': ('Mozilla/5.0 (Windows NT 6.1; rv:88.0)'
' Gecko/20100101 Firefox/88.0'),
'Accept': '*/*',
}
# Common text for displaying while script is shutting down
FATAL_ERROR_STR = 'Fatal error. Shutting down.'
# Regular expression for extraction image URL from the CSS style
IMAGE_RE = re.compile(r'^background-image:url\((.*)\)$')
# Characters not allowed in filenames
FORBIDDEN_CHAR_RE = r'[<>:"\/\\\|\?\*]'
# Name of the file where URLs for processed brands are stored
PROCESSED_BRANDS_FILENAME = 'processed_brands.txt'
# Script entry point
def main():
setup_logging()
logging.info('Scraping process initialization.')
try:
brands = get_brands()
except Exception as e:
logging.error('Error while retrieving brands list. ' + str(e) + '\n'
+ FATAL_ERROR_STR)
return
logging.info(f'Total brands count: {len(brands)}')
processed_brands = load_brand_list()
logging.info(f'Already scraped brands count: {len(processed_brands)}')
for brand in brands:
if brand['url'] not in processed_brands:
if scrape_brand(brand['url']):
processed_brands.append(brand['url'])
save_brand_list(processed_brands)
else:
logging.error(FATAL_ERROR_STR)
return
if len(processed_brands) > 4:
break
logging.info('Scraping process complete.')
# Setting up configuration for logging
def setup_logging():
logFormatter = logging.Formatter(
fmt='[%(asctime)s] %(filename)s:%(lineno)d %(levelname)s - %(message)s',
datefmt='%d.%m.%Y %H:%M:%S')
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.INFO)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
if not os.path.exists(LOG_FOLDER):
try:
os.mkdir(LOG_FOLDER)
except OSError:
logging.warning('Не удалось создать папку для журнала ошибок.')
if os.path.exists(LOG_FOLDER):
fileHandler = logging.handlers.RotatingFileHandler(
LOG_PATH, mode='a', maxBytes=LOG_SIZE, backupCount=LOG_BACKUPS)
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
# Retrieving HTTP GET response implying TIMEOUT and HEADERS
def get_response(url: str, params: dict=None) -> requests.Response:
"""Input and output parameters are the same as for requests.get() function.
Also retries, timeouts, headers and error handling are ensured.
"""
for attempt in range(0, MAX_RETRIES):
try:
r = requests.get(url, headers=HEADERS, timeout=TIMEOUT,
params=params)
except requests.exceptions.RequestException:
time.sleep(SLEEP_TIME)
else:
time.sleep(SLEEP_TIME)
if r.status_code != requests.codes.ok:
logging.error(f'Error {r.status_code} while accessing {url}.')
return None
return r
logging.error(f'Error: can\'t execute HTTP request while accessing {url}.')
return None
# Retrieve an image from URL and save it to a file
def save_image(url: str, filename: str) -> bool:
r = get_response(url)
try:
with open(filename, 'wb') as f:
f.write(r.content)
except OSError:
logging.error('Error: can\'t save an image to the disk.')
return False
except Exception as e:
logging.error('Error while retrieving an image from URL: ' + str(e))
return False
return True
def scrape_page(url: str) -> dict:
"""Scrapes single page with given URL.
Returns a dict containing page info:
{
'previous_caption': str - last but one text element in "breadcrumb"
section;
'current_caption': str - last text element in "breadcrumb" section;
'items': list(dict)
}
Each item is a dict as follows:
{
'caption': str,
'url': str,
'image_url': str
}
"""
response = get_response(url)
if response == None:
return None
soup = BeautifulSoup(response.text, 'html.parser')
previous_caption = soup.find_all('a', class_='breadcrump')[-1].get_text()
current_caption = soup.find('span', class_='breadcrump__active').get_text()
result = {
'previous_caption': previous_caption.strip(),
'current_caption': current_caption.strip(),
'items': []
}
items = (soup.find('div', class_='col-md-10')
.find('div', class_='row')
.find_all('a'))
for item in items:
new_item = dict()
new_item['url'] = HOST_URL + item['href']
new_item['image_url'] = HOST_URL + re.findall(IMAGE_RE,
item.div['style'])[0]
new_item['caption'] = item.p.get_text().strip()
result['items'].append(new_item)
return result
def get_brands() -> list:
"""Returns the list of all brands. Each list's item is a dict as follows:
{
'caption': str,
'url': str
}
"""
response = get_response(BRANDS_URL)
if response == None:
return None
soup = BeautifulSoup(response.text, 'html.parser')
brands = []
items = (soup.find('div', class_='col-md-10')
.find('div', class_='row')
.find_all('a'))
for item in items:
new_item = {
'url': HOST_URL + item['href'],
'caption': item.p.get_text().strip(),
}
brands.append(new_item)
return brands
def save_item(item: dict, worksheet: xlsxwriter.worksheet.Worksheet,
row: int, max_image_width: int) -> int:
"""Saves a given item as an image file and as a row with text and graphical
data in an Excel worksheet.
Input:
item: dict - a dictionary with item data as follows:
{
'brand': str,
'model': str,
'submodel': str,
'url': str,
'image_url': str,
}
worksheet: xlsxwriter.worksheet.Worksheet - the Excel worksheet for
the item to be saved;
row: int - row number of the Excel worksheet to write the item's data;
max_image_width: int - previously retrieved maximum item's image width,
used for column width ajusting.
Returns:
new maximum image width (int) or None if an error occured.
"""
image_name = item['brand'] + '-' + item['model'] + '-' + item['submodel']
image_name = re.sub(FORBIDDEN_CHAR_RE, '-', image_name)
image_name = re.sub(r'\s+', '-', image_name)
image_name = re.sub(r'-+', '-', image_name)
image_name = re.sub(r'-\.\.\.$', '', image_name)
image_name += '.' + item['image_url'].split('.')[-1]
image_path = os.path.join(item['brand'], image_name)
if not os.path.exists(item['brand']):
try:
os.mkdir(item['brand'])
except OSError:
logging.error(f"Can't create a folder for brand {item['brand']}.")
return None
if not save_image(item['image_url'], image_path):
return None
image_width, image_height = Image.open(image_path).size
max_image_width = max(image_width, max_image_width)
brand_model = item['brand'] + ' ' + item['model']
worksheet.write_url(row, 0, item['url'], string=brand_model)
worksheet.write(row, 1, item['submodel'])
worksheet.set_row_pixels(row, image_height)
worksheet.set_column_pixels(2, 2, max_image_width)
worksheet.insert_image(row, 2, image_path)
worksheet.write(row, 3, image_name)
return max_image_width
def scrape_brand(url: str) -> bool:
""" Scrapes entire single brand for a given URL.
Returns True on success and False otherwise.
"""
def finish_brand_scraping():
try:
workbook.close()
except Exception as e:
logging.error(f'Can\'t save {xlsx_filename} workbook. ' + str(e))
return False
logging.info(f'Total items scraped: {row_count}')
logging.info(f'Beginnig scraping for brand {url}')
try:
scraped_page = scrape_page(url)
xlsx_filename = scraped_page['current_caption'] + '.xlsx'
except Exception as e:
logging.error('Scraping initial page for brand failed. ' + str(e))
return False
logging.info(f'Total models count: {len(scraped_page["items"])}')
try:
workbook = xlsxwriter.Workbook(xlsx_filename)
except Exception as e:
logging.error(f'Can\'t create {xlsx_filename} workbook. ' + str(e))
return False
bold = workbook.add_format({'bold': True})
worksheet = workbook.add_worksheet()
worksheet.write(0, 0, 'Бренд + Авто', bold)
worksheet.write(0, 1, 'Модель', bold)
worksheet.write(0, 2, 'Фото', bold)
worksheet.write(0, 3, 'Название фото', bold)
row_count = 0
max_image_width = 0
try:
for model in scrape_page(url)['items']:
logging.info(f'Scraping data for model {model["url"]}')
model_page = scrape_page(model['url'])
for submodel in model_page['items']:
row_count += 1
item_to_save = {
'brand': model_page['previous_caption'],
'model': model_page['current_caption'],
'submodel': submodel['caption'],
'url': submodel['url'],
'image_url': submodel['image_url'],
}
max_image_width = save_item(item_to_save, worksheet,
row_count, max_image_width)
# Error while saving item
if max_image_width == None:
finish_brand_scraping()
return False
except Exception as e:
logging.error('Failure while scraping pages for car model. ' + str(e))
finish_brand_scraping()
return False
finish_brand_scraping()
return True
# Saves a list of URLs of processed brands
def save_brand_list(brands: list) -> bool:
try:
with open(PROCESSED_BRANDS_FILENAME, 'w') as f:
f.writelines([brand + '\n' for brand in brands])
except OSError:
logging.warning('Can\'t save processed brands list.')
return False
return True
# Loads previously saved list of URLs of processed brands
def load_brand_list() -> list:
brands = []
if os.path.exists(PROCESSED_BRANDS_FILENAME):
try:
with open(PROCESSED_BRANDS_FILENAME, 'r') as f:
brands = f.readlines()
except OSError:
logging.warning('Can\'t load processed brands list.')
return []
return [brand.strip() for brand in brands]
if __name__ == '__main__':
main()
|
'use strict';
const assert = require('assert');
const rds = require('ali-rds');
let count = 0;
module.exports = app => {
app.addSingleton('mssql', createOneClient);
};
function createOneClient(config, app) {
assert(config.host && config.port && config.user && config.database,
`[egg-mssql] 'host: ${config.host}', 'port: ${config.port}', 'user: ${config.user}', 'database: ${config.database}' are required on config`);
app.coreLogger.info('[egg-mssql] connecting %s@%s:%s/%s',
config.user, config.host, config.port, config.database);
const client = rds(config);
app.beforeStart(function* () {
const rows = yield client.query('select now() as currentTime;');
const index = count++;
app.coreLogger.info(`[egg-mssql] instance[${index}] status OK, rds currentTime: ${rows[0].currentTime}`);
});
return client;
}
|
/* eslint-disable no-await-in-loop */
const cloneDeep = require('lodash/cloneDeep');
const nanoid = require('nanoid');
const RedPop = require('../RedPop');
const EventBatch = require('./EventBatch/EventBatch');
const PendingEvents = require('./PendingEvents');
const IdleConsumers = require('./IdleConsumers');
const defaultConfig = require('./config');
/**
* Consumer is an abstract class that encapsulates
* the functionalty to run a consumer. A subclass
* should extend this class and override the abstract
* method(s). At a minimum, processEvent should be extended.
*
*/
class Consumer extends RedPop {
constructor(config) {
const rpConfig = config || cloneDeep(defaultConfig);
// process configuration in parent class RedPop
super(rpConfig);
this.processing = false;
}
/**
* Initializer that runs at the begin of the first subscribe batch
*/
async _init() {
// Ensure consumer group exists
try {
await this.xgroup(
'CREATE',
this.config.stream.name,
this.config.consumer.group,
'$',
'MKSTREAM'
);
} catch (e) {
console.log(
`Found existing consumer group '${this.config.consumer.group}'`
);
}
await this.init();
}
/**
* setConfig
* Sets consumer specific configuration settings
*/
setConfig() {
const { consumer } = this.config;
const defConsumer = defaultConfig.consumer;
consumer.name = `${this.config.consumer.name}_${nanoid.nanoid()}`;
consumer.waitTimeMs = consumer.waitTimeMs || defConsumer.waitTimeMs;
consumer.batchSize = consumer.batchSize || defConsumer.batchSize;
consumer.idleTimeoutMs = consumer.idleTimeoutMs || defConsumer.batchSize;
consumer.eventMaximumReplays =
consumer.eventMaximumReplays || defConsumer.eventMaximumReplays;
}
/**
* processEvents
*
* Processes a batch of events calling the users. utiltiy processEvent()
* be overridden in a subclass
*
* @param {Object} events - Array of events received via ioredis.
*
*/
async _processEvents(batch) {
const events = batch.getEvents();
await events.reduce(async (memo, event) => {
await memo;
const currentEvent = event;
const result = await this.processEvent(currentEvent);
if (result) {
await this.xack(currentEvent.id);
}
return memo;
}, Promise.resolve());
}
/**
* poll -- Main loop to poll Redis for events
*/
async start() {
const { stream, consumer } = this.config;
if (!this.connected) {
this.connect();
}
await this._init();
let done = false;
if (!stream?.name) {
console.log('Error - Consumer requires a stream to be configured');
return false;
}
while (!done) {
try {
const batch = await this.xreadgroup([
'GROUP',
consumer.group,
consumer.name,
'BLOCK',
consumer.waitTimeMs,
'COUNT',
consumer.batchSize,
'STREAMS',
stream.name,
'>'
]);
if (!batch) {
await this._onBatchesComplete();
} else {
const eventBatch = new EventBatch(batch);
await this._onBatchReceived(eventBatch);
await this._onBatchComplete();
}
if (this.config.consumer.runOnce) {
// used for tests to break out of the loop
// normally this loop never ends until the
// process is terminated.
done = true;
}
} catch (e) {
try {
console.log('Redis server connection lost, resetting connection....');
console.log('Disconnecting');
this.disconnectRedis();
console.log('Reconnecting');
this.connected = false;
this.connect();
console.log('Initializing');
this._init();
console.log('Finished resetting connection');
} catch (e1) {
console.log(e1);
}
}
}
return 'stopped';
}
/**
* Events
*/
/**
* onBatchesComplete()
*/
async _onBatchesComplete() {
// Perform post-processing after all
// events in the stream have been played
this.processing = false;
await this.onBatchesComplete();
await this._processPendingEvents();
await this._removeIdleConsumers();
}
/**
* onBatchReceived()
* Process the new batch of events.
* this.processevents should be overridden in a
* subclass of Consumer
*/
async _onBatchReceived(eventBatch) {
this.processing = true;
await this._processEvents(eventBatch);
}
/**
* onBatchComplete()
* Perform any batch-specific post-processing
*/
async _onBatchComplete() {
await this.onBatchComplete();
}
/**
* processPendingEvent()
* Process any events that were played by other
* consumers and didn't result in an xack. This
* can happen if the subbscriber is terminated in
* the middle of processing an event or if an unhandled
* error occurs in the processEvent() call.
*/
async _processPendingEvents() {
const pendingEvents = new PendingEvents(this);
await pendingEvents.processPendingEvents();
}
/**
* removeIdleConsumers()
* Remove consumers that have been idle
* longer than config.consumer.idleConsumerTimeoutMs
*/
async _removeIdleConsumers() {
const idleConsumers = new IdleConsumers(this);
await idleConsumers.removeIdleConsumers();
}
/**
/**
* * Abstract Methods -- Override in sub-classes
*/
/**
* processEvent
*
*/
async processEvent(event) {
console.log('Event Received', event);
return true;
}
/**
* onBatchComplete
*
*/
async onBatchComplete() {
return true;
}
/**
* onBatchesComplete
*
*/
async onBatchesComplete() {
return true;
}
/**
* init()
*
*/
async init() {
return true;
}
}
module.exports = Consumer;
|
#!/usr/bin/env python3
import random
shared = 0
trial_number = 10000
for i in range(trial_number):
birthdays = [0] * 365
for j in range(25):
date = random.randint(0, 364)
birthdays[date] += 1
if birthdays[date] == 2:
shared += 1
break
print(f'{shared / trial_number : .3f}')
|
/**
* @license Highcharts JS v6.0.0 (2017-10-04)
*
* (c) 2009-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(H) {
/**
* (c) 2009-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
/**
* Highcharts module to hide overlapping data labels. This module is included in
* Highcharts.
*/
var Chart = H.Chart,
each = H.each,
objectEach = H.objectEach,
pick = H.pick,
addEvent = H.addEvent;
// Collect potensial overlapping data labels. Stack labels probably don't need
// to be considered because they are usually accompanied by data labels that lie
// inside the columns.
Chart.prototype.callbacks.push(function(chart) {
function collectAndHide() {
var labels = [];
// Consider external label collectors
each(chart.labelCollectors || [], function(collector) {
labels = labels.concat(collector());
});
each(chart.yAxis || [], function(yAxis) {
if (
yAxis.options.stackLabels &&
!yAxis.options.stackLabels.allowOverlap
) {
objectEach(yAxis.stacks, function(stack) {
objectEach(stack, function(stackItem) {
labels.push(stackItem.label);
});
});
}
});
each(chart.series || [], function(series) {
var dlOptions = series.options.dataLabels,
// Range series have two collections
collections = series.dataLabelCollections || ['dataLabel'];
if (
(dlOptions.enabled || series._hasPointLabels) &&
!dlOptions.allowOverlap &&
series.visible
) { // #3866
each(collections, function(coll) {
each(series.points, function(point) {
if (point[coll]) {
point[coll].labelrank = pick(
point.labelrank,
point.shapeArgs && point.shapeArgs.height
); // #4118
labels.push(point[coll]);
}
});
});
}
});
chart.hideOverlappingLabels(labels);
}
// Do it on render and after each chart redraw
addEvent(chart, 'render', collectAndHide);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to
* provide a smooth visual imression.
*/
Chart.prototype.hideOverlappingLabels = function(labels) {
var len = labels.length,
label,
i,
j,
label1,
label2,
isIntersecting,
pos1,
pos2,
parent1,
parent2,
padding,
bBox,
intersectRect = function(x1, y1, w1, h1, x2, y2, w2, h2) {
return !(
x2 > x1 + w1 ||
x2 + w2 < x1 ||
y2 > y1 + h1 ||
y2 + h2 < y1
);
};
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
// Mark with initial opacity
label.oldOpacity = label.opacity;
label.newOpacity = 1;
// Get width and height if pure text nodes (stack labels)
if (!label.width) {
bBox = label.getBBox();
label.width = bBox.width;
label.height = bBox.height;
}
}
}
// Prevent a situation in a gradually rising slope, that each label will
// hide the previous one because the previous one always has lower rank.
labels.sort(function(a, b) {
return (b.labelrank || 0) - (a.labelrank || 0);
});
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
if (
label1 && label2 &&
label1 !== label2 && // #6465, polar chart with connectEnds
label1.placed && label2.placed &&
label1.newOpacity !== 0 && label2.newOpacity !== 0
) {
pos1 = label1.alignAttr;
pos2 = label2.alignAttr;
// Different panes have different positions
parent1 = label1.parentGroup;
parent2 = label2.parentGroup;
// Substract the padding if no background or border (#4333)
padding = 2 * (label1.box ? 0 : (label1.padding || 0));
isIntersecting = intersectRect(
pos1.x + parent1.translateX,
pos1.y + parent1.translateY,
label1.width - padding,
label1.height - padding,
pos2.x + parent2.translateX,
pos2.y + parent2.translateY,
label2.width - padding,
label2.height - padding
);
if (isIntersecting) {
(label1.labelrank < label2.labelrank ? label1 : label2)
.newOpacity = 0;
}
}
}
}
// Hide or show
each(labels, function(label) {
var complete,
newOpacity;
if (label) {
newOpacity = label.newOpacity;
if (label.oldOpacity !== newOpacity && label.placed) {
// Make sure the label is completely hidden to avoid catching
// clicks (#4362)
if (newOpacity) {
label.show(true);
} else {
complete = function() {
label.hide();
};
}
// Animate or set the opacity
label.alignAttr.opacity = newOpacity;
label[label.isOld ? 'animate' : 'attr'](
label.alignAttr,
null,
complete
);
}
label.isOld = true;
}
});
};
}(Highcharts));
}));
|
# Copyright (c) 2013-2020 Philip Hane
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. 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.
#
# 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.
# CLI python script interface for ipwhois.utils lookups.
import argparse
from collections import OrderedDict
import json
from ipwhois.utils import (ipv4_lstrip_zeros, calculate_cidr, get_countries,
ipv4_is_defined, ipv6_is_defined,
ipv4_generate_random, ipv6_generate_random,
unique_everseen, unique_addresses)
# CLI ANSI rendering
ANSI = {
'end': '\033[0m',
'b': '\033[1m',
'ul': '\033[4m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'cyan': '\033[36m'
}
# Setup the arg parser.
parser = argparse.ArgumentParser(
description='ipwhois utilities CLI interface'
)
parser.add_argument(
'--ipv4_lstrip_zeros',
type=str,
nargs=1,
metavar='"IP ADDRESS"',
help='Strip leading zeros in each octet of an IPv4 address.'
)
parser.add_argument(
'--calculate_cidr',
type=str,
nargs=2,
metavar='"IP ADDRESS"',
help='Calculate a CIDR range(s) from a start and end IP address.'
)
parser.add_argument(
'--get_countries',
action='store_true',
help='Output a dictionary containing ISO_3166-1 country codes to names.'
)
parser.add_argument(
'--get_country',
type=str,
nargs=1,
metavar='"COUNTRY CODE"',
help='Output the ISO_3166-1 name for a country code.'
)
parser.add_argument(
'--ipv4_is_defined',
type=str,
nargs=1,
metavar='"IP ADDRESS"',
help='Check if an IPv4 address is defined (in a reserved address range).'
)
parser.add_argument(
'--ipv6_is_defined',
type=str,
nargs=1,
metavar='"IP ADDRESS"',
help='Check if an IPv6 address is defined (in a reserved address range).'
)
parser.add_argument(
'--ipv4_generate_random',
type=int,
nargs=1,
metavar='TOTAL',
help='Generate random, unique IPv4 addresses that are not defined (can be '
'looked up using ipwhois).'
)
parser.add_argument(
'--ipv6_generate_random',
type=int,
nargs=1,
metavar='TOTAL',
help='Generate random, unique IPv6 addresses that are not defined (can be '
'looked up using ipwhois).'
)
parser.add_argument(
'--unique_everseen',
type=json.loads,
nargs=1,
metavar='"ITERABLE"',
help='List unique elements from input iterable, preserving the order.'
)
parser.add_argument(
'--unique_addresses',
type=str,
nargs=1,
metavar='"FILE PATH"',
help='Search an input file, extracting, counting, and summarizing '
'IPv4/IPv6 addresses/networks.'
)
# Output options
group = parser.add_argument_group('Output options')
group.add_argument(
'--colorize',
action='store_true',
help='If set, colorizes the output using ANSI. Should work in most '
'platform consoles.'
)
# Get the args
script_args = parser.parse_args()
if script_args.ipv4_lstrip_zeros:
print(ipv4_lstrip_zeros(address=script_args.ipv4_lstrip_zeros[0]))
elif script_args.calculate_cidr:
try:
result = calculate_cidr(
start_address=script_args.calculate_cidr[0],
end_address=script_args.calculate_cidr[1]
)
print('{0}Found {1} CIDR blocks for ({2}, {3}){4}:\n{5}'.format(
ANSI['green'] if script_args.colorize else '',
len(result),
script_args.calculate_cidr[0],
script_args.calculate_cidr[1],
ANSI['end'] if script_args.colorize else '',
'\n'.join(result)
))
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.get_countries:
try:
result = get_countries()
print('{0}Found {1} countries{2}:\n{3}'.format(
ANSI['green'] if script_args.colorize else '',
len(result),
ANSI['end'] if script_args.colorize else '',
'\n'.join(['{0}: {1}'.format(k, v) for k, v in (
OrderedDict(sorted(result.items())).iteritems())])
))
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.get_country:
try:
countries = get_countries()
result = countries[script_args.get_country[0].upper()]
print('{0}Match found for country code ({1}){2}:\n{3}'.format(
ANSI['green'] if script_args.colorize else '',
script_args.get_country[0],
ANSI['end'] if script_args.colorize else '',
result
))
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.ipv4_is_defined:
try:
result = ipv4_is_defined(address=script_args.ipv4_is_defined[0])
if result[0]:
print('{0}{1} is defined{2}:\n{3}'.format(
ANSI['green'] if script_args.colorize else '',
script_args.ipv4_is_defined[0],
ANSI['end'] if script_args.colorize else '',
'Name: {0}\nRFC: {1}'.format(result[1], result[2])
))
else:
print('{0}{1} is not defined{2}'.format(
ANSI['yellow'] if script_args.colorize else '',
script_args.ipv4_is_defined[0],
ANSI['end'] if script_args.colorize else ''
))
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.ipv6_is_defined:
try:
result = ipv6_is_defined(address=script_args.ipv6_is_defined[0])
if result[0]:
print('{0}{1} is defined{2}:\n{3}'.format(
ANSI['green'] if script_args.colorize else '',
script_args.ipv6_is_defined[0],
ANSI['end'] if script_args.colorize else '',
'Name: {0}\nRFC: {1}'.format(result[1], result[2])
))
else:
print('{0}{1} is not defined{2}'.format(
ANSI['yellow'] if script_args.colorize else '',
script_args.ipv6_is_defined[0],
ANSI['end'] if script_args.colorize else ''
))
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.ipv4_generate_random:
try:
result = ipv4_generate_random(total=script_args.ipv4_generate_random[0])
for random_ip in result:
print(random_ip)
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.ipv6_generate_random:
try:
result = ipv6_generate_random(total=script_args.ipv6_generate_random[0])
for random_ip in result:
print(random_ip)
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.unique_everseen:
try:
result = list(unique_everseen(iterable=script_args.unique_everseen[0]))
print('{0}Unique everseen{1}:\n{2}'.format(
ANSI['green'] if script_args.colorize else '',
ANSI['end'] if script_args.colorize else '',
result
))
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
elif script_args.unique_addresses:
try:
result = unique_addresses(file_path=script_args.unique_addresses[0])
tmp = []
for k, v in sorted(result.items(), key=lambda kv: int(kv[1]['count']),
reverse=True):
tmp.append('{0}{1}{2}: Count: {3}, Ports: {4}'.format(
ANSI['b'] if script_args.colorize else '',
k,
ANSI['end'] if script_args.colorize else '',
v['count'],
json.dumps(v['ports'])
))
print('{0}Found {1} unique addresses{2}:\n{3}'.format(
ANSI['green'] if script_args.colorize else '',
len(result),
ANSI['end'] if script_args.colorize else '',
'\n'.join(tmp)
))
except Exception as e:
print('{0}Error{1}: {2}'.format(ANSI['red'], ANSI['end'], str(e)))
|
from electrum_ltc.i18n import _
fullname = _('Cosigner Pool')
description = ' '.join([
_("This plugin facilitates the use of multi-signatures wallets."),
_("It sends and receives partially signed transactions from/to your cosigner wallet."),
_("Transactions are encrypted and stored on a remote server.")
])
#requires_wallet_type = ['2of2', '2of3']
available_for = ['qt']
|
import React, { useState } from 'react';
import api from '../../services/api';
export default function Login({ history }){
const [email, setEmail] = useState('');
async function handleSubmit(event){
event.preventDefault();
const response = await api.post('/sessions', { email });
const { _id } = response.data;
localStorage.setItem('user', _id);
history.push('/dashboard');
}
return (
<>
<p>
Ofereça <strong>spots</strong> para programadores e encontre <strong>talentos</strong> para sua empresa
</p>
<form onSubmit={handleSubmit}>
<label htmlFor="email">E-MAIL *</label>
<input
type="email"
id="email"
placeholder="Seu melhor e-mail"
value={email}
onChange={event => setEmail(event.target.value)}
/>
<button className="btn" type="submit">Entre</button>
</form>
</>
);
}; |
module.exports = [
"dnn",
"evoq",
"eslint",
"fetch-ie8",
"react-dom",
"lodash",
"bool",
"func",
"dropdown",
"globals",
"init",
"cors",
"api",
"integrations",
"const",
"dom",
"stringify",
"debounce",
"debounced",
"unmount",
"ceil",
"px",
"rgba",
"svg",
"html",
"src",
"calc",
"img",
"jpg",
"nowrap",
"js",
"dropzone",
"ondropactivate",
"ondragenter",
"draggable",
"ondrop",
"ondragleave",
"ondropdeactivate",
"droppable",
"onmove",
"onend",
"interactable",
"webkit",
"rect",
"concat",
"resize",
"sortable",
"socialpanelheader",
"socialpanelbody",
"asc",
"dx",
"dy",
"num",
"reactid",
"currentcolor",
"ui",
"checkbox",
"tooltip",
"scrollbar",
"unshift",
"dragstart",
"contenteditable",
"addons",
"tbody",
"resizable",
"resizemove",
"resizestart",
"resizeend",
"resizing",
"resized",
"ondropmove",
"moz",
"evq",
"btn",
"addon",
"substring",
"jpeg",
"gif",
"pdf",
"png",
"ppt",
"txt",
"autocomplete",
"utils",
"js-htmlencode",
"webpack",
"undef",
"analytics",
"dataset",
"checkmark",
"li",
"br",
"localizations",
"javascript",
"ie",
"na",
"searchable",
"clearable",
"http",
"decrement",
"ok",
"checkboxes",
"ddmmyy",
"mmddyy",
"ddmmyyyy",
"mmddyyyy",
"yyyymmdd",
"td",
"th",
"marketo",
"salesforce",
"captcha",
"rgb",
"sunday",
"xxxx",
"typeof",
"popup",
"ccc",
"aaf",
"dddd",
"redux",
"middleware",
"dev",
"util",
"searchpanel",
"uncollapse",
"dev",
"devtools",
"ctrl"
] |
const {Client} = require('discord.js')
const config = require('../config.json');
const { Db } = require('mongodb');
/**
* @param {Client} client
* @param {Db} maindb
* @param {Db} alicedb
*/
module.exports.run = async (client, maindb, alicedb) => {
console.log("Discord API connection established\nAlice Synthesis Thirty is up and running");
const disabledCommandsAndUtils = await alicedb.collection("channelsettings").find({}, {projection: {_id: 0, channelID: 1, disabledCommands: 1, disabledUtils: 1}}).toArray();
require('./message').setDisabledCommandsAndUtils(disabledCommandsAndUtils);
let maintenance = require('./message').maintenance;
const activity_list = [
["Underworld Console", "PLAYING"],
["Rulid Village", "WATCHING"],
[config.prefix + "help", "LISTENING"],
["Dark Territory", "WATCHNG"],
["in Axiom church", "PLAYING"],
["with Integrity Knights", "PLAYING"],
["flowers from my beloved Fragnant Olive", "WATCHING"],
["Uncle Bercoulli's orders", "LISTENING"],
["Centoria", "WATCHING"],
["Human Empire", "WATCHING"],
["The Great War of Underworld", "COMPETING"]
];
// Custom activity, daily reset, and unverified prune
setInterval(() => {
maintenance = require('./message').maintenance;
client.utils.get("unverified").run(client, alicedb);
if (maintenance) {
return;
}
client.utils.get("dailyreset").run(client, alicedb);
client.utils.get('birthdaytrack').run(client, maindb, alicedb);
const index = Math.floor(Math.random() * activity_list.length);
client.user.setActivity(activity_list[index][0], {type: activity_list[index][1]});
}, 10000);
// Utilities
setInterval(() => {
maintenance = require('./message').maintenance;
if (!maintenance) {
console.log("Utilities running");
client.utils.get("trackfunc").run(client, maindb);
client.utils.get("clantrack").run(client, maindb, alicedb);
client.utils.get("dailytrack").run(client, maindb, alicedb);
client.utils.get("weeklytrack").run(client, maindb, alicedb);
client.utils.get("auctiontrack").run(client, maindb, alicedb);
}
}, 600000);
// Clan rank update
setInterval(() => {
if (!maintenance) {
client.utils.get("clanrankupdate").run(maindb);
}
}, 1200000);
// Occasional report command broadcast
const nextReportBroadcast = (await alicedb.collection("playerpoints").findOne({discordid: "386742340968120321"})).nextReportBroadcast;
setTimeout(() => {
if (!maintenance) {
client.utils.get("reportbroadcast").run(client);
}
setInterval(async () => {
await alicedb.collection("playerpoints").updateOne({discordid: "386742340968120321"}, {$inc: {nextReportBroadcast: 3600}});
if (!maintenance) {
client.utils.get("reportbroadcast").run(client);
}
}, 3600000);
}, Math.max(1, nextReportBroadcast * 1000 - Date.now()));
// Mudae role assignment reaction-based on droid cafe
client.subevents.get("mudaeRoleReaction").run(client);
// Challenge role assignment (reaction-based)
client.subevents.get("challengeRoleReaction").run(client);
// Continue mutes
client.subevents.get("muteResume").run(client, alicedb);
};
module.exports.config = {
name: "ready"
};
|
'use strict'
const PuppeteerExtraPlugin = require('puppeteer-extra-plugin')
/**
* Pass the Webdriver Test.
*/
class Plugin extends PuppeteerExtraPlugin {
constructor (opts = { }) { super(opts) }
get name () { return 'stealth/evasions/navigator.webdriver' }
async onPageCreated (page) {
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', {
get: () => false
})
})
}
}
module.exports = function (pluginConfig) { return new Plugin(pluginConfig) }
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const passphraseModule = tslib_1.__importStar(require("phaeton-passphrase"));
const utils_1 = require("./utils");
exports.getFirstLineFromString = (multilineString) => typeof multilineString === 'string'
? multilineString.split(/[\r\n]+/)[0]
: undefined;
exports.getInputsFromSources = async ({ passphrase: passphraseInput, secondPassphrase: secondPassphraseInput, password: passwordInput, data: dataInput, }) => {
const [passphraseIsRequired, secondPassphraseIsRequired, passwordIsRequired, dataIsRequired,] = [passphraseInput, secondPassphraseInput, passwordInput, dataInput].map(input => !!input && input.source === 'stdin');
const stdIn = await utils_1.getStdIn({
passphraseIsRequired,
secondPassphraseIsRequired,
passwordIsRequired,
dataIsRequired,
});
const passphrase = typeof stdIn.passphrase !== 'string' && passphraseInput
? await utils_1.getPassphrase(passphraseInput.source, {
shouldRepeat: passphraseInput.repeatPrompt,
})
: stdIn.passphrase || undefined;
const secondPassphrase = typeof stdIn.secondPassphrase !== 'string' && secondPassphraseInput
? await utils_1.getPassphrase(secondPassphraseInput.source, {
displayName: 'your second secret passphrase',
shouldRepeat: secondPassphraseInput.repeatPrompt,
})
: stdIn.secondPassphrase || undefined;
const passphraseErrors = [passphrase, secondPassphrase]
.filter(Boolean)
.map(pass => passphraseModule.validation
.getPassphraseValidationErrors(pass)
.filter((error) => error.message));
passphraseErrors.forEach(errors => {
if (errors.length > 0) {
const passphraseWarning = errors
.filter((error) => error.code !== 'INVALID_MNEMONIC')
.reduce((accumulator, error) => accumulator.concat(`${error.message.replace(' Please check the passphrase.', '')} `), 'Warning: ');
console.warn(passphraseWarning);
}
});
const password = typeof stdIn.password !== 'string' && passwordInput
? await utils_1.getPassphrase(passwordInput.source, {
displayName: 'your password',
shouldRepeat: passwordInput.repeatPrompt,
})
: stdIn.password || undefined;
const data = typeof stdIn.data !== 'string' && dataInput
? await utils_1.getData(dataInput.source)
: stdIn.data || undefined;
return {
passphrase,
secondPassphrase,
password,
data,
};
};
//# sourceMappingURL=index.js.map
|
function format(txt,compress/*是否为压缩模式*/){/* 格式化JSON源码(对象转换为JSON文本) */
var indentChar = ' ';
if(/^\s*$/.test(txt)){
alert('数据为空,无法格式化! ');
return;
}
try{var data=eval('('+txt+')');}
catch(e){
alert('数据源语法错误,格式化失败! 错误信息: '+e.description,'err');
return;
};
var draw=[],last=false,This=this,line=compress?'':'\n',nodeCount=0,maxDepth=0;
var notify=function(name,value,isLast,indent/*缩进*/,formObj){
nodeCount++;/*节点计数*/
for (var i=0,tab='';i<indent;i++ )tab+=indentChar;/* 缩进HTML */
tab=compress?'':tab;/*压缩模式忽略缩进*/
maxDepth=++indent;/*缩进递增并记录*/
if(value&&value.constructor==Array){/*处理数组*/
draw.push(tab+(formObj?('"'+name+'":'):'')+'['+line);/*缩进'[' 然后换行*/
for (var i=0;i<value.length;i++)
notify(i,value[i],i==value.length-1,indent,false);
draw.push(tab+']'+(isLast?line:(','+line)));/*缩进']'换行,若非尾元素则添加逗号*/
}else if(value&&typeof value=='object'){/*处理对象*/
draw.push(tab+(formObj?('"'+name+'":'):'')+'{'+line);/*缩进'{' 然后换行*/
var len=0,i=0;
for(var key in value)len++;
for(var key in value)notify(key,value[key],++i==len,indent,true);
draw.push(tab+'}'+(isLast?line:(','+line)));/*缩进'}'换行,若非尾元素则添加逗号*/
}else{
if(typeof value=='string')value='"'+value+'"';
draw.push(tab+(formObj?('"'+name+'":'):'')+value+(isLast?'':',')+line);
};
};
var isLast=true,indent=0;
notify('',data,isLast,indent,false);
return draw.join('');
} |
// 模块的名称
const moduleName = `calculator`;
// 定义常量并且导出
// 获取当前输入的值
export const GET_VALUE_NOW = `${moduleName}/get_value_now`;
// 加法
export const ADD_VALUE = `${moduleName}/add_value`;
// 减法
export const MINUS_VALUE = `${moduleName}/minus_value`;
// 计算
export const COMPUTE_VALUE = `${moduleName}/compute_value`;
// 清空数据
export const CLEAN_VALUE = `${moduleName}/clean_value`;
// 记录数据
export const RECORD_VALUE = `${moduleName}/record_value`;
// 退格
export const BACK_SPACE = `${moduleName}/back_space`;
|
// This file was automatically generated. Do not modify.
'use strict';
Blockly.Msg["ARD_180SERVO"] = "0~180 degree Servo (angle)"; // untranslated
Blockly.Msg["ARD_360SERVO"] = "0~360 degree Servo (rotation)"; // untranslated
Blockly.Msg["ARD_7SEGMENT_COMPONENT"] = "7-Segment Display"; // untranslated
Blockly.Msg["ARD_7SEGMENT_COMPONENT_TIP"] = "7-Segment LED Display can be used to show numbers and some characters. It has 7 segments and 1 dot, requiring 8 digital pins on the Arduino to use."; // untranslated
Blockly.Msg["ARD_7SEGMENT_COMPONENT_WARN"] = "Pin used in segment %1 is also present in one of the other segments! Change the pin number."; // untranslated
Blockly.Msg["ARD_7SEGMENT_WRITE"] = "show number"; // untranslated
Blockly.Msg["ARD_7SEGMENT_WRITESEG"] = "Set segment"; // untranslated
Blockly.Msg["ARD_7SEGMENT_WRITESEG_TIP"] = "Set a specific segment of the 7-Segment display high"; // untranslated
Blockly.Msg["ARD_7SEGMENT_WRITE_TIP"] = "Write a specific number to the 7-segment display. Number must be between 0 and 9, otherwise nothing is shown."; // untranslated
Blockly.Msg["ARD_ALLBOTSERVO_ANIMATE"] = "Move AllBot Servo "; // untranslated
Blockly.Msg["ARD_ALLBOTSERVO_ANIMATE_TIP"] = "Move Servo to a specified angle gradually over the animation duration. You can combine this with other servo movements"; // untranslated
Blockly.Msg["ARD_ALLBOTSERVO_WRITE"] = "Set AllBot Servo "; // untranslated
Blockly.Msg["ARD_ALLBOT_ANIMATE"] = "Animate AllBot"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANIMATESERVOS"] = "Servos"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANIMATESPEED"] = "Animation duration (ms):"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANIMATE_TIP"] = "Animate the allbot by moving different servos at the same time. Total duration of this animation can be set. A servo may have only one movement block present."; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLEFRONTLEFT"] = "ankleFrontLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLEFRONTRIGHT"] = "ankleFrontRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLELEFT"] = "ankleLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLEMIDDLELEFT"] = "ankleMiddleLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLEMIDDLERIGHT"] = "ankleMiddleRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLEREARLEFT"] = "ankleRearLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLEREARRIGHT"] = "ankleRearRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_ANKLERIGHT"] = "ankleRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_BACKWARD"] = "AllBot Backward:"; // untranslated
Blockly.Msg["ARD_ALLBOT_CHIRP"] = "AllBot Chirp:"; // untranslated
Blockly.Msg["ARD_ALLBOT_CHIRPSPEED"] = "beeps, beepspeed"; // untranslated
Blockly.Msg["ARD_ALLBOT_CHIRP_TIP"] = "Make the allbot chirp a number of beeps at the given speed (delay in microseconds, use 1 to 255)"; // untranslated
Blockly.Msg["ARD_ALLBOT_FORWARD"] = "AllBot Forward:"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPFRONTLEFT"] = "hipFrontLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPFRONTRIGHT"] = "hipFrontRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPLEFT"] = "hipLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPMIDDLELEFT"] = "hipMiddleLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPMIDDLERIGHT"] = "hipMiddleRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPREARLEFT"] = "hipRearLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPREARRIGHT"] = "hipRearRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_HIPRIGHT"] = "hipRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_KNEEFRONTLEFT"] = "kneeFrontLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_KNEEFRONTRIGHT"] = "kneeFrontRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_KNEEMIDDLELEFT"] = "kneeMiddleLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_KNEEMIDDLERIGHT"] = "kneeMiddleRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_KNEEREARLEFT"] = "kneeRearLeft"; // untranslated
Blockly.Msg["ARD_ALLBOT_KNEEREARRIGHT"] = "kneeRearRight"; // untranslated
Blockly.Msg["ARD_ALLBOT_LEFT"] = "AllBot Left:"; // untranslated
Blockly.Msg["ARD_ALLBOT_LOOKLEFT"] = "AllBot Look Left, speed (ms):"; // untranslated
Blockly.Msg["ARD_ALLBOT_LOOKRIGHT"] = "AllBot Look Right, speed (ms):"; // untranslated
Blockly.Msg["ARD_ALLBOT_LOOK_TIP"] = "Make the allbot look towards a specific direction with the given speed (ms)"; // untranslated
Blockly.Msg["ARD_ALLBOT_RC"] = "AllBot Remote Control Handling"; // untranslated
Blockly.Msg["ARD_ALLBOT_RCCOMMAND"] = "On receiving command "; // untranslated
Blockly.Msg["ARD_ALLBOT_RCCOMMANDS"] = "Commands "; // untranslated
Blockly.Msg["ARD_ALLBOT_RCCOMMAND_SINGLE"] = "This block must be inside an AllBot Remote Control block "; // untranslated
Blockly.Msg["ARD_ALLBOT_RCCOMMAND_TIP"] = "Set the actions the AllBot must do on receiving a command."; // untranslated
Blockly.Msg["ARD_ALLBOT_RCDO"] = "Do "; // untranslated
Blockly.Msg["ARD_ALLBOT_RCSERIAL"] = "Use Serial to view Commands"; // untranslated
Blockly.Msg["ARD_ALLBOT_RC_SPEED"] = "RC Speed"; // untranslated
Blockly.Msg["ARD_ALLBOT_RC_SPEED_TIP"] = "The speed as set in the Remote Control App"; // untranslated
Blockly.Msg["ARD_ALLBOT_RC_TIMES"] = "RC Times"; // untranslated
Blockly.Msg["ARD_ALLBOT_RC_TIMES_TIP"] = "The times (number of steps) as set in the Remote Control App"; // untranslated
Blockly.Msg["ARD_ALLBOT_RC_TIP"] = "A block to react to the AllBot Remote Control App on your smarthphone. Check Serial to see in the serial monitor what commands are received. Note: Your AllBot shield must be switched to RECEIVE after programming it."; // untranslated
Blockly.Msg["ARD_ALLBOT_RIGHT"] = "AllBot Right:"; // untranslated
Blockly.Msg["ARD_ALLBOT_SCARED"] = "AllBot Look Scared:"; // untranslated
Blockly.Msg["ARD_ALLBOT_SCAREDBEEPS"] = "shakes, beeps:"; // untranslated
Blockly.Msg["ARD_ALLBOT_SCARED_TIP"] = "Make the allbot shake the given number of shakes, and beep the given number of beeps "; // untranslated
Blockly.Msg["ARD_ALLBOT_SERVOHUB"] = "AllBot Servo motor"; // untranslated
Blockly.Msg["ARD_ALLBOT_STEPS"] = "steps, stepspeed"; // untranslated
Blockly.Msg["ARD_ALLBOT_WALK_TIP"] = "Make the allbot move a number of steps with the given speed (ms) for one step"; // untranslated
Blockly.Msg["ARD_ANALOGREAD"] = "Lecture du signal analogique #";
Blockly.Msg["ARD_ANALOGREAD_TIP"] = "Valeur de retour entre 0 et 1024";
Blockly.Msg["ARD_ANALOGWRITE"] = "Ecriture du signal analogique #";
Blockly.Msg["ARD_ANALOGWRITE_ERROR"] = "The analogue value set must be between 0 and 255"; // untranslated
Blockly.Msg["ARD_ANALOGWRITE_TIP"] = "Ecrit une valeur analogique comprise entre 0 et 255 sur un port PWM spécifique";
Blockly.Msg["ARD_ANASENSOR"] = "Analog Sensor"; // untranslated
Blockly.Msg["ARD_ANASENSOR_COMPONENT"] = "Analog Sensor"; // untranslated
Blockly.Msg["ARD_ANASENSOR_DEFAULT_NAME"] = "AnaSensor1"; // untranslated
Blockly.Msg["ARD_ANASENSOR_READ"] = "Read analog sensor"; // untranslated
Blockly.Msg["ARD_ANASENSOR_TIP"] = "Connect an analog sensor to an analog pin, so as to read its value. On an Arduino UNO a value between 0 and 1024 is returned, corresponding to a measured value between 0 and 5V. Eg.: an LDR sensor, a potmeter, ..."; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_LENGTH"] = "of length"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_LENGTH_TOOLTIP"] = "Create an array containing the given number of elements"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_TITLE"] = "array"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_TITLE0"] = "Create"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_TITLE2"] = "with values"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_WITH_CONTAINER_TITLE_ADD"] = "array"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_WITH_CONTAINER_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this array block."; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_WITH_INPUT_WITH"] = "Create array with"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_WITH_ITEM_TITLE"] = "item"; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_WITH_ITEM_TOOLTIP"] = "Add an item to the array."; // untranslated
Blockly.Msg["ARD_ARRAY_CREATE_WITH_TOOLTIP"] = "Create an array with any number of items"; // untranslated
Blockly.Msg["ARD_ARRAY_DEFAULT_NAME"] = "Array1"; // untranslated
Blockly.Msg["ARD_ARRAY_GETINDEX_AT"] = "get element with index"; // untranslated
Blockly.Msg["ARD_ARRAY_GETINDEX_ITEM"] = "in array"; // untranslated
Blockly.Msg["ARD_ARRAY_GETINDEX_TOOLTIP"] = "Obtain element in the array at given index. Index must be a number from 0 to the length minus 1!"; // untranslated
Blockly.Msg["ARD_ARRAY_GETLENGTH"] = "Length of array"; // untranslated
Blockly.Msg["ARD_ARRAY_GETLENGTH_TOOLTIP"] = "Return the length (=number of elements) of the selected array"; // untranslated
Blockly.Msg["ARD_ARRAY_IND_ERR1"] = "Index must be number >= 0"; // untranslated
Blockly.Msg["ARD_ARRAY_IND_ERR2"] = "Index must be number < length array"; // untranslated
Blockly.Msg["ARD_ARRAY_LEN_ERR1"] = "Length of array must be 1 or more"; // untranslated
Blockly.Msg["ARD_ARRAY_LEN_ERR2"] = "Length of array must be an integer number"; // untranslated
Blockly.Msg["ARD_ARRAY_LEN_ERR3"] = "Length of array must be a number, not a variable"; // untranslated
Blockly.Msg["ARD_ARRAY_NOT_FLOAT"] = "One of the values is not a numeric value"; // untranslated
Blockly.Msg["ARD_ARRAY_NOT_INT"] = "One of the values is not an integer"; // untranslated
Blockly.Msg["ARD_ARRAY_NOT_KNOWN"] = "Unknown type of array given"; // untranslated
Blockly.Msg["ARD_ARRAY_NOT_NUMBER"] = "Only assign numbers, not variables when defining an array!"; // untranslated
Blockly.Msg["ARD_ARRAY_SETINDEX_AT"] = "the element with index"; // untranslated
Blockly.Msg["ARD_ARRAY_SETINDEX_ITEM"] = "Set in array"; // untranslated
Blockly.Msg["ARD_ARRAY_SETINDEX_TOOLTIP"] = "Set an element in the array at given index equal to the given value. Index must be a number from 0 to the length minus 1!"; // untranslated
Blockly.Msg["ARD_ARRAY_SETINDEX_VALUE"] = "to the value"; // untranslated
Blockly.Msg["ARD_AS_ANAINPUT_PIN"] = "as analog input"; // untranslated
Blockly.Msg["ARD_AS_ANAINPUT_PIN_TIP"] = "Declare a variable as a analog input pin"; // untranslated
Blockly.Msg["ARD_AS_ANAOUTPUT_PIN"] = "as analg output"; // untranslated
Blockly.Msg["ARD_AS_ANAOUTPUT_PIN_TIP"] = "Declare a variable as a analog PWM output pin"; // untranslated
Blockly.Msg["ARD_AS_BOOL_NUMBER"] = "as boolean"; // untranslated
Blockly.Msg["ARD_AS_BOOL_NUMBER_TIP"] = "Declare a variable as boolean with value true or false"; // untranslated
Blockly.Msg["ARD_AS_DIGINPUT_PIN"] = "as digital input"; // untranslated
Blockly.Msg["ARD_AS_DIGINPUT_PIN_TIP"] = "Declare a variable as a digital input pin"; // untranslated
Blockly.Msg["ARD_AS_DIGOUTPUT_PIN"] = "as digital output"; // untranslated
Blockly.Msg["ARD_AS_DIGOUTPUT_PIN_TIP"] = "Declare a variable as a digital output pin"; // untranslated
Blockly.Msg["ARD_AS_FLOAT_NUMBER"] = "as decimal number"; // untranslated
Blockly.Msg["ARD_AS_FLOAT_NUMBER_TIP"] = "Declare a variable as a decimal number, eg 3.6 or 5e4 or -3.14"; // untranslated
Blockly.Msg["ARD_AS_INTEGER_NUMBER"] = "as integer number"; // untranslated
Blockly.Msg["ARD_AS_INTEGER_NUMBER_TIP"] = "Declare a variable as integer, -32768 to 32767"; // untranslated
Blockly.Msg["ARD_AS_LONG_NUMBER"] = "as long integer number"; // untranslated
Blockly.Msg["ARD_AS_LONG_NUMBER_TIP"] = "Declare a variable as a long integer, -2,147,483,648 to 2,147,483,647"; // untranslated
Blockly.Msg["ARD_AS_UINT_NUMBER"] = "as positive integer number"; // untranslated
Blockly.Msg["ARD_AS_UINT_NUMBER_TIP"] = "Declare a variable as a positive integer, 0 to 65535"; // untranslated
Blockly.Msg["ARD_AS_ULONG_NUMBER"] = "as long positive integer number"; // untranslated
Blockly.Msg["ARD_AS_ULONG_NUMBER_TIP"] = "Declare a variable as a long positive integer, 0 to 4,294,967,295"; // untranslated
Blockly.Msg["ARD_BLOCKS"] = "You have this block twice on the canvas. That is once too many!"; // untranslated
Blockly.Msg["ARD_BOARD"] = "Board"; // untranslated
Blockly.Msg["ARD_BOARD_WARN"] = "This block requires as board %1, but or a duplicate block is present or another block is present that requires another Arduino board!"; // untranslated
Blockly.Msg["ARD_BTHUB_READCODE"] = "BlueTooth Code received from"; // untranslated
Blockly.Msg["ARD_BTHUB_TIP"] = "Block which indicates that to these two Arduino pins a BlueTooth type sensor is attached"; // untranslated
Blockly.Msg["ARD_BT_COLOUR_TOOLTIP"] = "is this a colour in the format xxx.xxx.xxx"; // untranslated
Blockly.Msg["ARD_BT_COMPONENT"] = "BlueTooth sensor"; // untranslated
Blockly.Msg["ARD_BT_DEFAULT_NAME"] = "BT_Sensor"; // untranslated
Blockly.Msg["ARD_BT_EFFECT1"] = "is effect 1"; // untranslated
Blockly.Msg["ARD_BT_EFFECT2"] = "is effect 2"; // untranslated
Blockly.Msg["ARD_BT_EFFECT3"] = "is effect 3"; // untranslated
Blockly.Msg["ARD_BT_EFFECT4"] = "is effect 4"; // untranslated
Blockly.Msg["ARD_BT_EFFECT5"] = "is effect 5"; // untranslated
Blockly.Msg["ARD_BT_EFFECT6"] = "is effect 6"; // untranslated
Blockly.Msg["ARD_BT_EFFECT7"] = "is effect 7"; // untranslated
Blockly.Msg["ARD_BT_EFFECT8"] = "is effect 8"; // untranslated
Blockly.Msg["ARD_BT_EFFECT_TOOLTIP"] = "test if the code %1 is an effect"; // untranslated
Blockly.Msg["ARD_BT_READCODEAPP_TIP"] = "Read the code send by the app and received by the BlueTooth sensor"; // untranslated
Blockly.Msg["ARD_BT_READCODEFROM"] = "Read the code from"; // untranslated
Blockly.Msg["ARD_BT_READCODE_TIP"] = "Read the code received by the BlueTooth sensor"; // untranslated
Blockly.Msg["ARD_BT_TEXT_ISBRIGHTNESS_TITLE"] = "%1 is brightness"; // untranslated
Blockly.Msg["ARD_BT_TEXT_ISBRIGHTNESS_TOOLTIP"] = "is this a brightness value (0-->100)"; // untranslated
Blockly.Msg["ARD_BT_TEXT_ISCOLOUR_TITLE"] = "%1 is a colour"; // untranslated
Blockly.Msg["ARD_BT_TEXT_ISCOLOUR_TOOLTIP"] = "is %1 a colourcode"; // untranslated
Blockly.Msg["ARD_BUILTIN_LED"] = "Configurer la DEL";
Blockly.Msg["ARD_BUILTIN_LED_TIP"] = "Allumer ou éteindre la DEL de la carte";
Blockly.Msg["ARD_BUTTON_COMPONENT"] = "Push Button"; // untranslated
Blockly.Msg["ARD_BUTTON_DEFAULT_NAME"] = "PushButton1"; // untranslated
Blockly.Msg["ARD_BUTTON_IFPUSHED"] = "If pushed we measure value"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_CLICK"] = " is clicked"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_IF"] = "If button"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_LONGCLICK"] = "is undergoing a long click"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_PRESSED"] = "is being pressed"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_PULLUP_COMPONENT"] = "Pushbutton 2-wire no resistor"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_PULLUP_TIP"] = "A push button which can be ON or OFF, connected to the Arduino with 2 wires: GND, and a digital pin"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_THEN"] = "do"; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_TIP"] = "Check the input received on a button, and react to it. This function does not block your program if you do not check the checkbox to wait for a click. A click is a press and a release of the button, a long press a click and holding long time before you release, press is active as soon as the button is pressed down."; // untranslated
Blockly.Msg["ARD_BUTTON_INPUT_WAIT"] = "wait for a click to happen"; // untranslated
Blockly.Msg["ARD_BUTTON_READ"] = "Read value button"; // untranslated
Blockly.Msg["ARD_BUTTON_TIP"] = "A push button which can be ON or OFF, connected to the Arduino with 3 wires: GND, 5V over resisotor, and a digital pin"; // untranslated
Blockly.Msg["ARD_BUZNOTONE"] = "No tone on buzzer"; // untranslated
Blockly.Msg["ARD_BUZNOTONE_TIP"] = "Stop generating a tone on the buzzer"; // untranslated
Blockly.Msg["ARD_BUZOUTPUT_COMPONENT"] = "Buzzer/Speaker"; // untranslated
Blockly.Msg["ARD_BUZOUTPUT_DEFAULT_NAME"] = "MyBuzzer1"; // untranslated
Blockly.Msg["ARD_BUZOUTPUT_TIP"] = "This component is a Buzzer or a Loudspeaker. You can connect it to a digital pin of the Arduino."; // untranslated
Blockly.Msg["ARD_BUZSELECTPITCH"] = "Pitch"; // untranslated
Blockly.Msg["ARD_BUZSELECTPITCH_TIP"] = "Select the pitch you want. This block returns a number which is the frequency of the selected pitch."; // untranslated
Blockly.Msg["ARD_BUZSETPITCH"] = "with pitch"; // untranslated
Blockly.Msg["ARD_BUZSETTONE"] = "Set tone on buzzer"; // untranslated
Blockly.Msg["ARD_BUZZEROUTPUT"] = "Buzzer/Speaker"; // untranslated
Blockly.Msg["ARD_COMMENT"] = "Comment"; // untranslated
Blockly.Msg["ARD_COMMENT_TIP"] = "Add the given text as comment to the Arduino code"; // untranslated
Blockly.Msg["ARD_COMPONENT_BOARD"] = "a specific Arduino Board"; // untranslated
Blockly.Msg["ARD_COMPONENT_BOARD_HUB_TIP"] = "Set the Arduino board you work with, and to what it connects"; // untranslated
Blockly.Msg["ARD_COMPONENT_BOARD_TIP"] = "Set which Arduino board you work with, and connect components to the pins."; // untranslated
Blockly.Msg["ARD_COMPONENT_WARN1"] = "A %1 configuration block with the same %2 name must be added to use this block!"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_ELSEIF_TOOLTIP"] = "Add an extra effect time at which statements must be done"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_ELSE_TOOLTIP"] = "Add a block for statements when the effect is finished."; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_ELSE"] = "at the end do"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_ELSEIF"] = "if effect time becomes greater than"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_FIRST1"] = "Effect"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_FIRST2"] = "with total duration (ms) ="; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_IF"] = "at the start do"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_TOOLTIP_1"] = "At the start of an effect, do some statements"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_TOOLTIP_2"] = "At the start of an effect, do some statements, and at the end of the effect too"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_TOOLTIP_3"] = "At the start of an effect, do some statements, if the effect time becomes larger than the given time, do the next statements."; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_TOOLTIP_4"] = "At the start of an effect, do some statements, if the effect time becomes larger than the given time, do the next statements. Ath end of the effect the final statements are done."; // untranslated
Blockly.Msg["ARD_DEFINE"] = "Définir";
Blockly.Msg["ARD_DHTHUB"] = "Temperature and humidity sensor"; // untranslated
Blockly.Msg["ARD_DHTHUB_READHEATINDEX"] = "Heat Index at"; // untranslated
Blockly.Msg["ARD_DHTHUB_READRH"] = "Relative Humidity at"; // untranslated
Blockly.Msg["ARD_DHTHUB_READTEMP"] = "°C temperature at"; // untranslated
Blockly.Msg["ARD_DHTHUB_TIP"] = "Block to assign to an Arduino pin a DHT type sensor"; // untranslated
Blockly.Msg["ARD_DHT_COMPONENT"] = "DHT sensor"; // untranslated
Blockly.Msg["ARD_DHT_DEFAULT_NAME"] = "TempRH_Sensor"; // untranslated
Blockly.Msg["ARD_DHT_READHEATINDEX_TIP"] = "Obtain the Heat Index ( human-perceived equivalent temperature in °C) of a DHT sensor"; // untranslated
Blockly.Msg["ARD_DHT_READRH_TIP"] = "Obtain the RH (Relative Humidity in %) as a value from 0 to 100 a DHT sensor"; // untranslated
Blockly.Msg["ARD_DHT_READTEMP_TIP"] = "Obtain the temperature in degree Celcius of a DHT sensor"; // untranslated
Blockly.Msg["ARD_DIGINPUT"] = "Digital input"; // untranslated
Blockly.Msg["ARD_DIGINPUT_COMPONENT"] = "Digital Input"; // untranslated
Blockly.Msg["ARD_DIGINPUT_DEFAULT_NAME"] = "DigInput1"; // untranslated
Blockly.Msg["ARD_DIGINPUT_READ"] = "Read digital input"; // untranslated
Blockly.Msg["ARD_DIGINPUT_TIP"] = "Connect a digital input to a digital pin, so as to read its value. The digital state can then be read, corresponding to 0V or 5V on the pin for an Arduino UNO."; // untranslated
Blockly.Msg["ARD_DIGITALREAD"] = "Lecture du signal numérique #";
Blockly.Msg["ARD_DIGITALREAD_TIP"] = "Lecture de la valeur d'un signal numérique: HAUT ou BAS";
Blockly.Msg["ARD_DIGITALWRITE"] = "Configuration du signal numérique #";
Blockly.Msg["ARD_DIGITALWRITEVAR_TIP"] = "Write digital value to a Port, the value and port can be computed variables"; // untranslated
Blockly.Msg["ARD_DIGITALWRITE_TIP"] = " Ecriture de la valeur HAUT ou BAS du signal numérique #";
Blockly.Msg["ARD_DIGOUTPUT"] = "Digital output"; // untranslated
Blockly.Msg["ARD_DIGOUTPUT_COMPONENT"] = "Digital Output"; // untranslated
Blockly.Msg["ARD_DIGOUTPUT_DEFAULT_NAME"] = "DigOutput1"; // untranslated
Blockly.Msg["ARD_DIGOUTPUT_TIP"] = "Connect a generic digital ouput to a digital pin, so as to write to that pin. The digital state can be set to LOW or HIGH, corresponding to 0V and 5V on the pin for an Arduino UNO."; // untranslated
Blockly.Msg["ARD_DIGOUTPUT_WRITE"] = "Write to digital output"; // untranslated
Blockly.Msg["ARD_DIORAMA_BOARD_TIP"] = "The Ingegno Diorama board - See manual for info"; // untranslated
Blockly.Msg["ARD_DIORAMA_BTN_TIP"] = "Diorama button code, executed in a loop once the button has been pressed"; // untranslated
Blockly.Msg["ARD_DIO_BOARD_MISSING"] = "No Diorama board present. Add it to the canvas!"; // untranslated
Blockly.Msg["ARD_DIO_DISPLAYTEXT"] = "Show on display: "; // untranslated
Blockly.Msg["ARD_DIO_DISPLAYTEXT_TIP"] = "Give a text of 8 characters to show on the diorama display"; // untranslated
Blockly.Msg["ARD_DIO_DISPLAYTEXT_WARNING"] = "Text can only be 8 long, not longer!"; // untranslated
Blockly.Msg["ARD_DIO_LESSLOUD"] = "Diorama: less loud output"; // untranslated
Blockly.Msg["ARD_DIO_LOUDER"] = "Diorama: louder output"; // untranslated
Blockly.Msg["ARD_DIO_PLAYTRACK"] = "Play track number "; // untranslated
Blockly.Msg["ARD_DIO_RESETBTN"] = "stop buttons"; // untranslated
Blockly.Msg["ARD_DIO_RESETBTNNR_TIP"] = "Stop action of the given button."; // untranslated
Blockly.Msg["ARD_DIO_RESETBTN_TIP"] = "Reset the buttons, so no button is considered pressed."; // untranslated
Blockly.Msg["ARD_DIO_SETLOUDNESS"] = "Diorama: set volume to (0-10):"; // untranslated
Blockly.Msg["ARD_DIO_SOUND_TIP"] = "Change sound output of the Diorama board. If louder or quieter, we stop processing the button after the call."; // untranslated
Blockly.Msg["ARD_DIO_SOUND_WARNING"] = "Volume must be between 0 and 10!"; // untranslated
Blockly.Msg["ARD_DIO_STOPBTN"] = "Pushbutton 8: stop"; // untranslated
Blockly.Msg["ARD_DIO_STOPTRACK"] = "Stop playing"; // untranslated
Blockly.Msg["ARD_DIO_STOPTRACK_TIP"] = "Immediately stop playing the track that is playing"; // untranslated
Blockly.Msg["ARD_DIO_TRACKPLAYING"] = "track is playing"; // untranslated
Blockly.Msg["ARD_DIO_TRACKPLAYING_TIP"] = "Return true if a track is still playing, false otherwise"; // untranslated
Blockly.Msg["ARD_DIO_TRACK_TIP"] = "If number 1, then play a track stored on SD card as track001.mp3'"; // untranslated
Blockly.Msg["ARD_DIO_TRACK_WARNING"] = "Track must be a number between 1 and 100!"; // untranslated
Blockly.Msg["ARD_FUN_RUN_DECL"] = "Arduino define up front:"; // untranslated
Blockly.Msg["ARD_FUN_RUN_DECL_TIP"] = "Code you want to declare up front (use this e.g. for variables you need in setup)"; // untranslated
Blockly.Msg["ARD_FUN_RUN_LOOP"] = "Arduino boucle infinie:";
Blockly.Msg["ARD_FUN_RUN_SETUP"] = "Arduino exécute en premier:";
Blockly.Msg["ARD_FUN_RUN_TIP"] = "Definition de la configuration de l'Arduino: fonctions setup() et loop().";
Blockly.Msg["ARD_HIGH"] = "HAUT";
Blockly.Msg["ARD_HIGHLOW_TIP"] = " Configuration d'un signal à l'état HAUT ou BAS";
Blockly.Msg["ARD_IRHUB"] = "IR sensor"; // untranslated
Blockly.Msg["ARD_IRHUB_READCODE"] = "IR Code at"; // untranslated
Blockly.Msg["ARD_IRHUB_TIP"] = "Block wich indicates an IR sensor is attached at this pin"; // untranslated
Blockly.Msg["ARD_IR_COMPONENT"] = "IR sensor"; // untranslated
Blockly.Msg["ARD_IR_DEFAULT_NAME"] = "IR_Receiver"; // untranslated
Blockly.Msg["ARD_IR_READCODE_TIP"] = "Read the code received by the IR sensor"; // untranslated
Blockly.Msg["ARD_LEDLEG"] = "LED"; // untranslated
Blockly.Msg["ARD_LEDLEGNEG"] = "minus"; // untranslated
Blockly.Msg["ARD_LEDLEGPOL"] = "leg polarity"; // untranslated
Blockly.Msg["ARD_LEDLEGPOS"] = "plus"; // untranslated
Blockly.Msg["ARD_LEDLEG_COMPONENT"] = "LED"; // untranslated
Blockly.Msg["ARD_LEDLEG_DEFAULT_NAME"] = "Led1"; // untranslated
Blockly.Msg["ARD_LEDLEG_OFF"] = "OFF"; // untranslated
Blockly.Msg["ARD_LEDLEG_ON"] = "ON"; // untranslated
Blockly.Msg["ARD_LEDLEG_SET"] = "Set LED"; // untranslated
Blockly.Msg["ARD_LEDLEG_TIP"] = "A LED light, on of the legs (the positive or negative) is connected to the Arduino. Can be ON or OFF."; // untranslated
Blockly.Msg["ARD_LEDUP_GADGET"] = "Gadget LedUpKidz"; // untranslated
Blockly.Msg["ARD_LEDUP_HUB"] = "LedUpKidz, destination: "; // untranslated
Blockly.Msg["ARD_LEDUP_HUB_TIP"] = "LedUpKidz is a gadget with 6 LED that you can program. There is a big prototype connected to an Arduino UNO, choose 'prototype' for code destined for this. The gadget itself works on a small attiny85 microchip, for code with that destination, select destination 'gadget'"; // untranslated
Blockly.Msg["ARD_LEDUP_LED0"] = "LED 0"; // untranslated
Blockly.Msg["ARD_LEDUP_LED1"] = "LED 1"; // untranslated
Blockly.Msg["ARD_LEDUP_LED2"] = "LED 2"; // untranslated
Blockly.Msg["ARD_LEDUP_LED3"] = "LED 3"; // untranslated
Blockly.Msg["ARD_LEDUP_LED4"] = "LED 4"; // untranslated
Blockly.Msg["ARD_LEDUP_LED5"] = "LED 5"; // untranslated
Blockly.Msg["ARD_LEDUP_LED_ONOFF1"] = "Put LedUp LED"; // untranslated
Blockly.Msg["ARD_LEDUP_LED_ONOFF2"] = "on? True/False:"; // untranslated
Blockly.Msg["ARD_LEDUP_LED_ONOFF_TIP"] = "Set a given LedUpKidz light to on or off using variable blocks"; // untranslated
Blockly.Msg["ARD_LEDUP_PROTO"] = "Prototype Arduino UNO"; // untranslated
Blockly.Msg["ARD_LOW"] = "BAS";
Blockly.Msg["ARD_MAP"] = "Converti";
Blockly.Msg["ARD_MAP_TIP"] = "Converti un nombre de la plage [0-1024].";
Blockly.Msg["ARD_MAP_VAL"] = "valeur de [0-";
Blockly.Msg["ARD_MD_180SERVO"] = "0~180 degree Servo"; // untranslated
Blockly.Msg["ARD_MD_360SERVO"] = "0~360 degree Servo"; // untranslated
Blockly.Msg["ARD_MD_AAABLOCK"] = "AAA 3V Battery module"; // untranslated
Blockly.Msg["ARD_MD_AAABLOCK_TIP"] = "The battery block for Microduino"; // untranslated
Blockly.Msg["ARD_MD_AAASOUNDWARN"] = "A AAA Battery module must be added to your blocks if you work with sound"; // untranslated
Blockly.Msg["ARD_MD_AMPBLOCK"] = "Loudspeaker (Amplifier) Module"; // untranslated
Blockly.Msg["ARD_MD_AMPBLOCK_TIP"] = "Amplifier module, connect the loudspeaker to it to hear sound."; // untranslated
Blockly.Msg["ARD_MD_AMPWARN"] = "An Amplifier module must be added to your blocks"; // untranslated
Blockly.Msg["ARD_MD_AUDIOAMPWARN"] = "An Audio module must be added to your blocks if you work with an amplifier"; // untranslated
Blockly.Msg["ARD_MD_AUDIOBLOCK"] = "Sound modules (Audio). Mode:"; // untranslated
Blockly.Msg["ARD_MD_AUDIOBLOCK_TIP"] = "Audio Function Module, Choose a mode and a volume"; // untranslated
Blockly.Msg["ARD_MD_AUDIOSOUNDWARN"] = "An Audio module must be added to your blocks to be able to work with music."; // untranslated
Blockly.Msg["ARD_MD_AUDIO_PAUSE"] = "Pause sound fragment"; // untranslated
Blockly.Msg["ARD_MD_AUDIO_PAUSE_TIP"] = "Pause the sound fragment that is playing"; // untranslated
Blockly.Msg["ARD_MD_AUDIO_PLAY"] = ""; // untranslated
Blockly.Msg["ARD_MD_AUDIO_PLAYNR"] = "Play sound fragment"; // untranslated
Blockly.Msg["ARD_MD_AUDIO_PLAY_TIP"] = "Write the number of the sound fragment you want to play. On the this number corresponds to the order in which files have been copied to the SD Card. Best: 1/Empty the SD card 2/copy files to SD card in the order you want to play them 3/it is easier if you name the files 001.mp3, 002.mp3, ... and copy them one after the other to the card!"; // untranslated
Blockly.Msg["ARD_MD_AUDIO_REP1"] = "Repeat everything"; // untranslated
Blockly.Msg["ARD_MD_AUDIO_REP2"] = "Play everything 1 time"; // untranslated
Blockly.Msg["ARD_MD_AUDIO_REP3"] = "Repeat 1 track"; // untranslated
Blockly.Msg["ARD_MD_AUDIO_REP4"] = "Play 1 track"; // untranslated
Blockly.Msg["ARD_MD_BLOCKS"] = "Microduino blocks: "; // untranslated
Blockly.Msg["ARD_MD_COOKIEBUTTON_COMPONENT"] = "Microduino MCookie CoreUSB"; // untranslated
Blockly.Msg["ARD_MD_COREBLOCK"] = "Brain (CoreUSB)"; // untranslated
Blockly.Msg["ARD_MD_COREBLOCK_TIP"] = "The Brain of your construction, the MCookie-CoreUSB"; // untranslated
Blockly.Msg["ARD_MD_COREWARN"] = "A Brain (CoreUSB) module must be added to your blocks"; // untranslated
Blockly.Msg["ARD_MD_CRASHBUTTON_COMPONENT"] = "Microduino Crash Button"; // untranslated
Blockly.Msg["ARD_MD_CRASHBUTTON_DEFAULT_NAME"] = "Crashbutton1"; // untranslated
Blockly.Msg["ARD_MD_CRASHBUTTON_TIP"] = "The microduino crash-button with which you can detect if you hit something, or that you can use as a push button."; // untranslated
Blockly.Msg["ARD_MD_HUBBLOCK"] = "The Cable holder (Sensor Hub)"; // untranslated
Blockly.Msg["ARD_MD_HUBBLOCK01"] = "connected to pins: IIC"; // untranslated
Blockly.Msg["ARD_MD_HUBBLOCK_TIP"] = "The Hub allows to connect up to 12 sensors to your Microduino"; // untranslated
Blockly.Msg["ARD_MD_NOSERVO"] = "Geen Servo gekoppeld"; // untranslated
Blockly.Msg["ARD_MD_SERVOBOT_DEFAULT_NAME"] = "BottomServo1"; // untranslated
Blockly.Msg["ARD_MD_SERVOCON"] = "Servo Motor Connector."; // untranslated
Blockly.Msg["ARD_MD_SERVOCON_BOTTOM"] = "Define bottom Servo"; // untranslated
Blockly.Msg["ARD_MD_SERVOCON_TIP"] = "Servo Motor Connector, can control two Servo (top and bottom). You have to give the servo a name, and what type it is (no servo attached, a 180 degree servo or a 360 degree servo."; // untranslated
Blockly.Msg["ARD_MD_SERVOCON_TOP"] = "Define top Servo"; // untranslated
Blockly.Msg["ARD_MD_SERVOCON_TYPE"] = "Type:"; // untranslated
Blockly.Msg["ARD_MD_SERVOTOP_DEFAULT_NAME"] = "TopServo1"; // untranslated
Blockly.Msg["ARD_MD_SERVOTYPE_TIP"] = "Select the type of Servo you attach to the Servo connnector"; // untranslated
Blockly.Msg["ARD_MD_SERVO_READ"] = "read Servo "; // untranslated
Blockly.Msg["ARD_MD_SERVO_STEP_WARN1"] = "A Servo configuration block must be added to the hub to use this block!"; // untranslated
Blockly.Msg["ARD_MD_SERVO_STEP_WARN2"] = "A Name input must be added to the Servo configuration block!"; // untranslated
Blockly.Msg["ARD_MD_SERVO_STEP_WARN3"] = "Selected servo does not exist any more, please select a new one."; // untranslated
Blockly.Msg["ARD_MD_SERVO_WRITE"] = "set 180 degree Servo "; // untranslated
Blockly.Msg["ARD_NEOPIXEL"] = "NeoPixel LED light"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_BRIGHTNESS"] = " brightness (%)"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_BRIGHTNESS_RANGE"] = "value(brightness) (0 --> 255)"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_CLEAR"] = "Clear"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_COMPONENT"] = "Neopixel strip"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_COUNT_PIXELS"] = "Number of pixels"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_COUNT_PIXELS_TIP"] = "Returns the number of pixels of this LED strip"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_DEFAULT_NAME"] = "NeoPixel1"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_DIRECT"] = "direct"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_COLORWIPE"] = "Colorwipe"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_METEOOR"] = "Meteor"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_RAINBOW"] = "Rainbow"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_SCANNER"] = "Scanner"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_SNAKE"] = "Snake"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_SNOW"] = "Snow"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_STROBE"] = "Strobe"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_THEATERCHASE"] = "Theater chase"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_EFF_THEATERCHASERAINBOW"] = "Theater chase rainbow"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_FADE"] = "fade"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_HUE_RANGE"] = "with hue (0 --> 65535)"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_HZ"] = "Frequency:"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_NUMBER"] = "number"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_ONCOLOUR"] = "on colour"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_ONCOLOURVALBLUE"] = "blue:"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_ONCOLOURVALGREEN"] = "green:"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_ONCOLOURVALRED"] = "on colour (0-255) red:"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_ONHSVCOLOUR"] = "on HSVcolour"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_PAUSE"] = "pause"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_PIXEL"] = "pixel"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_PIXELS"] = "Pixels."; // untranslated
Blockly.Msg["ARD_NEOPIXEL_SAT_RANGE"] = "saturation (0 --> 255)"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_SET"] = "Set Neopixel"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_STRIP"] = "Strip with"; // untranslated
Blockly.Msg["ARD_NEOPIXEL_TIP"] = "A NEOPIXEL LED light or a strip with multiple neopixels."; // untranslated
Blockly.Msg["ARD_NEOPIXEL_TYPE"] = "Type:"; // untranslated
Blockly.Msg["ARD_NOTONE"] = "Eteindre la tonalité du signal #";
Blockly.Msg["ARD_NOTONE_PIN"] = "PAS de Signal de tonalité #";
Blockly.Msg["ARD_NOTONE_PIN_TIP"] = "Arret de la génération de tonalité (son)sur un signal";
Blockly.Msg["ARD_NOTONE_TIP"] = "Eteindre / Activer la tonalité du signal selectioné";
Blockly.Msg["ARD_NO_ALLBOT"] = "No AllBot present"; // untranslated
Blockly.Msg["ARD_OLED"] = "OLED"; // untranslated
Blockly.Msg["ARD_OLED_CLEAR"] = "clear display"; // untranslated
Blockly.Msg["ARD_OLED_CLEAR_TIP"] = "Before writing new text to the display, use this block to clear it first."; // untranslated
Blockly.Msg["ARD_OLED_CONFIG_TIP"] = "Define a display of the given resolution to use to write text to"; // untranslated
Blockly.Msg["ARD_OLED_CURSORX"] = "set cursor position X"; // untranslated
Blockly.Msg["ARD_OLED_CURSORY"] = "Y"; // untranslated
Blockly.Msg["ARD_OLED_DEFAULT_NAME"] = "OLED1"; // untranslated
Blockly.Msg["ARD_OLED_FONT_SIZE"] = "choose font size"; // untranslated
Blockly.Msg["ARD_OLED_FONT_TIP"] = "Select the font size to use to write text from now on"; // untranslated
Blockly.Msg["ARD_OLED_INIT"] = "OLED Initialise"; // untranslated
Blockly.Msg["ARD_OLED_PRINT"] = "print"; // untranslated
Blockly.Msg["ARD_OLED_PRINT_NUMBER"] = "print number"; // untranslated
Blockly.Msg["ARD_OLED_PRINT_NUMBER_DIGITS"] = "with #digits:"; // untranslated
Blockly.Msg["ARD_OLED_PRINT_TIP"] = "Prepare to show the given text on the display in the given size. You need to use the write block to actually see it!"; // untranslated
Blockly.Msg["ARD_OLED_RESOLUTIE"] = "with resolution"; // untranslated
Blockly.Msg["ARD_OLED_WRITE"] = "write to display"; // untranslated
Blockly.Msg["ARD_OLED_WRITE_TIP"] = "After you have printed text on the display, use this block to actually show the text."; // untranslated
Blockly.Msg["ARD_OUTPUT_WRITE_TO"] = "value"; // untranslated
Blockly.Msg["ARD_PIN_AN"] = "analog pin"; // untranslated
Blockly.Msg["ARD_PIN_AN_TIP"] = "One of the analog pins of the Arduino Board"; // untranslated
Blockly.Msg["ARD_PIN_DIG"] = "digital pin"; // untranslated
Blockly.Msg["ARD_PIN_DIGDIG"] = "digital pin1 and pin2"; // untranslated
Blockly.Msg["ARD_PIN_DIGDIG1"] = "digital pin1#"; // untranslated
Blockly.Msg["ARD_PIN_DIGDIG2"] = "pin2#"; // untranslated
Blockly.Msg["ARD_PIN_DIGDIG_TIP"] = "Component requiring two digital pins, pin1 and pin2"; // untranslated
Blockly.Msg["ARD_PIN_DIG_TIP"] = "One of the digital pins of the Arduino Board"; // untranslated
Blockly.Msg["ARD_PIN_PWM"] = "PWM pin"; // untranslated
Blockly.Msg["ARD_PIN_PWM_TIP"] = "One of the Pulse Width Modeling (PWM) pins of the Arduino Board"; // untranslated
Blockly.Msg["ARD_PIN_WARN1"] = "Signal %1 est utilisé pour %2 alors que signal %3. Déjà utilisé en tant que %4.";
Blockly.Msg["ARD_PULSEON"] = "pulse on pin #"; // untranslated
Blockly.Msg["ARD_PULSEREAD"] = "Read"; // untranslated
Blockly.Msg["ARD_PULSETIMEOUT"] = "timeout after"; // untranslated
Blockly.Msg["ARD_PULSETIMEOUT_MS"] = ""; // untranslated
Blockly.Msg["ARD_PULSETIMEOUT_TIP"] = "Mesure la durée d'une pulsation sur le signal selectioné, dans le delai imparti";
Blockly.Msg["ARD_PULSE_READ"] = "mesure %1 impulsion sur le signal #%2";
Blockly.Msg["ARD_PULSE_READ_TIMEOUT"] = "mesure %1 impulsion sur le signal #%2 (délai de retard %3 μs)";
Blockly.Msg["ARD_PULSE_TIP"] = "Mesure la durée d'une pulsation sur le signal selectioné.";
Blockly.Msg["ARD_PWMOUTPUT"] = "PWM output"; // untranslated
Blockly.Msg["ARD_PWMOUTPUT_COMPONENT"] = "PWM Output"; // untranslated
Blockly.Msg["ARD_PWMOUTPUT_DEFAULT_NAME"] = "PWMOutput1"; // untranslated
Blockly.Msg["ARD_PWMOUTPUT_TIP"] = "Connect a generic PWM (Pulse Width Modulation) ouput to a pwm pin, so as to write an analog value to that pin. The value written should be a number between 0 and 255, and will generate a block pulse over this pin."; // untranslated
Blockly.Msg["ARD_PWMOUTPUT_WRITE"] = "Write to PWM output"; // untranslated
Blockly.Msg["ARD_SERIAL_BPS"] = "bps";
Blockly.Msg["ARD_SERIAL_PRINT"] = "imprimer";
Blockly.Msg["ARD_SERIAL_PRINT_NEWLINE"] = "ajouter une nouvelle ligne";
Blockly.Msg["ARD_SERIAL_PRINT_TIP"] = "Imprime les données sur la console série en texte lisible ASCII.";
Blockly.Msg["ARD_SERIAL_PRINT_WARN"] = "Un bloc de configuration pour %1 doit être ajouté à l'espace de travail afin d'utiliser ce bloc!";
Blockly.Msg["ARD_SERIAL_SETUP"] = "Configuration";
Blockly.Msg["ARD_SERIAL_SETUP_TIP"] = "Choisir la vitesse d'un périphérique série";
Blockly.Msg["ARD_SERIAL_SPEED"] = ": vitesse";
Blockly.Msg["ARD_SERVOHUB"] = "Servo motor"; // untranslated
Blockly.Msg["ARD_SERVOHUB_READ"] = "read Servo "; // untranslated
Blockly.Msg["ARD_SERVOHUB_TIP"] = "Servo Motor Connection, which can attach to a PWM pin. You have to give the servo a name, and what type it is (a 180 degree servo or a 360 degree servo.)"; // untranslated
Blockly.Msg["ARD_SERVOHUB_WRITE"] = "set 180 degree Servo "; // untranslated
Blockly.Msg["ARD_SERVO_COMPONENT"] = "servo"; // untranslated
Blockly.Msg["ARD_SERVO_DEFAULT_NAME"] = "Servo1"; // untranslated
Blockly.Msg["ARD_SERVO_READ"] = "Lecture du signal# du SERVO";
Blockly.Msg["ARD_SERVO_READ_TIP"] = "Lecture d'un angle du SERVO";
Blockly.Msg["ARD_SERVO_ROTATE360"] = "Rotate 360 degree Servo"; // untranslated
Blockly.Msg["ARD_SERVO_ROTATEPERC"] = "% (-100 to 100)"; // untranslated
Blockly.Msg["ARD_SERVO_ROTATESPEED"] = "with speed"; // untranslated
Blockly.Msg["ARD_SERVO_ROTATE_TIP"] = "Turn a Servo with a specific speed"; // untranslated
Blockly.Msg["ARD_SERVO_TYPE"] = "Type:"; // untranslated
Blockly.Msg["ARD_SERVO_WRITE"] = "Configurer SERVO sur Patte";
Blockly.Msg["ARD_SERVO_WRITE_DEG_180"] = "Degrés (0~180)";
Blockly.Msg["ARD_SERVO_WRITE_TIP"] = "Configurer un SERVO à un angle donné";
Blockly.Msg["ARD_SERVO_WRITE_TO"] = "vers";
Blockly.Msg["ARD_SETTONE"] = "Définir une tonalité sur le signal #";
Blockly.Msg["ARD_SPI_SETUP"] = "Configuration";
Blockly.Msg["ARD_SPI_SETUP_CONF"] = "configuration:";
Blockly.Msg["ARD_SPI_SETUP_DIVIDE"] = "Division de fréquence";
Blockly.Msg["ARD_SPI_SETUP_LSBFIRST"] = "LSBFIRST";
Blockly.Msg["ARD_SPI_SETUP_MODE"] = "mode SPI (idle - edge)";
Blockly.Msg["ARD_SPI_SETUP_MODE0"] = "0 (Bas - Descendant)";
Blockly.Msg["ARD_SPI_SETUP_MODE1"] = "1 (Bas - Montant)";
Blockly.Msg["ARD_SPI_SETUP_MODE2"] = "2 (Haut - Descendant)";
Blockly.Msg["ARD_SPI_SETUP_MODE3"] = "3 (Haut - Montant)";
Blockly.Msg["ARD_SPI_SETUP_MSBFIRST"] = "MSBFIRST";
Blockly.Msg["ARD_SPI_SETUP_SHIFT"] = "décalage de données";
Blockly.Msg["ARD_SPI_SETUP_TIP"] = "Configuration du périphérique SPI.";
Blockly.Msg["ARD_SPI_TRANSRETURN_TIP"] = "Envoie d'un message SPI à un esclave précis et recuperation de la donnée.";
Blockly.Msg["ARD_SPI_TRANS_NONE"] = "vide";
Blockly.Msg["ARD_SPI_TRANS_SLAVE"] = "vers le signal esclave";
Blockly.Msg["ARD_SPI_TRANS_TIP"] = "Envoie d'un message SPI à un esclave précis.";
Blockly.Msg["ARD_SPI_TRANS_VAL"] = "transfert";
Blockly.Msg["ARD_SPI_TRANS_WARN1"] = "Un bloc de configuration pour %1 doit être ajouté à l'espace de travail afin d'utiliser ce bloc!";
Blockly.Msg["ARD_SPI_TRANS_WARN2"] = "L'ancienne valeur du signal %1 n'est plus disponible.";
Blockly.Msg["ARD_STEPPER_COMPONENT"] = "stepper"; // untranslated
Blockly.Msg["ARD_STEPPER_DEFAULT_NAME"] = "MyStepper"; // untranslated
Blockly.Msg["ARD_STEPPER_DEGREES"] = "degrees"; // untranslated
Blockly.Msg["ARD_STEPPER_FOUR_PINS"] = "4";
Blockly.Msg["ARD_STEPPER_ISROTATING"] = "in movement"; // untranslated
Blockly.Msg["ARD_STEPPER_ISROTATING_TIP"] = "Returns true if the stepper is moving."; // untranslated
Blockly.Msg["ARD_STEPPER_MOTOR"] = "Moteur pas-à-pas:";
Blockly.Msg["ARD_STEPPER_NUMBER_OF_PINS"] = "Number of pins"; // untranslated
Blockly.Msg["ARD_STEPPER_PIN1"] = "signal1 #";
Blockly.Msg["ARD_STEPPER_PIN2"] = "signal2 #";
Blockly.Msg["ARD_STEPPER_PIN3"] = "signal3 #";
Blockly.Msg["ARD_STEPPER_PIN4"] = "signal4 #";
Blockly.Msg["ARD_STEPPER_RESTART"] = "Get"; // untranslated
Blockly.Msg["ARD_STEPPER_RESTART_AFTER"] = "ready"; // untranslated
Blockly.Msg["ARD_STEPPER_RESTART_TIP"] = "Reset the motor ready after a rotation block has finished, so as to be able to rotate again"; // untranslated
Blockly.Msg["ARD_STEPPER_REVOLVS"] = "Combien de pas par tour";
Blockly.Msg["ARD_STEPPER_ROTATE"] = "Rotate"; // untranslated
Blockly.Msg["ARD_STEPPER_ROTATE_TIP"] = "Rotate the stepper motor over a number of degrees in a non-blocking way. This block must be called in the loop. When finished the stepper is blocked, and a call to restart movement is needed for the block to cause a next movement."; // untranslated
Blockly.Msg["ARD_STEPPER_SETUP"] = "Configuration";
Blockly.Msg["ARD_STEPPER_SETUP_TIP"] = "Configuration d'un moteur pas-à-pas: signaux et autres paramètres.";
Blockly.Msg["ARD_STEPPER_SPEED"] = "Configuration de la vitesse(rpm) à";
Blockly.Msg["ARD_STEPPER_SPEED_TIP"] = "Sets speed of the stepper motor. The steps are set at the speed needed to have the set RPM speed based on the given steps per revolution in the constructor."; // untranslated
Blockly.Msg["ARD_STEPPER_STEP"] = "Déplacement grace au moteur pas-à-pas";
Blockly.Msg["ARD_STEPPER_STEPS"] = "pas";
Blockly.Msg["ARD_STEPPER_STEP_TIP"] = "Configurer le moteur pas-à-pas avec un nombre précis de pas.";
Blockly.Msg["ARD_STEPPER_TWO_PINS"] = "2";
Blockly.Msg["ARD_TFT_BG_COLOUR"] = "Color of the background"; // untranslated
Blockly.Msg["ARD_TFT_BG_TIP"] = "Fill the entire screen with the given colour"; // untranslated
Blockly.Msg["ARD_TFT_CIRC_HEIGHT"] = "Height"; // untranslated
Blockly.Msg["ARD_TFT_CIRC_RADIUS"] = "Radius"; // untranslated
Blockly.Msg["ARD_TFT_CIRC_TIP"] = "Draw a circle on the screen with the given coordinates in the given colour. If Filled is checked the circle is filled, otherwise only an outline"; // untranslated
Blockly.Msg["ARD_TFT_CIRC_XPOS"] = "X Position Center"; // untranslated
Blockly.Msg["ARD_TFT_CIRC_YPOS"] = "Y Position Center"; // untranslated
Blockly.Msg["ARD_TFT_COMPONENT"] = "TFT-Scherm"; // untranslated
Blockly.Msg["ARD_TFT_COMPONENT_TIP"] = "The ST7735 1.8” Color TFT scherm. Scherm is 128x160 pixels."; // untranslated
Blockly.Msg["ARD_TFT_FILLED"] = "Fill the drawing"; // untranslated
Blockly.Msg["ARD_TFT_LINE_COLOUR"] = "Colour"; // untranslated
Blockly.Msg["ARD_TFT_LINE_TIP"] = "Draw a line on the screen with the given coordinates in the given colour."; // untranslated
Blockly.Msg["ARD_TFT_LINE_XPOSBEGIN"] = "X Position Start"; // untranslated
Blockly.Msg["ARD_TFT_LINE_XPOSEND"] = "X Position End"; // untranslated
Blockly.Msg["ARD_TFT_LINE_YPOSBEGIN"] = "Y Position Start"; // untranslated
Blockly.Msg["ARD_TFT_LINE_YPOSEND"] = "Y Position End"; // untranslated
Blockly.Msg["ARD_TFT_MAKE_CIRC"] = "Draw Circle"; // untranslated
Blockly.Msg["ARD_TFT_MAKE_LINE"] = "Draw Line"; // untranslated
Blockly.Msg["ARD_TFT_MAKE_RECT"] = "Draw Rectangle"; // untranslated
Blockly.Msg["ARD_TFT_RECT_COLOUR"] = "Colour"; // untranslated
Blockly.Msg["ARD_TFT_RECT_HEIGHT"] = "Height"; // untranslated
Blockly.Msg["ARD_TFT_RECT_TIP"] = "Draw a rectangle on the screen with the given coordinates in the given colour. If Filled is checked the rectangle is filled, otherwise only an outline"; // untranslated
Blockly.Msg["ARD_TFT_RECT_WIDTH"] = "Width"; // untranslated
Blockly.Msg["ARD_TFT_RECT_XPOSBEGIN"] = "X Position Top Left"; // untranslated
Blockly.Msg["ARD_TFT_RECT_YPOSBEGIN"] = "Y Position Top Left"; // untranslated
Blockly.Msg["ARD_TFT_SPRITE_NAME"] = "Sprite named"; // untranslated
Blockly.Msg["ARD_TFT_TEXT_COLOUR"] = "Colour of the text"; // untranslated
Blockly.Msg["ARD_TFT_TEXT_SIZE"] = "Size"; // untranslated
Blockly.Msg["ARD_TFT_TEXT_TIP"] = "Write a text to the screen in the given colour at the given position."; // untranslated
Blockly.Msg["ARD_TFT_TEXT_WRITE"] = "Write text"; // untranslated
Blockly.Msg["ARD_TFT_TEXT_XPOS"] = "X Position"; // untranslated
Blockly.Msg["ARD_TFT_TEXT_YPOS"] = "Y Position"; // untranslated
Blockly.Msg["ARD_TIME_DELAY"] = "Délai d'attente de";
Blockly.Msg["ARD_TIME_DELAY_MICROS"] = "microsecondes";
Blockly.Msg["ARD_TIME_DELAY_MICRO_TIP"] = "Attendre un délai précis en microsecondes";
Blockly.Msg["ARD_TIME_DELAY_TIP"] = "Attendre un délai précis en millisecondes";
Blockly.Msg["ARD_TIME_EVERY"] = "every"; // untranslated
Blockly.Msg["ARD_TIME_INF"] = "Attente sans fin (fin du programme)";
Blockly.Msg["ARD_TIME_INF_TIP"] = "Attente indéfinie, arrêt du programme.";
Blockly.Msg["ARD_TIME_MICROS"] = "Temps écoulé (microsecondes)";
Blockly.Msg["ARD_TIME_MICROS_TIP"] = "Renvoie le temps en microseconds depuis le lancement de ce programme sur la carte Arduino. Doit être stocké dans un Entier long positif";
Blockly.Msg["ARD_TIME_MILLIS"] = "Temps écoulé (millisecondes)";
Blockly.Msg["ARD_TIME_MILLIS_TIP"] = "Renvoie le temps en milliseconds depuis le lancement de ce programme sur la carte Arduino. Doit être stocké dans un Entier long positif";
Blockly.Msg["ARD_TIME_MS"] = "millisecondes";
Blockly.Msg["ARD_TIME_S"] = "seconds"; // untranslated
Blockly.Msg["ARD_TONEDURATION"] = "and duration (ms)"; // untranslated
Blockly.Msg["ARD_TONEDURATION_TIP"] = "Sets tone on a buzzer to the specified frequency within range 31 - 65535 and given duration in milliseconds. Careful: a durations continues, also during delays, a new tone can only be given if a previous tone is terminated!"; // untranslated
Blockly.Msg["ARD_TONEFREQ"] = "à la frequence";
Blockly.Msg["ARD_TONEPITCH_TIP"] = "Sets tone on a buzzer to the specified pitch and given duration in milliseconds. Careful: a durations continues, also during delays, a new tone can only be given if a previous tone is terminated!"; // untranslated
Blockly.Msg["ARD_TONE_FREQ"] = "frequence";
Blockly.Msg["ARD_TONE_PIN"] = "Signal de tonalité #";
Blockly.Msg["ARD_TONE_PIN_TIP"] = "Génération de tonalité (son)sur un signal";
Blockly.Msg["ARD_TONE_TIP"] = " Configurer le signal de tonalité dans la plage: 31 - 65535";
Blockly.Msg["ARD_TONE_WARNING"] = "La fréquence doit être dans la plage 31 - 65535";
Blockly.Msg["ARD_TONE_WARNING2"] = "A duration must be positive (>0)"; // untranslated
Blockly.Msg["ARD_TYPE_ARRAY"] = "Tableau";
Blockly.Msg["ARD_TYPE_BOOL"] = "Booléen";
Blockly.Msg["ARD_TYPE_CHAR"] = "Charactère";
Blockly.Msg["ARD_TYPE_CHILDBLOCKMISSING"] = "Dépendance manquante";
Blockly.Msg["ARD_TYPE_DECIMAL"] = "Décimal";
Blockly.Msg["ARD_TYPE_LONG"] = "Entier long";
Blockly.Msg["ARD_TYPE_NULL"] = "Null";
Blockly.Msg["ARD_TYPE_NUMBER"] = "Entier";
Blockly.Msg["ARD_TYPE_SHORT"] = "Entier court";
Blockly.Msg["ARD_TYPE_TEXT"] = "Texte";
Blockly.Msg["ARD_TYPE_UNDEF"] = "Non défini";
Blockly.Msg["ARD_TYPE_UNSIGNED_NUMBER"] = "Positive Number"; // untranslated
Blockly.Msg["ARD_UNKNOWN_ALLBOTJOINT"] = "The old joint value %1 is no longer available"; // untranslated
Blockly.Msg["ARD_VALUE"] = "value"; // untranslated
Blockly.Msg["ARD_VAR_AS"] = "comme";
Blockly.Msg["ARD_VAR_AS_TIP"] = "Configure une valeur à un type précis";
Blockly.Msg["ARD_WRITE_TO"] = "à";
Blockly.Msg["B4A_COMPILE_EMPTY"] = "Compiler returned empty file - Device not flashed"; // untranslated
Blockly.Msg["B4A_ERROR"] = "ERROR!"; // untranslated
Blockly.Msg["B4A_FLASHING"] = "Flashing to device"; // untranslated
Blockly.Msg["B4A_MSG_EXTENSION"] = "Message from extension: "; // untranslated
Blockly.Msg["B4A_NO_CHROME"] = "You need to use Google Chrome to use this Upload functionality"; // untranslated
Blockly.Msg["B4A_NO_EXTENSION"] = "Chrome Extension is not installed"; // untranslated
Blockly.Msg["B4A_SET_IP_COMPILER"] = "New IP Address Compiler"; // untranslated
Blockly.Msg["B4A_SUCCESS"] = "SUCCESS!"; // untranslated
Blockly.Msg["B4A_UPLOAD_FAIL"] = "Upload failed. Chrome Extension is not installed"; // untranslated
Blockly.Msg["B4A_VERIFY_FAIL"] = "Verify failed. Chrome Extension is not installed"; // untranslated
Blockly.Msg["COLOUR_RGB255_TOOLTIP"] = "Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 255. See https://www.google.be/search?q=color+picker"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_CASEBREAK_TOOLTIP"] = "Add a new 'case'-block to check the condition for a new value."; // untranslated
Blockly.Msg["CONTROLS_SWITCH_DEFAULT_TOOLTIP"] = "Add an optional standard action which will be executed if NONE of the above conditions was satisfied"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_HELPURL"] = "https://nl.wikibooks.org/wiki/Programmeren_in_C++/Switch"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_MSG_CASEBREAK"] = "case"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_MSG_DEFAULT"] = "otherwise"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_MSG_DO"] = "do"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_MSG_SWITCHVAR"] = "Switch (condition variable)"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_SWITCH_TOOLTIP"] = "Add cases, remove them, or change the order of the cases in this switch-block."; // untranslated
Blockly.Msg["CONTROLS_SWITCH_TOOLTIP_1"] = "If the condition has the value, then do the statements."; // untranslated
Blockly.Msg["CONTROLS_SWITCH_TOOLTIP_2"] = "If the condition has the value, then do the first block of statements. Otherwise, do the second block of statements."; // untranslated
Blockly.Msg["CONTROLS_SWITCH_TOOLTIP_3"] = "If the condition has the first value, then do the first block of statements. Otherwise, if the condition has the second value, do the second block of statements."; // untranslated
Blockly.Msg["CONTROLS_SWITCH_TOOLTIP_4"] = "If the condition has the first value, then do the first block of statements. Otherwise, if the condition has the second value, do the second block of statements. If none of the values are correct, do the last block of statements."; // untranslated
Blockly.Msg["CONTROLS_SWITCH_VAR_TAIL"] = ")"; // untranslated
Blockly.Msg["CONTROLS_SWITCH_VAR_TITLE"] = "Switch condition ("; // untranslated
Blockly.Msg["CONTROLS_SWITCH_VAR_TOOLTIP"] = "Drag blocks from left to this region to add them."; // untranslated
Blockly.Msg["NEW_INSTANCE"] = "New instance..."; // untranslated
Blockly.Msg["NEW_INSTANCE_TITLE"] = "New instance name:"; // untranslated
Blockly.Msg["RENAME_INSTANCE"] = "Rename instance..."; // untranslated
Blockly.Msg["RENAME_INSTANCE_TITLE"] = "Rename all '%1' instances to:"; // untranslated
Blockly.Msg["REPLACE_EXISTING_BLOCKS"] = "Replace existing blocks? 'Cancel' will merge."; // untranslated
Blockly.Msg["SAVE_FILE_AS"] = "Save script as"; // untranslated
Blockly.Msg["UPLOAD_CLICK_1"] = "To Upload your code to Arduino:"; // untranslated
Blockly.Msg["UPLOAD_CLICK_2"] = " 1. click on the Arduino tab"; // untranslated
Blockly.Msg["UPLOAD_CLICK_3"] = " 2. select all the code, and copy (CTRL+A and CTRL+C)"; // untranslated
Blockly.Msg["UPLOAD_CLICK_4"] = " 3. In the Arduino IDE or in a http://codebender.cc sketch, paste the code (CTRL+V)"; // untranslated
Blockly.Msg["UPLOAD_CLICK_5"] = " 4. Upload to your connected Arduino"; // untranslated
Blockly.Msg["ARD_CONTROLS_EFFECT_ELSEIF_TITLE_ELSEIF"] = Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_ELSEIF"];
Blockly.Msg["ARD_CONTROLS_EFFECT_ELSE_TITLE_ELSE"] = Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_ELSE"];
Blockly.Msg["ARD_CONTROLS_EFFECT_IF_TITLE_IF"] = Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_IF"];
Blockly.Msg["ARD_CONTROLS_EFFECT_IF_TOOLTIP"] = Blockly.Msg["CONTROLS_IF_IF_TOOLTIP"];
Blockly.Msg["ARD_CONTROLS_EFFECT_MSG_THEN"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"];
Blockly.Msg["COMPONENTS_HUE"] = "#70D65C"; |
function a() {
b();
}
|
'use strict';
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime = void 0;
function debug() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// Disabled?
if (!debug.enabled) {
return;
}
var self = debug;
// Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend;
// Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
var i = void 0;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) {
return '-' + namespace;
}))).join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i = void 0;
var len = void 0;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup; |
const PricesData = [
{
id: 1,
title: "Wyważenie z optymalizacją geometryczną i przykręcenie koła",
thead: ["Rozmiar felgi", "Felga stalowa", "Felga aluminiowa"],
tbody: [
["13-14''", "20 zł", "25 zł"],
["15''", "25 zł", "30 zł"],
["16''", "30 zł", "35 zł"],
["17''", "35 zł", "40 zł"],
["18''", "", "45 zł"],
["19''", "", "50 zł"],
["20''", "", "55 zł"],
["Od 21''", "", "60 zł"],
],
},
{
id: 2,
title: "Wyważenie z optymalizacją geometryczną (koło luzem)",
thead: ["Rozmiar felgi", "Felga stalowa", "Felga aluminiowa"],
tbody: [
["13-14''", "15 zł", "20 zł"],
["15''", "20 zł", "25 zł"],
["16''", "25 zł", "30 zł"],
["17''", "30 zł", "35 zł"],
["18''", "", "40 zł"],
["19''", "", "45 zł"],
["20''", "", "50 zł"],
["Od 21''", "", "55 zł"],
],
},
{
id: 3,
title: "Prostowanie felgi",
thead: ["Rozmiar felgi", "Felga stalowa", "Felga aluminiowa"],
tbody: [
["13-14''", "Od 40 zł", "Od 80 zł"],
["15''", "Od 50 zł", "Od 100 zł"],
["16''", "Od 60 zł", "Od 100 zł"],
["17''", "Od 70 zł", "Od 130 zł"],
["18''", "", "Od 150 zł"],
["19''", "", "Od 200 zł"],
["20''", "", "Od 200 zł"],
["Od 21''", "", "Od 250 zł"],
],
},
{
id: 4,
title: "Malowanie felgi",
thead: ["Rozmiar felgi", "Felga stalowa", "Felga aluminiowa"],
tbody: [
["13-14''", "Od 50 zł", "Od 200 zł"],
["15''", "Od 55 zł", "Od 225 zł"],
["16''", "Od 60 zł", "Od 250 zł"],
["17''", "Od 70 zł", "Od 275 zł"],
["18''", "", "Od 325 zł"],
["19''", "", "Od 350 zł"],
["20''", "", "Od 375 zł"],
["Od 21''", "", "Od 400 zł"],
],
},
{
id: 5,
title: "Samochody",
thead: [],
tbody: [
["Koła z czujnikami ciśnienia", "+0 zł do ceny wyważenia"],
["Felgi nieprzelotowe", "+5 zł do ceny wyważenia"],
["4x4, SUV, bus/dostawczy", "Od 5 zł do ceny wyważenia"],
["Koła z oponami typu Run Flat", "+5 zł do ceny wyważenia"],
["Odkręcenie i przykręcenie koła", "10 zł"],
["Montaż/demontaż opony", "Od 5 zł"],
["Wulkanizacja opony (+koszt wyważenia)", "Od 25 zł"],
["Wulkanizacja dętki", "Od 10 zł"],
["Uszczelnienie 1 rantu felgi", "25 zł"],
["Utylizacja opony", "5 zł"],
["Montaż czujnika ciśnienia", "10 zł"],
["Przyuczanie czujników ciśnienia", "40 zł / samochód"],
["Mycie koła", "Od 5 zł"],
["Gwintowanie otworu/szpilki", "5 zł"],
["Podmalowanie felgi aluminiowej", "Od 120 zł"],
["Roztoczenie otworu centrującego", "50 zł"],
["Poprawienie stożków/rozwiercenie otworów", "10 zł"],
["Awaryjny demontaż śruby", "25 zł"],
["Optymalizacja wadliwej opony", "1/2 ceny wyważenia"],
["Malowanie na więcej niż jeden kolor", "+150 zł / kolor"],
["Toczenie frontu/rantu CNC", "+150 zł"],
["Pierścień centrujący", "Od 10 zł"],
["Kominek/zawór gumowy (do 210 km/h)", "Od 5 zł"],
["Kominek/zawór alu lub TPMS", "Od 25 zł"],
["Śruba/nakrętka", "Od 5 zł"],
["Śruby/nakrętki zabezpieczające McGard", "Od 130 zł"],
["Dystanse", "Od 200 zł / para"],
],
},
{
id: 6,
title: "Motory i Quady",
thead: [],
tbody: [
["Wyważenie koła", "30 zł"],
["Montaż/demontaż opony", "15 zł"],
["Montaż/demontaż opony z dętką", "20 zł"],
["Hamulec w feldze", "+10 zł"],
["Prostowanie felgi", "Od 150 zł"],
["Malowanie felgi", "Od 150 zł"],
],
},
{
id: 7,
title: "Przechowanie kompletu kół/opon",
thead: [],
tbody: [
["Przechowanie do 16''", "60 zł"],
["Przechowanie od 17''", "80 zł"],
["Przechowanie od 19''", "100 zł"],
["Przechowanie 4x4, SUV, itp.", "100 zł"],
],
},
]
export default PricesData
|
"""Streamdata.io demo."""
import sys
import collections
import json
import time
import random
import jsonpatch
import requests
import sseclient
from terminaltables import AsciiTable
SD_TOKEN = "[YOUR_STREAMDATAIO_APP_TOKEN]"
DEMO_API = "http://stockmarket.streamdata.io/v2/prices"
URL = (
"https://streamdata.motwin.net/{}?X-Sd-Token={}".format(DEMO_API, SD_TOKEN)
)
def print_table(data):
"""Print data as a table."""
table_data = []
for item in data:
item = collections.OrderedDict(
sorted(item.items(), key=lambda t: t[0]))
if len(table_data) == 0:
table_data.append(item.keys())
table_data.append(item.values())
table = AsciiTable(table_data)
print(table.table)
def run(data, headers, retryCount):
"""Launch client."""
"""with requests.get(URL, stream=True) as response:"""
print(headers)
try:
with requests.get(URL, stream=True, headers=headers) as response:
client = sseclient.SSEClient(response)
for event in client.events():
if event.event == "data":
print("Data event received")
last_event_id = event.id
data = json.loads(event.data)
print_table(data)
elif event.event == "patch":
print("Patch event received")
last_event_id = event.id
patch = jsonpatch.JsonPatch.from_string(event.data)
patch.apply(data, in_place=True)
print_table(data)
elif event.event == "error":
"""Print the error by default.
You can perform some error analysis according to
the message sent"""
print("Error: {}".format(event.data))
"""By default, close the connnection and re-initiate a
new one with the Last-Event-ID of the latest message
"""
client.close()
"""Depending on the analysis of the error, you may want to
reconnect. That's the purpose of the code below.
BEWARE to perform an error analysis first. IN SOME CASE,
YOU DON'T WANT TO RECONNECT blindingly: bad API url,
authentication errors, etc. In such a case, you just
close the connection and deal with the error.
In the below example, we reconnect according to the status
code returned by the server.
NOTE that in addition, we count the number of attempts.
If a threshold of unsuccessful attempts has been reached,
we don't reconnect again: the issue is probably permanent.
NOTE that you can analyze the err['message'] to provide
a finer error message to your end users.
"""
err = json.loads(event.data)
status = err['status']
""" status 2001 -> the API had an error, retry can be worthwhile
status 2004 -> there was a connection issue with the targeted API server, retry can be worthwhile
status 2008 -> there was an issue while sending the event message from the server, retry can be worthwhile
"""
if retryCount < 5 and (status == 2001 or status == 2004 or status == 2008):
retryCount = retryCount + 1
"""The server can set a retry in ms if not, we set a default
one to give to the 'Requests' lib
the time to close properly the connection"""
retry = 15
if event.retry is not None:
retry = event.retry / 1000.0
"""If there are several parallel connections, we introduce
a random in order to avoid re-connnections at
the same time
"""
time.sleep(retry + random.randint(0, 15))
"""Re-initiate a new connection with the Last-Event-ID and
the latest data received (to be able to apply the next
patch)
"""
run(data, { 'Last-Event-ID': last_event_id }, retryCount)
else:
print("Unhandled event received.")
client.close()
except:
print("Unexpected error:", sys.exc_info()[0])
if __name__ == "__main__":
run([], {}, 0)
|
var ListTakeOrder = {
Init: function () {
this.InitData();
},
InitEvent:function(){
},
InitData: function () {
this.CreateTabs();
},
CreateTabs: function () {
var orderType = $.trim($('[id$=hOrderType]').val());
var Id = $.trim($("#hId").val());
var t = $("#tabTakeOrder");
if (!t.tabs('exists', '常用')) {
t.tabs('add', {
selected:true,
title: '常用',
style: { paddingTop: 20 },
href: '/wms/a/ginstore.html?Id=' + Id + '&orderType=' + orderType + ''
});
}
if (!t.tabs('exists', '其他信息')) {
t.tabs('add', {
selected: false,
title: '其他信息',
style: { padding: 20 },
href: '/wms/a/ttinstore.html?Id=' + Id + '&orderType=' + orderType + ''
});
}
if (!t.tabs('exists', '自定义')) {
t.tabs('add', {
selected: false,
title: '自定义',
style: { padding: 20 },
href: '/wms/a/tyinstore.html?Id=' + Id + '&orderType=' + orderType + ''
});
}
},
Add: function () {
var orderType = $.trim($('[id$=hOrderType]').val());
window.location = '/wms/a/yinstore.html?orderType=' + orderType + '';
},
SaveOrderReceipt: function () {
var isValid = $('#addOrderReceiptBaseFm').form('validate');
if (!isValid) return false;
isValid = $('#addOrderReceiptAttrFm').form('validate');
if (!isValid) return false;
var orderType = $.trim($('[id$=hOrderType]').val());
var Id = $.trim($("#hId").val());
var sPreOrderCode = $.trim($('[id$=txtPreOrderCode]').val());
var sPurchaseOrderCode = $.trim($("#txtPurchaseOrderCode").val());
var status = $.trim($("#ddlOrderReceiptStatus option:selected").text());
var type = $.trim($("#ddlOrderReceiptType>option:selected").text());
var settlementDate = $.trim($("#txtSettlementDate").val());
var expectVolume = $.trim($("#txtExpectVolume").val());
if (expectVolume == "") expectVolume = 0;
var gW = $.trim($("#txtGW").val());
if (gW == "") gW = 0;
var customerId = $.trim($("#hCustomerId").val());
var customAttr = "";
$("#customInfoT tr input").each(function () {
var value = $.trim($(this).val());
var key = $.trim($(this).parent().prev().find("span").text());
customAttr += "<Add Key=\"" + key + "\"><![CDATA[" + value + "]]></Add>";
})
customAttr = "<Datas><Data>" + customAttr + "</Data></Datas>";
customAttr = encodeURIComponent(customAttr);
var url = "/wms/Services/WmsService.svc/SaveOrderReceipt";
var sData = '{"OrderType":"' + orderType + '","Id":"' + Id + '","OrderCode":"' + $.trim($("#lbOrderNum").text()) + '","CustomerId":"' + customerId + '","PurchaseOrderCode":"' + sPurchaseOrderCode + '","TypeName":"' + type + '","Status":"' + status + '","RecordDate":"' + $.trim($("#txtRecordDate").val()) + '","SettlementDate":"' + settlementDate + '","Remark":"' + $.trim($("#txtaRemark").val()) + '","LastTakeDate":"' + $.trim($("#txtLastTakeDate").val()) + '","ExpectTakeDate":"' + $.trim($("#txtExpectTakeDate").val()) + '","SendDate":"' + $.trim($("#txtSendDate").val()) + '","PlanSendDate":"' + $.trim($("#txtPlanSendDate").val()) + '","RMA":"' + $.trim($("#txtRMA").val()) + '","ExpectVolume":"' + expectVolume + '","GW":"' + gW + '","CustomAttr":"' + customAttr + '"}';
$.ajax({
url: url,
type: "post",
data: '{"model":' + sData + '}',
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$.messager.progress({ title: '请稍等', msg: '正在执行...' });
},
complete: function () {
$.messager.progress('close');
},
success: function (result) {
if (result.ResCode != 1000) {
$.messager.alert('系统提示', result.Msg, 'info');
return false;
}
$("#hId").val(result.Data);
jeasyuiFun.show("温馨提示", "保存成功!");
setTimeout(function () {
window.location = '/wms/a/yinstore.html?Id=' + result.Data + '';
}, 1000);
}
});
}
} |
import{B as e}from"./index.73c280ed.js";import{g as s}from"./index.3f4b0a4c.js";import{_ as c}from"./PageWrapper.acc8d12f.js";import{k as l,c0 as t,bM as n,r as a,l as r,m as i,K as u,o,n as d,q as f,x as p,Y as m}from"./vendor.9d9efc92.js";import"./createAsyncComponent.a0cf9207.js";import"./usePageContext.18bdf57b.js";/* empty css *//* empty css */import"./onMountedOrActivated.b73559bc.js";var y=l({components:{BasicDragVerify:e,BugOutlined:t,RightOutlined:n,PageWrapper:c},setup(){const{createMessage:e}=s();return{handleSuccess:function(s){const{time:c}=s;e.success(`校验成功,耗时${c}秒`)},el1:a(null),el2:a(null),el3:a(null),el4:a(null),el5:a(null),handleBtnClick:function(e){e&&e.resume()}}}});const g=p();r("data-v-a0470878");const k={class:"flex justify-center p-4 items-center bg-gray-700"},S=m(" 还原 "),b={class:"flex justify-center p-4 items-center bg-gray-700"},x=m(" 还原 "),h={class:"flex justify-center p-4 items-center bg-gray-700"},j=m(" 还原 "),C={class:"flex justify-center p-4 items-center bg-gray-700"},v=m(" 还原 "),B={class:"flex justify-center p-4 items-center bg-gray-700"},_={key:0},O=m(" 成功 "),P={key:1},M=m(" 拖动 "),W=m(" 还原 ");i();const A=g(((e,s,c,l,t,n)=>{const a=u("BasicDragVerify"),r=u("a-button"),i=u("BugOutlined"),p=u("RightOutlined"),m=u("PageWrapper");return o(),d(m,{title:"拖动校验示例"},{default:g((()=>[f("div",k,[f(a,{ref:"el1",onSuccess:e.handleSuccess},null,8,["onSuccess"]),f(r,{type:"primary",class:"ml-2",onClick:s[1]||(s[1]=s=>e.handleBtnClick(e.el1))},{default:g((()=>[S])),_:1})]),f("div",b,[f(a,{ref:"el2",onSuccess:e.handleSuccess,circle:""},null,8,["onSuccess"]),f(r,{type:"primary",class:"ml-2",onClick:s[2]||(s[2]=s=>e.handleBtnClick(e.el2))},{default:g((()=>[x])),_:1})]),f("div",h,[f(a,{ref:"el3",onSuccess:e.handleSuccess,text:"拖动以进行校验",successText:"校验成功",barStyle:{backgroundColor:"#018ffb"}},null,8,["onSuccess"]),f(r,{type:"primary",class:"ml-2",onClick:s[3]||(s[3]=s=>e.handleBtnClick(e.el3))},{default:g((()=>[j])),_:1})]),f("div",C,[f(a,{ref:"el4",onSuccess:e.handleSuccess},{actionIcon:g((e=>[e?(o(),d(i,{key:0})):(o(),d(p,{key:1}))])),_:1},8,["onSuccess"]),f(r,{type:"primary",class:"ml-2",onClick:s[4]||(s[4]=s=>e.handleBtnClick(e.el4))},{default:g((()=>[v])),_:1})]),f("div",B,[f(a,{ref:"el5",onSuccess:e.handleSuccess},{text:g((e=>[e?(o(),d("div",_,[f(i),O])):(o(),d("div",P,[M,f(p)]))])),_:1},8,["onSuccess"]),f(r,{type:"primary",class:"ml-2",onClick:s[5]||(s[5]=s=>e.handleBtnClick(e.el5))},{default:g((()=>[W])),_:1})])])),_:1})}));y.render=A,y.__scopeId="data-v-a0470878";export default y;
|
import styled from 'styled-components';
const Container = styled.div`
background: #F0F0F3;
width: 100%;
height: 100%;
`;
export { Container }; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.