text stringlengths 1 1.05M |
|---|
package io.opensphere.csvcommon.detect.columnformat;
/** Common interface for column format parameters. */
public interface ColumnFormatParameters
{
}
|
#!/bin/bash
set -e
echo
echo "Updating zcashd and instructing it to reindex the wallet."
echo
echo "This may take a minute..."
curl -sS https://raw.githubusercontent.com/lamassu/lamassu-patches/master/wallets/update/zec.sh | bash &>/dev/null
supervisorctl stop zcash &>/dev/null
curl -#o /etc/supervisor/conf.d/zcash.conf https://raw.githubusercontent.com/lamassu/lamassu-patches/master/wallets/reindex/zec/zcash-reindex.conf &>/dev/null
supervisorctl update zcash &>/dev/null
curl -#o /etc/supervisor/conf.d/zcash.conf https://raw.githubusercontent.com/lamassu/lamassu-patches/master/wallets/reindex/zec/zcash.conf &>/dev/null
sleep 10s
supervisorctl update zcash &>/dev/null
echo
echo "Done. Your latest wallet balance will be displayed after the blockchain has fully reindexed."
echo
echo "This may take some time. Use the KB article 'Checking wallet synchronization' for current status."
echo
|
#!/usr/bin/env bash
#
# This script is copied from `https://github.com/paritytech/jsonrpc` with some minor tweaks.
# Add `--dry-run` and/or `--allow-dirty` to your command line to test things before publication.
set -eu
ORDER=(types proc-macros utils http-client http-server ws-client ws-server jsonrpsee)
function read_toml () {
NAME=""
VERSION=""
NAME=$(grep "^name" ./Cargo.toml | sed -e 's/.*"\(.*\)"/\1/')
VERSION=$(grep "^version" ./Cargo.toml | sed -e 's/.*"\(.*\)"/\1/')
}
function remote_version () {
REMOTE_VERSION=""
REMOTE_VERSION=$(cargo search "$NAME" | grep "^$NAME =" | sed -e 's/.*"\(.*\)".*/\1/')
}
# First display the plan
for CRATE_DIR in ${ORDER[@]}; do
cd $CRATE_DIR > /dev/null
read_toml
echo "$NAME@$VERSION"
cd - > /dev/null
done
read -p ">>>> Really publish?. Press [enter] to continue. "
set -x
cargo clean
set +x
# Then actually perform publishing.
for CRATE_DIR in ${ORDER[@]}; do
cd $CRATE_DIR > /dev/null
read_toml
remote_version
# Seems the latest version matches, skip by default.
if [ "$REMOTE_VERSION" = "$VERSION" ] || [[ "$REMOTE_VERSION" > "$VERSION" ]]; then
RET=""
echo "Seems like $NAME@$REMOTE_VERSION is already published. Continuing in 5s. "
read -t 5 -p ">>>> Type [r][enter] to retry, or [enter] to continue... " RET || true
if [ "$RET" != "r" ]; then
echo "Skipping $NAME@$VERSION"
cd - > /dev/null
continue
fi
fi
# Attempt to publish (allow retries)
while : ; do
# give the user an opportunity to abort or skip before publishing
echo "🚀 Publishing $NAME@$VERSION..."
sleep 3
set +e && set -x
cargo publish $@
RES=$?
set +x && set -e
# Check if it succeeded
if [ "$RES" != "0" ]; then
CHOICE=""
echo "##### Publishing $NAME failed"
read -p ">>>>> Type [s][enter] to skip, or [enter] to retry.. " CHOICE
if [ "$CHOICE" = "s" ]; then
break
fi
else
break
fi
done
# Wait again to make sure that the new version is published and available.
echo "Waiting for $NAME@$VERSION to become available at the registry..."
while : ; do
sleep 3
remote_version
if [ "$REMOTE_VERSION" = "$VERSION" ]; then
echo "🥳 $NAME@$VERSION published succesfully."
sleep 3
break
else
echo "#### Got $NAME@$REMOTE_VERSION but expected $NAME@$VERSION. Retrying..."
fi
done
cd - > /dev/null
done
echo "Tagging jsonrpsee@$VERSION"
set -x
git tag -a v$VERSION -m "Version $VERSION"
sleep 3
git push --tags
|
<reponame>naga-project/webfx
package dev.webfx.kit.mapper.peers.javafxgraphics.base;
import javafx.scene.Group;
/**
* @author <NAME>
*/
public class GroupPeerBase
<N extends Group, NB extends GroupPeerBase<N, NB, NM>, NM extends GroupPeerMixin<N, NB, NM>>
extends NodePeerBase<N, NB, NM> {
}
|
<filename>client/components/user-home.js
import React from 'react'
// import PropTypes from 'prop-types'
import {
connect
} from 'react-redux'
// import { Draft } from './draft'
import { withStyles } from '@material-ui/core/styles';
import {
fetchNotes,
fetchSharedNotes
} from '../store';
import NoteThumb from './NoteThumb'
import EditModalWrapped from './editModal'
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import AddIcon from '@material-ui/icons/Add';
import { Avatar } from '@material-ui/core';
const styles = theme => ({
root: theme.mixins.gutters({
paddingTop: 16,
paddingBottom: 16,
marginTop: theme.spacing.unit * 3,
}),
});
/**
* COMPONENT
*/
export class UserHome extends React.Component {
componentDidMount() {
this.props.loadInitialData()
}
render() {
let { note, share } = this.props
return (
<div className = "card-main" >
{
note.length && note.map(
notes => ( <NoteThumb key = {notes.id} note = {notes} readonly={false} /> )
)
}
{
share.length && share.map(
shares => ( <NoteThumb key = {shares.id} note = {shares.note} shares={shares} readonly={shares.readonly} /> )
)
}
</div>
)
}
}
/**
* CONTAINER
*/
const mapState = ({
user,
note,
share
}) => ({
note,
share,
isLoggedIn: !!user.id
});
const mapDispatch = (dispatch) => {
return {
loadInitialData() {
dispatch(fetchSharedNotes())
dispatch(fetchNotes())
}
}
}
// export default connect(mapState, mapDispatch).withStyles(styles)(UserHome);
const UserHomeStyle = withStyles(styles)(UserHome);
export default connect(mapState, mapDispatch)(UserHomeStyle)
|
<filename>server/src/cloud/board.ts
import {newObjectId} from "parse-server/lib/cryptoUtils";
import {StatusResponse} from "types";
import {UserConfigurations} from "types/user";
import * as crypto from "crypto";
import {getAdminRoleName, getMemberRoleName, isMember, isOnline, requireValidBoardAdmin} from "./permission";
import {api} from "./util";
import {serverConfig} from "../index";
import Color, {isOfTypeColor} from "../util/Color";
interface JoinBoardResponse {
status: "accepted" | "passphrase_required" | "incorrect_passphrase" | "rejected" | "pending";
joinRequestReference?: string;
}
const goOnline = (user: Parse.User, boardId: string) => {
user.add("boards", boardId);
user.save(null, {useMasterKey: true});
};
const addAsMember = async (user: Parse.User, boardId: string) => {
const memberRoleQuery = new Parse.Query(Parse.Role);
memberRoleQuery.equalTo("name", getMemberRoleName(boardId));
const memberRole = await memberRoleQuery.first({useMasterKey: true});
if (memberRole) {
goOnline(user, boardId);
memberRole.getUsers().add(user);
return memberRole.save(null, {useMasterKey: true});
}
throw new Error(`No roles for board '${boardId}' found`);
};
const addToModerators = async (user: Parse.User, boardId: string) => {
const adminRoleQuery = new Parse.Query(Parse.Role);
adminRoleQuery.equalTo("name", getAdminRoleName(boardId));
const adminRole = await adminRoleQuery.first({useMasterKey: true});
if (adminRole) {
adminRole.getUsers().add(user);
return adminRole.save(null, {useMasterKey: true});
}
throw new Error(`No roles for board '${boardId}' found`);
};
const removeFromModerators = async (user: Parse.User, boardId: string) => {
const adminRoleQuery = new Parse.Query(Parse.Role);
adminRoleQuery.equalTo("name", getAdminRoleName(boardId));
const adminRole = await adminRoleQuery.first({useMasterKey: true});
if (adminRole) {
adminRole.getUsers().remove(user);
return adminRole.save(null, {useMasterKey: true});
}
throw new Error(`No roles for board '${boardId}' found`);
};
const AccessPolicyType = {
Public: "Public" as const,
ByPassphrase: "ByPassphrase" as const,
ManualVerification: "ManualVerification" as const,
};
type AccessPolicy = {
type: keyof typeof AccessPolicyType;
passphrase?: string;
};
type AccessPolicyByPassphrase = AccessPolicy & {
passphrase: string;
salt: string;
};
const convertToAccessPolicyByPassphrase = (accessPolicy: AccessPolicy): AccessPolicyByPassphrase => {
const salt = crypto.randomBytes(32).toString("hex");
const passphrase = crypto
.createHash("sha256")
.update(accessPolicy.passphrase + salt)
.digest("base64");
return {
type: accessPolicy.type,
salt,
passphrase,
};
};
const respondToJoinRequest = async (currentUser: Parse.User, users: string[], board: string, manipulate: (object: Parse.Object) => void) => {
await requireValidBoardAdmin(currentUser, board);
const BoardClass = Parse.Object.extend("Board");
const joinRequestQuery = new Parse.Query("JoinRequest");
joinRequestQuery.equalTo("board", BoardClass.createWithoutData(board));
joinRequestQuery.containedIn(
"user",
users.map((userId) => Parse.User.createWithoutData(userId))
);
joinRequestQuery.find({useMasterKey: true}).then(async (pendingJoinRequests) => {
pendingJoinRequests.forEach(
(joinRequest) => {
manipulate(joinRequest);
},
{useMasterKey: true}
);
await Parse.Object.saveAll(pendingJoinRequests, {useMasterKey: true});
});
};
export interface CreateBoardRequest {
columns: {
name: string;
color: Color;
hidden: boolean;
}[];
name?: string;
encryptedContent?: boolean;
accessPolicy: AccessPolicy;
}
export type EditableBoardAttributes = {
name: string;
showAuthors?: boolean;
timerUTCEndTime?: Date;
accessPolicy?: AccessPolicy;
voting?: "active" | "disabled";
votingIteration: number;
showNotesOfOtherUsers: boolean;
moderation?: {userId?: string; status: "active" | "disabled"};
};
export type EditBoardRequest = {id: string} & Partial<EditableBoardAttributes>;
export type DeleteBoardRequest = {boardId: string};
export interface JoinRequestResponse {
board: string;
users: string[];
}
export interface JoinBoardRequest {
boardId: string;
passphrase?: string;
}
export const initializeBoardFunctions = () => {
api<CreateBoardRequest, string>("createBoard", async (user, request) => {
const board = new Parse.Object("Board");
const columns = request.columns.reduce((acc, current) => {
if (!isOfTypeColor(current.color)) {
throw new Error(`color ${current.color} is not allowed for columns`);
}
acc[newObjectId(serverConfig.objectIdSize)] = {
name: current.name,
color: current.color,
hidden: current.hidden,
};
return acc;
}, {});
const userConfigurations: UserConfigurations = {};
userConfigurations[user.id] = {showHiddenColumns: true};
let {accessPolicy} = request;
if (accessPolicy.type === AccessPolicyType.ByPassphrase) {
accessPolicy = convertToAccessPolicyByPassphrase(accessPolicy);
}
const savedBoard = await board.save({...request, accessPolicy, columns, owner: user, userConfigurations}, {useMasterKey: true});
const adminRoleACL = new Parse.ACL();
adminRoleACL.setPublicReadAccess(false);
adminRoleACL.setPublicWriteAccess(false);
adminRoleACL.setWriteAccess(user, true);
const adminRole = new Parse.Role(getAdminRoleName(board.id), adminRoleACL);
adminRoleACL.setRoleWriteAccess(adminRole, true);
adminRoleACL.setRoleReadAccess(adminRole, true);
adminRoleACL.setRoleReadAccess(getMemberRoleName(board.id), true);
adminRole.getUsers().add(user);
const memberRoleACL = new Parse.ACL();
memberRoleACL.setPublicReadAccess(false);
memberRoleACL.setPublicWriteAccess(false);
memberRoleACL.setRoleWriteAccess(adminRole, true);
memberRoleACL.setRoleReadAccess(adminRole, true);
const memberRole = new Parse.Role(getMemberRoleName(board.id), memberRoleACL);
memberRoleACL.setRoleReadAccess(memberRole, true);
await memberRole.save(null, {useMasterKey: true});
await addAsMember(user, savedBoard.id);
adminRole.getRoles().add(memberRole);
await adminRole.save(null, {useMasterKey: true});
const boardACL = new Parse.ACL();
boardACL.setRoleWriteAccess(adminRole, true);
boardACL.setRoleReadAccess(adminRole, true);
boardACL.setRoleReadAccess(memberRole, true);
savedBoard.setACL(boardACL);
return (await savedBoard.save(null, {useMasterKey: true})).id;
});
api<JoinBoardRequest, JoinBoardResponse>("joinBoard", async (user, request) => {
const boardQuery = new Parse.Query<Parse.Object>("Board");
const board = await boardQuery.get(request.boardId, {
useMasterKey: true,
});
if (!board) {
throw new Error(`Board '${request.boardId}' not found`);
}
if (await isMember(user, request.boardId)) {
// handle browser refresh
if (!isOnline(user, request.boardId)) {
goOnline(user, request.boardId);
}
return {
status: "accepted",
};
}
const accessPolicy = board.get("accessPolicy");
if (accessPolicy.type !== AccessPolicyType.Public) {
if (accessPolicy.type === AccessPolicyType.ByPassphrase) {
if (!request.passphrase) {
return {
status: "passphrase_required",
};
}
const passphrase = crypto
.createHash("sha256")
.update(request.passphrase + accessPolicy.salt)
.digest("base64");
if (passphrase !== accessPolicy.passphrase) {
return {
status: "incorrect_passphrase",
};
}
}
if (accessPolicy.type === AccessPolicyType.ManualVerification) {
const BoardClass = Parse.Object.extend("Board");
const boardReference = BoardClass.createWithoutData(request.boardId);
const joinRequestQuery = new Parse.Query("JoinRequest");
joinRequestQuery.equalTo("board", boardReference);
joinRequestQuery.equalTo("user", user);
const joinRequestQueryResult = await joinRequestQuery.first({
useMasterKey: true,
});
if (joinRequestQueryResult) {
if (joinRequestQueryResult.get("status") === "accepted") {
await addAsMember(user, request.boardId);
return {
status: "accepted",
joinRequestReference: joinRequestQueryResult.id,
accessKey: joinRequestQueryResult.get("accessKey"),
};
}
return {
status: joinRequestQueryResult.get("status"),
joinRequestReference: joinRequestQueryResult.id,
accessKey: joinRequestQueryResult.get("accessKey"),
};
}
const joinRequest = new Parse.Object("JoinRequest");
joinRequest.set("user", user);
joinRequest.set("board", boardReference);
const joinRequestACL = new Parse.ACL();
joinRequestACL.setReadAccess(user.id, true);
joinRequestACL.setRoleReadAccess(getAdminRoleName(request.boardId), true);
joinRequestACL.setRoleWriteAccess(getAdminRoleName(request.boardId), true);
joinRequest.setACL(joinRequestACL);
const savedJoinRequest = await joinRequest.save(null, {
useMasterKey: true,
});
return {
status: "pending",
joinRequestReference: savedJoinRequest.id,
};
}
}
const userConfigurations: UserConfigurations = await board.get("userConfigurations");
userConfigurations[user.id] = {showHiddenColumns: true};
board.set("userConfigurations", userConfigurations);
await board.save(null, {useMasterKey: true});
await addAsMember(user, request.boardId);
return {status: "accepted"};
});
api<JoinRequestResponse, boolean>("acceptUsers", async (user, request) => {
await respondToJoinRequest(user, request.users, request.board, (object) => {
object.set("status", "accepted");
// object.set('accessKey', params.accessKey);
});
return true;
});
api<JoinRequestResponse, boolean>("rejectUsers", async (user, request) => {
await respondToJoinRequest(user, request.users, request.board, (object) => {
object.set("status", "rejected");
});
return true;
});
api<{board: EditBoardRequest}, boolean>("editBoard", async (user, request) => {
await requireValidBoardAdmin(user, request.board.id);
if (Object.keys(request.board).length <= 1) {
throw new Error(`No fields to edit defined in edit request of board '${request.board.id}'`);
}
const boardQuery = new Parse.Query(Parse.Object.extend("Board"));
const board = await boardQuery.get(request.board.id, {useMasterKey: true});
if (!board) {
throw new Error(`Board ${request.board.id} not found`);
}
if (request.board.showAuthors != null) {
board.set("showAuthors", request.board.showAuthors);
}
if (request.board.timerUTCEndTime) {
board.set("timerUTCEndTime", request.board.timerUTCEndTime);
}
if (request.board.name) {
board.set("name", request.board.name);
}
if (request.board.accessPolicy != null) {
if (request.board.accessPolicy.type === AccessPolicyType.ByPassphrase) {
board.set("accessPolicy", convertToAccessPolicyByPassphrase(request.board.accessPolicy));
} else {
board.set("accessPolicy", request.board.accessPolicy);
}
}
if (request.board.voting) {
if (request.board.voting === "active") {
board.set("votingIteration", board.get("votingIteration") + 1);
}
board.set("voting", request.board.voting);
}
if (request.board.moderation) {
board.set("moderation", request.board.moderation);
if (request.board.moderation.status === "disabled") {
const notesQuery = new Parse.Query("Note");
notesQuery.equalTo("board", board);
if ((await notesQuery.count()) > 0) {
notesQuery.first({useMasterKey: true}).then(async (note) => {
note.set("focus", false);
await note.save(null, {useMasterKey: true});
});
}
}
}
if (request.board.showNotesOfOtherUsers != undefined) {
board.set("showNotesOfOtherUsers", request.board.showNotesOfOtherUsers);
}
await board.save(null, {useMasterKey: true});
return true;
});
api<DeleteBoardRequest, boolean>("deleteBoard", async (user, request) => {
await requireValidBoardAdmin(user, request.boardId);
const boardQuery = new Parse.Query(Parse.Object.extend("Board"));
const board = await boardQuery.get(request.boardId, {useMasterKey: true});
const noteQuery = new Parse.Query(Parse.Object.extend("Note"));
noteQuery.equalTo("board", board);
const notes = await noteQuery.findAll({useMasterKey: true});
await Parse.Object.destroyAll(notes, {useMasterKey: true});
const voteQuery = new Parse.Query("Vote");
voteQuery.equalTo("board", board);
const votes = await voteQuery.findAll({useMasterKey: true});
await Parse.Object.destroyAll(votes, {useMasterKey: true});
const joinRequestQuery = new Parse.Query("JoinRequest");
joinRequestQuery.equalTo("board", board);
const joinRequests = await joinRequestQuery.findAll({useMasterKey: true});
await Parse.Object.destroyAll(joinRequests, {useMasterKey: true});
const voteConfigurationQuery = new Parse.Query("VoteConfiguration");
voteConfigurationQuery.equalTo("board", board);
const voteConfigurations = await voteConfigurationQuery.findAll({useMasterKey: true});
await Parse.Object.destroyAll(voteConfigurations, {useMasterKey: true});
const adminRoleQuery = new Parse.Query(Parse.Role);
adminRoleQuery.equalTo("name", `admin_of_${request.boardId}`);
const adminRoles = await adminRoleQuery.findAll({useMasterKey: true});
await Parse.Object.destroyAll(adminRoles, {useMasterKey: true});
const memberRoleQuery = new Parse.Query(Parse.Role);
memberRoleQuery.equalTo("name", `member_of_${request.boardId}`);
const memberRoles = await memberRoleQuery.findAll({useMasterKey: true});
await Parse.Object.destroyAll(memberRoles, {useMasterKey: true});
await board.destroy({useMasterKey: true});
return true;
});
type ChangePermissionRequest = {
userId: string;
boardId: string;
moderator: boolean;
};
api<ChangePermissionRequest, StatusResponse>("changePermission", async (user, request) => {
await requireValidBoardAdmin(user, request.boardId);
if (request.moderator) {
await addToModerators(Parse.User.createWithoutData(request.userId), request.boardId);
return {status: "Success", description: "User was successfully added to the list of moderators"};
}
// Make sure that moderators cannot remove themselfs from the list of moderators
if (request.userId === user.id) {
return {status: "Error", description: "You cannot remove yourself from the list of moderators"};
}
// Make sure that the board creator cannot get removed from the list of moderators)
const board = await new Parse.Query("Board").get(request.boardId, {useMasterKey: true});
if (request.userId === board.get("owner").id) {
return {status: "Error", description: "The creator of the board cannot be removed from the list of moderators"};
}
await removeFromModerators(Parse.User.createWithoutData(request.userId), request.boardId);
return {status: "Success", description: "User was successfully removed from the list of moderators"};
});
/**
* Cancel voting
*/
api<{boardId: string}, StatusResponse>("cancelVoting", async (user, request) => {
await requireValidBoardAdmin(user, request.boardId);
const board = await new Parse.Query("Board").get(request.boardId, {useMasterKey: true});
// Check if the board exists
if (!board) {
return {status: "Error", description: `Board '${request.boardId}' does not exist`};
}
// Check if the board exists
if ((await board.get("voting")) === "disabled") {
return {status: "Error", description: `Voting is already disabled`};
}
const votingIteration = await board.get("votingIteration");
const voteConfigurationQuery = new Parse.Query("VoteConfiguration");
voteConfigurationQuery.equalTo("board", board);
// Voting iteraion already incremented
const voteConfiguration = await voteConfigurationQuery.equalTo("votingIteration", votingIteration).first({useMasterKey: true});
await voteConfiguration.destroy({useMasterKey: true});
const voteQuery = new Parse.Query("Vote");
voteQuery.equalTo("board", board);
voteQuery.equalTo("votingIteration", votingIteration);
const votes = await voteQuery.findAll({useMasterKey: true});
await Parse.Object.destroyAll(votes, {useMasterKey: true});
// add new value canceled?
board.set("voting", "disabled");
await board.save(null, {useMasterKey: true});
return {status: "Success", description: "Current voting phase was canceled"};
});
api<{endDate: Date; boardId: string}, StatusResponse>("setTimer", async (user, request) => {
await requireValidBoardAdmin(user, request.boardId);
const board = await new Parse.Query("Board").get(request.boardId, {useMasterKey: true});
if (!board) {
return {status: "Error", description: `Board '${request.boardId}' does not exist`};
}
board.set("timerUTCEndTime", request.endDate);
await board.save(null, {useMasterKey: true});
return {status: "Success", description: "Timer was successfully set"};
});
api<{boardId: string}, StatusResponse>("cancelTimer", async (user, request) => {
await requireValidBoardAdmin(user, request.boardId);
const board = await new Parse.Query("Board").get(request.boardId, {useMasterKey: true});
if (!board) {
return {status: "Error", description: `Board '${request.boardId}' does not exist`};
}
board.unset("timerUTCEndTime");
await board.save(null, {useMasterKey: true});
return {status: "Success", description: "Timer was successfully removed"};
});
api<{}, string>("getServerTime", async (user, request) => new Date().toUTCString());
};
|
"use strict";
var explorer_openedfolders = ["/"];
$(document).ready(function () {
setInterval(function () {
$("#explorer").height($(window).height() - 20);
}, 10);
setInterval(function () {
reloadExplorer();
}, 1000);
});
async function reloadExplorer() {
var res = await server.getFiles();
var dir = res.working_dir;
var files = res.files;
function generateHTMLTree(key, files) {
function getIcon(file) {
var ending = file.split(".")[file.split(".").length - 1];
switch (ending) {
case "mcscript":
return "/images/explorericons/mcscript.png";
break;
case "mcfunction":
return "/images/explorericons/mcfunction.png";
break;
case "mcmeta":
return "/images/explorericons/mcmeta.png";
break;
default:
return "/images/explorericons/unknown.png";
break;
}
}
var name = key;
if (name.endsWith("/")) name = name.replace(/\/$/, "");
name = name.substring(name.lastIndexOf("/") + 1, name.length);
if (files instanceof Object) {
var ret = "<li class=\"dir\" path=\"" + key + "\"><i class=\"material-icons\">keyboard_arrow_right</i><img src=/images/explorericons/folder.png /><p>" + name + "</p><ul style=\"display: none\">";
for (var k in files) {
ret += generateHTMLTree(key + "/" + k, files[k]);
}
ret += "</ul></li>";
return ret;
} else {
return "<li class=\"file\" path=\"" + files + "\"><img src=\"" + getIcon(files) + "\" /><p>" + name + "</p></li>";
}
}
$("#explorerlist").remove();
$("#explorer").append("<ul id=\"explorerlist\">" + generateHTMLTree(dir, files) + "</p>");
$("#explorer ul li i").click(function (e) {
var path = $(this).parent().attr('path');
if ($(this).text() == "keyboard_arrow_down") {
$(this).parent().children('ul').hide();
$(this).text("keyboard_arrow_right");
explorer_openedfolders.remove(path);
} else {
$(this).parent().children('ul').show();
$(this).text("keyboard_arrow_down");
explorer_openedfolders.push(path);
}
});
$("#explorer .file").click(function () {
var path = $(this).attr('path');
editor.open(path);
});
$("#explorer ul li.dir").each(function () {
if (explorer_openedfolders.includes($(this).attr('path'))) $(this).children('i').trigger('click');
});
/*
$("#explorer ul li:has(i)").click(function(event) {
$(this).children('i').trigger('click');
});*/
} |
<filename>images/tabix.ui/src/app/draw/draw-echarts-map.js
/*
* Licensed under the Apache License, Version 2.0 Copyright 2017 <NAME>,<NAME>,SMI2 LLC and other contributors
*/
'use strict';
class DrawEchartsMap extends DrawEcharts {
loadWorldMapJS() {
if (window.loadWorldMapJSEcharts) return false;
let sc = document.createElement('script');
sc.type = 'text/javascript';
sc.async = false; // SYNCHRONOUSLY
sc.src = 'http://loader.tabix.io/extend/echarts_world_map.js';
sc.charset = 'utf-8';
let s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(sc, s);
window.loadWorldMapJSEcharts=true;
}
create() {
this.loadWorldMapJS();
// Если это код не JS попробуем получить обьект
let drw = this.getDrawCommandObject();
let sets = {
longitude: 'longitude',
latitude: 'latitude',
count: 'count',
name: 'name',
title: 'Map',
destination: {
longitude: 'destination_longitude',
latitude: 'destination_latitude',
speed: 'destination_speed',
name: 'destination_name',
count: 'destination_count'
}
};
let max_value = 0;
if (drw) {
sets = Object.assign(sets, drw);
}
// ---------------------------------------------------------------------------
let seriesScatter = [];
let flySeries = [];
this.data().forEach(function (itemOpt, i) {
let v = parseInt(itemOpt[sets.count]);
if (max_value < v) max_value = v;
if (itemOpt[sets.destination.longitude] && itemOpt[sets.destination.latitude]) {
let toName = '';
if (itemOpt[sets.destination.name]) {
toName = itemOpt[sets.destination.name];
}
flySeries.push({
fromName: itemOpt[sets.name],
toName: toName,
coords: [
[
itemOpt[sets.longitude],
itemOpt[sets.latitude],
],
[
itemOpt[sets.destination.longitude],
itemOpt[sets.destination.latitude]
]]
});
}
seriesScatter.push(
{
name: itemOpt[sets.name],
value: [
itemOpt[sets.longitude],
itemOpt[sets.latitude],
v
],
label: {
emphasis: {
position: 'right',
show: true
}
},
}
);
});
// ---------------------------------------------------------------------------
let series = [
{
name: sets.title,
type: 'effectScatter',
coordinateSystem: 'geo',
data: seriesScatter,
showEffectOn: 'render',
rippleEffect: {
brushType: 'stroke'
},
symbolSize: function (val) {
if (max_value) {
return (val[2] / max_value) * 15;
}
return val[2] / 10000;
},
hoverAnimation: true,
label: {
normal: {
formatter: '{b}',
position: 'right',
show: true
}
},
itemStyle: {
normal: {
color: '#f4e925',
shadowBlur: 10,
shadowColor: '#333'
}
},
zlevel: 1
}
];
// ---------------------------------------------------------------------------
// Fly
// ---------------------------------------------------------------------------
if (flySeries.length > 0) {
let planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z';
series.push(
{
name: sets.title,
type: 'lines',
zlevel: 1,
effect: {
show: true,
period: 6,
trailLength: 0.7,
color: '#fff',
symbolSize: 3
},
lineStyle: {
normal: {
// color: color[i],
width: 0,
curveness: 0.2
}
},
data: flySeries
}
);
//
series.push(
{
name: sets.title,
type: 'lines',
zlevel: 2,
symbol: ['none', 'arrow'],
symbolSize: 10,
effect: {
show: true,
period: 6,
trailLength: 0,
symbol: planePath,
symbolSize: 15
},
lineStyle: {
normal: {
// color: color[i],
width: 1,
opacity: 0.6,
curveness: 0.2
}
},
data: flySeries
}
);//push
}
;//if
// ---------------------------------------------------------------------------
let o = {
tooltip: {
trigger: 'item'
},
// legend: {
// orient: 'vertical',
// top: 'bottom',
// left: 'right',
// data:['data Top10', 'data Top10', 'data Top10'],
// textStyle: {
// color: '#fff'
// },
// selectedMode: 'single'
// },
geo: {
name: sets.title,
type: 'map',
map: 'world',
label: {
emphasis: {
show: false
}
},
visualMap: {
show: true,
min: 0,
max: 100,// max,
inRange: {
symbolSize: [6, 60]
}
},
roam: true,
itemStyle: {
normal: {
areaColor: '#323c48',
borderColor: '#404a59'
},
emphasis: {
areaColor: '#2a333d'
}
}
},
series: series
};
this.options = Object.assign(this.options, o);
return true;
}
} |
function agp() {
echo $AWS_PROFILE
}
# AWS profile selection
function asp() {
if [[ -z "$1" ]]; then
unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE
echo AWS profile cleared.
return
fi
local -a available_profiles
available_profiles=($(aws_profiles))
if [[ -z "${available_profiles[(r)$1]}" ]]; then
echo "${fg[red]}Profile '$1' not found in '${AWS_CONFIG_FILE:-$HOME/.aws/config}'" >&2
echo "Available profiles: ${(j:, :)available_profiles:-no profiles found}${reset_color}" >&2
return 1
fi
export AWS_DEFAULT_PROFILE=$1
export AWS_PROFILE=$1
export AWS_EB_PROFILE=$1
}
# AWS profile switch
function acp() {
if [[ -z "$1" ]]; then
unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
echo AWS profile cleared.
return
fi
local -a available_profiles
available_profiles=($(aws_profiles))
if [[ -z "${available_profiles[(r)$1]}" ]]; then
echo "${fg[red]}Profile '$1' not found in '${AWS_CONFIG_FILE:-$HOME/.aws/config}'" >&2
echo "Available profiles: ${(j:, :)available_profiles:-no profiles found}${reset_color}" >&2
return 1
fi
local profile="$1"
# Get fallback credentials for if the aws command fails or no command is run
local aws_access_key_id="$(aws configure get aws_access_key_id --profile $profile)"
local aws_secret_access_key="$(aws configure get aws_secret_access_key --profile $profile)"
local aws_session_token="$(aws configure get aws_session_token --profile $profile)"
# First, if the profile has MFA configured, lets get the token and session duration
local mfa_serial="$(aws configure get mfa_serial --profile $profile)"
local sess_duration="$(aws configure get duration_seconds --profile $profile)"
if [[ -n "$mfa_serial" ]]; then
local -a mfa_opt
local mfa_token
echo -n "Please enter your MFA token for $mfa_serial: "
read -r mfa_token
if [[ -z "$sess_duration" ]]; then
echo -n "Please enter the session duration in seconds (900-43200; default: 3600, which is the default maximum for a role): "
read -r sess_duration
fi
mfa_opt=(--serial-number "$mfa_serial" --token-code "$mfa_token" --duration-seconds "${sess_duration:-3600}")
# Now see whether we need to just MFA for the current role, or assume a different one
local role_arn="$(aws configure get role_arn --profile $profile)"
local sess_name="$(aws configure get role_session_name --profile $profile)"
if [[ -n "$role_arn" ]]; then
# Means we need to assume a specified role
aws_command=(aws sts assume-role --role-arn "$role_arn" "${mfa_opt[@]}")
# Check whether external_id is configured to use while assuming the role
local external_id="$(aws configure get external_id --profile $profile)"
if [[ -n "$external_id" ]]; then
aws_command+=(--external-id "$external_id")
fi
# Get source profile to use to assume role
local source_profile="$(aws configure get source_profile --profile $profile)"
if [[ -z "$sess_name" ]]; then
sess_name="${source_profile:-profile}"
fi
aws_command+=(--profile="${source_profile:-profile}" --role-session-name "${sess_name}")
echo "Assuming role $role_arn using profile ${source_profile:-profile}"
else
# Means we only need to do MFA
aws_command=(aws sts get-session-token --profile="$profile" "${mfa_opt[@]}")
echo "Obtaining session token for profile $profile"
fi
# Format output of aws command for easier processing
aws_command+=(--query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' --output text)
# Run the aws command to obtain credentials
local -a credentials
credentials=(${(ps:\t:)"$(${aws_command[@]})"})
if [[ -n "$credentials" ]]; then
aws_access_key_id="${credentials[1]}"
aws_secret_access_key="${credentials[2]}"
aws_session_token="${credentials[3]}"
fi
fi
# Switch to AWS profile
if [[ -n "${aws_access_key_id}" && -n "$aws_secret_access_key" ]]; then
export AWS_DEFAULT_PROFILE="$profile"
export AWS_PROFILE="$profile"
export AWS_EB_PROFILE="$profile"
export AWS_ACCESS_KEY_ID="$aws_access_key_id"
export AWS_SECRET_ACCESS_KEY="$aws_secret_access_key"
if [[ -n "$aws_session_token" ]]; then
export AWS_SESSION_TOKEN="$aws_session_token"
else
unset AWS_SESSION_TOKEN
fi
echo "Switched to AWS Profile: $profile"
fi
}
function aws_change_access_key() {
if [[ -z "$1" ]]; then
echo "usage: $0 <profile>"
return 1
fi
echo "Insert the credentials when asked."
asp "$1" || return 1
AWS_PAGER="" aws iam create-access-key
AWS_PAGER="" aws configure --profile "$1"
echo "You can now safely delete the old access key running \`aws iam delete-access-key --access-key-id ID\`"
echo "Your current keys are:"
AWS_PAGER="" aws iam list-access-keys
}
function aws_profiles() {
[[ -r "${AWS_CONFIG_FILE:-$HOME/.aws/config}" ]] || return 1
grep --color=never -Eo '\[.*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | sed -E 's/^[[:space:]]*\[(profile)?[[:space:]]*([-_[:alnum:]\.@]+)\][[:space:]]*$/\2/g'
}
function _aws_profiles() {
reply=($(aws_profiles))
}
compctl -K _aws_profiles asp acp aws_change_access_key
# AWS prompt
function aws_prompt_info() {
[[ -z $AWS_PROFILE ]] && return
echo "${ZSH_THEME_AWS_PREFIX:=<aws:}${AWS_PROFILE}${ZSH_THEME_AWS_SUFFIX:=>}"
}
if [[ "$SHOW_AWS_PROMPT" != false && "$RPROMPT" != *'$(aws_prompt_info)'* ]]; then
RPROMPT='$(aws_prompt_info)'"$RPROMPT"
fi
# Load awscli completions
# AWS CLI v2 comes with its own autocompletion. Check if that is there, otherwise fall back
if command -v aws_completer &> /dev/null; then
autoload -Uz bashcompinit && bashcompinit
complete -C aws_completer aws
else
function _awscli-homebrew-installed() {
# check if Homebrew is installed
(( $+commands[brew] )) || return 1
# speculatively check default brew prefix
if [ -h /usr/local/opt/awscli ]; then
_brew_prefix=/usr/local/opt/awscli
else
# ok, it is not in the default prefix
# this call to brew is expensive (about 400 ms), so at least let's make it only once
_brew_prefix=$(brew --prefix awscli)
fi
}
# get aws_zsh_completer.sh location from $PATH
_aws_zsh_completer_path="$commands[aws_zsh_completer.sh]"
# otherwise check common locations
if [[ -z $_aws_zsh_completer_path ]]; then
# Homebrew
if _awscli-homebrew-installed; then
_aws_zsh_completer_path=$_brew_prefix/libexec/bin/aws_zsh_completer.sh
# Ubuntu
elif [[ -e /usr/share/zsh/vendor-completions/_awscli ]]; then
_aws_zsh_completer_path=/usr/share/zsh/vendor-completions/_awscli
# NixOS
elif [[ -e "${commands[aws]:P:h:h}/share/zsh/site-functions/aws_zsh_completer.sh" ]]; then
_aws_zsh_completer_path="${commands[aws]:P:h:h}/share/zsh/site-functions/aws_zsh_completer.sh"
# RPM
else
_aws_zsh_completer_path=/usr/share/zsh/site-functions/aws_zsh_completer.sh
fi
fi
[[ -r $_aws_zsh_completer_path ]] && source $_aws_zsh_completer_path
unset _aws_zsh_completer_path _brew_prefix
fi
function asr() {
aws_command=(aws sts assume-role --role-arn "$1" --role-session-name sridhartest )
aws_command+=(--query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' --output text)
local -a credentials
credentials=(${(ps:\t:)"$(${aws_command[@]})"})
if [[ -n "$credentials" ]]; then
aws_access_key_id="${credentials[1]}"
aws_secret_access_key="${credentials[2]}"
aws_session_token="${credentials[3]}"
fi
export AWS_ACCESS_KEY_ID="$aws_access_key_id"
export AWS_SECRET_ACCESS_KEY="$aws_secret_access_key"
export AWS_SESSION_TOKEN="$aws_session_token"
}
|
<reponame>zhangfurun/TT
//
// WXAuthRequest.h
// TT
//
// Created by 张福润 on 2017/3/21.
// Copyright © 2017年 张福润. All rights reserved.
//
#import "TTBaseRequest.h"
@interface WXGetAccessTokenRequest : TTBaseRequest
//code
//appid
//secret
@end
@interface WXRefreshAccessTokenRequest : TTBaseRequest
//appid
//refresh_token
@end
@interface WXGetUserInfoReqeust : TTBaseRequest
//access_token
//openid
@end
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[90],{
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=script&lang=js&":
/*!******************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=script&lang=js& ***!
\******************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
props: {
jobid: {
required: true,
type: Number
}
},
data: function data() {
return {
currentPath: '',
stepId: ''
};
},
computed: {
setActiveClassOnJobStep: function setActiveClassOnJobStep() {
return this.$route.matched.some(function (route) {
return route.name === 'job_processing_step_details_job_step_step_details';
}) || this.$route.matched.some(function (route) {
return route.name === 'job_processing_job_steps';
});
}
},
methods: {
loadStepDetails: function loadStepDetails() {
Event.fire('load-first-step-details');
}
},
mounted: function mounted() {
this.currentPath = this.$route.path;
this.stepId = this.$route.params.stepId;
if (this.$route.path === '/') {
this.$router.push({
name: 'job_processing_job_steps',
params: {
jobId: this.jobid
}
});
}
}
});
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=template&id=b2b4915a&":
/*!**********************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=template&id=b2b4915a& ***!
\**********************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c("div", { staticClass: "row" }, [
_c(
"div",
{
staticClass: "col-lg-12 col-xlg-12 col-md-12",
staticStyle: { "border-top": "1px solid #dee2e6" }
},
[
_c("div", { staticClass: "card" }, [
_c(
"ul",
{
staticClass: "nav nav-tabs profile-tab",
attrs: { role: "tablist" }
},
[
_c(
"li",
{
staticClass: "nav-item",
on: {
click: function($event) {
return _vm.loadStepDetails()
}
}
},
[
_c(
"router-link",
{
staticClass: "nav-link",
class: { active: _vm.setActiveClassOnJobStep },
attrs: {
to: {
name: "job_processing_job_steps",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n Job Processing\n "
)
]
)
],
1
),
_vm._v(" "),
_c(
"li",
{ staticClass: "nav-item" },
[
_c(
"router-link",
{
staticClass: "nav-link ",
attrs: {
to: {
name: "job_processing_clients_documents",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n Clients Documents\n "
)
]
)
],
1
),
_vm._v(" "),
_c(
"li",
{ staticClass: "nav-item" },
[
_c(
"router-link",
{
staticClass: "nav-link ",
attrs: {
to: {
name: "job_processing_cargo_images",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n Cargo Images\n "
)
]
)
],
1
),
_vm._v(" "),
_c(
"li",
{ staticClass: "nav-item" },
[
_c(
"router-link",
{
staticClass: "nav-link ",
attrs: {
to: "/job-processing/job-dsr",
to: {
name: "job_processing_job_dsr",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n DSR\n "
)
]
)
],
1
),
_vm._v(" "),
_c(
"li",
{ staticClass: "nav-item" },
[
_c(
"router-link",
{
staticClass: "nav-link ",
attrs: {
to: "/job-processing/job-delivery-docs",
to: {
name: "job_processing_job_delivery_docs",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n Delivery Docs\n "
)
]
)
],
1
),
_vm._v(" "),
_c(
"li",
{ staticClass: "nav-item" },
[
_c(
"router-link",
{
staticClass: "nav-link ",
attrs: {
to: "/job-processing/complete-job",
to: {
name: "job_processing_complete_job",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n Complete\n "
)
]
)
],
1
),
_vm._v(" "),
_c(
"li",
{ staticClass: "nav-item" },
[
_c(
"router-link",
{
staticClass: "nav-link ",
attrs: {
to: "/job-processing/project-cost",
to: {
name: "job_processing_project_cost",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n Project Cost\n "
)
]
)
],
1
),
_vm._v(" "),
_c(
"li",
{ staticClass: "nav-item" },
[
_c(
"router-link",
{
staticClass: "nav-link ",
attrs: {
to: "/job-processing/purchase-order",
to: {
name: "job_processing_purchase_order",
params: { jobId: _vm.jobid }
}
}
},
[
_vm._v(
"\n Purchase Order\n "
)
]
)
],
1
)
]
)
])
]
)
])
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./resources/assets/js/views/JobProcessing/Tab.vue":
/*!*********************************************************!*\
!*** ./resources/assets/js/views/JobProcessing/Tab.vue ***!
\*********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Tab_vue_vue_type_template_id_b2b4915a___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Tab.vue?vue&type=template&id=b2b4915a& */ "./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=template&id=b2b4915a&");
/* harmony import */ var _Tab_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Tab.vue?vue&type=script&lang=js& */ "./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])(
_Tab_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_Tab_vue_vue_type_template_id_b2b4915a___WEBPACK_IMPORTED_MODULE_0__["render"],
_Tab_vue_vue_type_template_id_b2b4915a___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/assets/js/views/JobProcessing/Tab.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=script&lang=js&":
/*!**********************************************************************************!*\
!*** ./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=script&lang=js& ***!
\**********************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Tab_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./Tab.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Tab_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=template&id=b2b4915a&":
/*!****************************************************************************************!*\
!*** ./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=template&id=b2b4915a& ***!
\****************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Tab_vue_vue_type_template_id_b2b4915a___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../node_modules/vue-loader/lib??vue-loader-options!./Tab.vue?vue&type=template&id=b2b4915a& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/assets/js/views/JobProcessing/Tab.vue?vue&type=template&id=b2b4915a&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Tab_vue_vue_type_template_id_b2b4915a___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Tab_vue_vue_type_template_id_b2b4915a___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ })
}]); |
<filename>lib/sunrise/config/has_groups.rb
# frozen_string_literal: true
require 'sunrise/config/group'
module Sunrise
module Config
module HasGroups
# Accessor for a group
#
# If group with given name does not yet exist it will be created. If a
# block is passed it will be evaluated in the context of the group
def group(name, options = nil, &block)
groups[name] ||= Sunrise::Config::Group.new(abstract_model, self, name, options)
groups[name].instance_eval &block if block
groups[name]
end
# Reader for groups
def groups
@groups ||= {}
end
# Reader for groups that are marked as visible
def visible_groups
groups.select { |g| g.visible? }
end
end
end
end
|
/*
* GestorUsuario.java
*
* Created on 10-sep-2007, 20:15:19
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package demo.beans;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author user
*/
public class UsuarioDao {
private static final List<Usuario> usuarios = new ArrayList<Usuario>();
public UsuarioDao() {
}
static {
for (Long i = 0L; i < 5L; i++) {
Usuario u = new Usuario(i, "Nombre" + i, "Clave " + i);
usuarios.add(u);
}
}
public static void rellenarUsuario(Usuario u, Long id) {
if (u == null) {
u = new Usuario(0L, "Sin definir", "Sin definir");
}
for (Usuario usuario : usuarios) {
if (usuario.getId().longValue() == id.longValue()) {
u.setId(usuario.getId());
u.setClave(usuario.getClave());
u.setNombre(usuario.getNombre());
break;
}
}
}
}
|
#! /bin/bash -l
#SBATCH -A b2011141
#SBATCH -p core
#SBATCH -o manhanttan.plot.out
#SBATCH -e manhanttan.plot.err
#SBATCH -J manhanttan.plot.job
#SBATCH -t 12:00:00
Rscript manhanttan.3methods.R
|
-------------------------------------------------------------------------------
-- cms favorite
-------------------------------------------------------------------------------
CREATE TABLE CMS_FAVORITE(
ID BIGINT NOT NULL,
SUBJECT VARCHAR(200),
CREATE_TIME TIMESTAMP,
USER_ID VARCHAR(200),
ARTICLE_ID BIGINT,
COMMENT_ID BIGINT,
CONSTRAINT PK_CMS_FAVORITE PRIMARY KEY(ID),
CONSTRAINT FK_CMS_FAVORITE_ARTICLE FOREIGN KEY(ARTICLE_ID) REFERENCES CMS_ARTICLE(ID),
CONSTRAINT FK_CMS_FAVORITE_COMMENT FOREIGN KEY(COMMENT_ID) REFERENCES CMS_COMMENT(ID)
) ENGINE=INNODB CHARSET=UTF8;
|
USE [DestinationDatabase]
GO
SELECT TOP (10) [OrderID]
,[Comments]
,[CustomerID]
,[SalespersonPersonID]
,[PickedByPersonID]
,[ContactPersonID]
,[BackorderOrderID]
,[OrderDate] -- This column has the 'Mapped' suffix for the first Demo
,[ExpectedDeliveryDate]
,[CustomerPurchaseOrderNumber]
,[IsUndersupplyBackordered]
,[DeliveryInstructions]
,[InternalComments]
,[PickingCompletedWhen]
,[LastEditedBy]
,[LastEditedWhen]
FROM [Sales].[Orders]
ORDER BY OrderID DESC;
/*
-- Use this between demos
USE [DestinationDatabase]
GO
DROP TABLE Sales.Orders;
GO
*/ |
package com.readytalk.swt.util;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class DisplaySafeTest {
@Before
public void initializeEmptyShell() {
// If we don't make a shell, Display will not initialize
new Shell();
}
@Test(expected = DisplaySafe.NullDisplayException.class)
public void getLatestDisplay_CurrentIsNull_DisplayUnchanged() throws DisplaySafe.NullDisplayException {
DisplaySafe safe = new DisplaySafe(null);
DisplaySafe safeSpy = spy(safe);
when(safeSpy.getCurrent()).thenReturn(null);
safeSpy.getLatestDisplay();
}
@Test
public void getLatestDisplay_CurrentIsNull_DisplayChanged() {
DisplaySafe safe = new DisplaySafe(null);
Display display = null;
try {
display = safe.getLatestDisplay();
} catch (DisplaySafe.NullDisplayException nde) {
fail();
}
assertNotNull(display);
}
@Test
public void getLatestDisplay_CurrentNotNull_DisplayUnchanged() {
Display display = Display.getCurrent();
DisplaySafe safe = new DisplaySafe(display);
DisplaySafe safeSpy = spy(safe);
when(safeSpy.getCurrent()).thenReturn(display);
Display sameDisplay = null;
try {
sameDisplay = safeSpy.getLatestDisplay();
} catch (DisplaySafe.NullDisplayException nde) {
fail();
}
assertEquals(display, sameDisplay);
}
@Test
public void getLatestDisplay_CurrentNull_DisplayNotNull() {
DisplaySafe safe = new DisplaySafe(Display.getCurrent());
DisplaySafe safeSpy = spy(safe);
when(safeSpy.getCurrent()).thenReturn(null);
Display display = null;
try {
display = safeSpy.getLatestDisplay();
} catch (DisplaySafe.NullDisplayException nde) {
fail();
}
assertNotNull(display);
}
}
|
// Copyright 2018-2020 Polyaxon, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* tslint:disable */
/* eslint-disable */
/**
* Polyaxon SDKs and REST API specification.
* Polyaxon SDKs and REST API specification.
*
* The version of the OpenAPI document: 1.0.79
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* - model: model - audio: audio - video: vidio - histogram: histogram - image: image - tensor: tensor - dataframe: dataframe - chart: plotly/bokeh chart - csv: Comma - tsv: Tab - psv: Pipe - ssv: Space - metric: Metric - env: Env - html: HTML - text: Text - file: File - dir: Dir - dockerfile: Dockerfile - docker_image: docker image - data: data - coderef: coderef - table: table
* @export
* @enum {string}
*/
export enum V1ArtifactKind {
Model = 'model',
Audio = 'audio',
Video = 'video',
Histogram = 'histogram',
Image = 'image',
Tensor = 'tensor',
Dataframe = 'dataframe',
Chart = 'chart',
Csv = 'csv',
Tsv = 'tsv',
Psv = 'psv',
Ssv = 'ssv',
Metric = 'metric',
Env = 'env',
Html = 'html',
Text = 'text',
File = 'file',
Dir = 'dir',
Dockerfile = 'dockerfile',
DockerImage = 'docker_image',
Data = 'data',
Coderef = 'coderef',
Table = 'table'
}
export function V1ArtifactKindFromJSON(json: any): V1ArtifactKind {
return V1ArtifactKindFromJSONTyped(json, false);
}
export function V1ArtifactKindFromJSONTyped(json: any, ignoreDiscriminator: boolean): V1ArtifactKind {
return json as V1ArtifactKind;
}
export function V1ArtifactKindToJSON(value?: V1ArtifactKind | null): any {
return value as any;
}
|
<gh_stars>0
import api from "../services/api";
export default function useGetCar(carDataDispatch) {
async function handleGetCar(carId) {
await api("GET", `/cars/${carId}`).then((r) => {
carDataDispatch({ type: "SET_CAR_DATA", carData: r });
});
}
return { handleGetCar };
}
|
function maxVal(arr){
return arr.reduce((max, value) => Math.max(max, value), arr[0]);
} |
<reponame>katokido/Yet-Another-React-Kit-Lite<filename>bin/serv.js<gh_stars>0
import path from 'path'
import express from 'express'
import helmet from 'helmet'
import morgan from 'morgan'
import compression from 'compression'
import 'colors'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import config from '../webpack.config.js'
const isProduction = process.env.NODE_ENV === 'production'
const app = express()
const port = 3090
const host = 'localhost'
if (isProduction) {
app.use(helmet())
app.disable('x-powered-by')
app.use(morgan('combined'))
} else {
app.use(morgan('dev'))
}
app.use(compression())
const startListen = () => {
console.log('startListen')
app.listen(port, (err) => {
if (err) {
console.log(`\n${err}`)
}
console.log(`\nExpress: Listening on port ${port}, open up http://${host}:${port}/ \n`.green)
})
}
if (!isProduction) {
// let listend = false
const compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}))
app.use(webpackHotMiddleware(compiler))
app.get('*', (_, res) => {
res.sendFile(path.join(__dirname, '../index.html'))
})
startListen()
} else {
app.use(express.static(path.join(__dirname, '../dist')))
startListen()
}
|
export class UnauthorizedError extends Error {} |
SELECT name, age, salary
FROM Employees
ORDER BY salary DESC; |
public class Birou {
private int lungime;
private int latime;
private int inaltime;
Sertar s1;
Sertar s2;
public Birou(int lungime, int latime, int inaltime, Sertar s1, Sertar s2) {
if (lungime < 0 || lungime > 200)
this.lungime = 120;
else
this.lungime = lungime;
if (latime < 0 || latime > 100)
this.latime = 70;
else
this.latime = latime;
if (inaltime < 0 || inaltime > 100)
this.inaltime = 60;
else
this.inaltime = inaltime;
this.s1 = s1;
this.s2 = s2;
}
public void DisplayBirou() {
System.out.println("Birou = Lungime: " + this.lungime + " Latime: " + this.latime + " Inaltime: " + this.inaltime);
s1.DisplaySertar();
s2.DisplaySertar();
}
} |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Need arguments [host [port [db]]]
THISSERVICE=beeline
export SERVICE_LIST="${SERVICE_LIST}${THISSERVICE} "
beeline () {
CLASS=org.apache.hive.beeline.BeeLine;
# include only the beeline client jar and its dependencies
beelineJarPath=`ls ${HIVE_LIB}/hive-beeline-*.jar`
superCsvJarPath=`ls ${HIVE_LIB}/super-csv-*.jar`
jlineJarPath=`ls ${HIVE_LIB}/jline-*.jar`
jdbcStandaloneJarPath=`ls ${HIVE_LIB}/hive-jdbc-*-standalone.jar`
hadoopClasspath=""
if [[ -n "${HADOOP_CLASSPATH}" ]]
then
hadoopClasspath="${HADOOP_CLASSPATH}:"
fi
export HADOOP_CLASSPATH="${hadoopClasspath}${HIVE_CONF_DIR}:${beelineJarPath}:${superCsvJarPath}:${jlineJarPath}:${jdbcStandaloneJarPath}"
export HADOOP_CLIENT_OPTS="$HADOOP_CLIENT_OPTS -Dlog4j.configuration=beeline-log4j.properties "
exec $HADOOP jar ${beelineJarPath} $CLASS $HIVE_OPTS "$@"
}
beeline_help () {
beeline "--help"
}
|
<gh_stars>0
/**
* @module botbuilder
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { Storage, StoreItems } from './storage';
/**
* Memory based storage provider for a bot.
*
* @remarks
* This provider is most useful for simulating production storage when running locally against the
* emulator or as part of a unit test. It has the following characteristics:
*
* - Starts off completely empty when the bot is run.
* - Anything written to the store will be forgotten when the process exits.
* - Objects that are read and written to the store are cloned to properly simulate network based
* storage providers.
* - Cloned objects are serialized using `JSON.stringify()` to catch any possible serialization
* related issues that might occur when using a network based storage provider.
*
* ```JavaScript
* const { MemoryStorage } = require('botbuilder');
*
* const storage = new MemoryStorage();
* ```
*/
export declare class MemoryStorage implements Storage {
protected memory: {
[k: string]: string;
};
protected etag: number;
/**
* Creates a new MemoryStorage instance.
* @param memory (Optional) memory to use for storing items. By default it will create an empty JSON object `{}`.
*/
constructor(memory?: {
[k: string]: string;
});
/**
* Reads storage items from storage.
* @param keys Keys of the [StoreItems](xref:botbuilder-core.StoreItems) objects to read.
* @returns The read items.
*/
read(keys: string[]): Promise<StoreItems>;
/**
* Writes storage items to storage.
* @param changes The [StoreItems](xref:botbuilder-core.StoreItems) to write, indexed by key.
*/
write(changes: StoreItems): Promise<void>;
/**
* Deletes storage items from storage.
* @param keys Keys of the [StoreItems](xref:botbuilder-core.StoreItems) objects to delete.
*/
delete(keys: string[]): Promise<void>;
}
//# sourceMappingURL=memoryStorage.d.ts.map
|
<gh_stars>0
import React from 'react';
import { Field, ErrorMessage, FormikErrors, FormikTouched } from 'formik';
import { BareProps } from '@polkadot/ui-app/types';
import { nonEmptyStr } from '@polkadot/joy-utils/index';
type FormValuesType = {
[s: string]: string
};
type LabelledProps<FormValues = FormValuesType> = BareProps & {
name?: keyof FormValues,
label?: React.ReactNode,
invisibleLabel?: boolean,
placeholder?: string,
children?: JSX.Element | JSX.Element[],
errors: FormikErrors<FormValues>,
touched: FormikTouched<FormValues>,
isSubmitting: boolean
};
export function LabelledField<FormValues = FormValuesType> () {
return (props: LabelledProps<FormValues>) => {
const { name, label, invisibleLabel = false, touched, errors, children } = props;
const hasError = name && touched[name] && errors[name];
const fieldWithError = <>
<div>{children}</div>
{name && <ErrorMessage name={name as string} component='div' className='ui pointing red label' />}
</>;
return (label || invisibleLabel)
? <div className={`ui--Labelled field ${hasError ? 'error' : ''}`}>
<label htmlFor={name as string}>{nonEmptyStr(label) && label + ':'}</label>
<div className='ui--Labelled-content'>
{fieldWithError}
</div>
</div>
: <div className={`field ${hasError ? 'error' : ''}`}>
{fieldWithError}
</div>;
};
}
export function LabelledText<FormValues = FormValuesType> () {
const LF = LabelledField<FormValues>();
return (props: LabelledProps<FormValues>) => {
const { name, placeholder, className, style, ...otherProps } = props;
const fieldProps = { className, style, name, placeholder };
return <LF name={name} {...otherProps} >
<Field id={name} disabled={otherProps.isSubmitting} {...fieldProps} />
</LF>;
};
}
|
package com.luizfrra.mail.Configurations;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQStartup {
@Bean("emailToSend")
Queue emailToSend() {
return new Queue("emailToSend", true, false, false);
}
@Bean("emailHistory")
Queue emailHistory() {
return new Queue("emailHistory", true, false, false);
}
@Bean
FanoutExchange fanoutExchange() {
return new FanoutExchange("stocksim.email", true, false);
}
@Bean
Binding bindingEmailOne(@Qualifier("emailToSend") Queue queue, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue).to(fanoutExchange);
}
@Bean
Binding bindingEmailTwo(@Qualifier("emailHistory") Queue queue, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue).to(fanoutExchange);
}
}
|
query {
allUsers {
id
name
email
}
} |
import React, { useState } from 'react'
import { KeyboardAvoidingView, StyleSheet } from 'react-native'
import { Text, H1, ListItem, CheckBox, Body, Container, Header, Content, View } from 'native-base'
import { Link, withRouter } from 'react-router-native'
import { connect } from 'react-redux'
import Icon from '../Icon'
function PushNotifications(props) {
const [checked, setChecked] = useState({
all: false,
agendas: false,
private: false,
group: false,
assignments: false,
files: false,
account: false,
donations: false
})
const allCheck = _ => {
if (!checked.all) {
setChecked({
all: true,
agendas: true,
private: true,
group: true,
assignments: true,
files: true,
account: true,
donations: true
})
} else {
setChecked({
all: false,
agendas: false,
private: false,
group: false,
assignments: false,
files: false,
account: false,
donations: false
})
}
}
return (
<View containerAllRoot>
{/*<Link onPress={() => props.history.goBack()} style={styles.link}>*/}
{/* <Icon*/}
{/* name='arrow-back'*/}
{/* color='green'*/}
{/* style={styles.backButton}*/}
{/* />*/}
{/*</Link>*/}
<H1>Push Notifications</H1>
<Container>
<Header />
<Content>
<ListItem>
<CheckBox
checked={checked.all}
onPress={() => {
setChecked({ all: !checked.all })
allCheck()
}}
/>
<Body>
<Text>All Activity</Text>
</Body>
</ListItem>
<ListItem>
<CheckBox
checked={checked.agendas}
onPress={() => setChecked({ ...checked, agendas: !checked.agendas })}
/>
<Body>
<Text>Agendas</Text>
</Body>
</ListItem>
<ListItem>
<CheckBox
checked={checked.private}
onPress={() => setChecked({ ...checked, private: !checked.private })}
/>
<Body>
<Text>Private Discussions</Text>
</Body>
</ListItem>
<ListItem>
<CheckBox
checked={checked.group}
onPress={() => setChecked({ ...checked, group: !checked.group })}
/>
<Body>
<Text>Group Discussions</Text>
</Body>
</ListItem>
<ListItem>
<CheckBox
checked={checked.assignments}
onPress={() => setChecked({ ...checked, assignments: !checked.assignments })}
/>
<Body>
<Text>Assignments</Text>
</Body>
</ListItem>
<ListItem>
<CheckBox
checked={checked.files}
onPress={() => setChecked({ ...checked, files: !checked.files })}
/>
<Body>
<Text>Files</Text>
</Body>
</ListItem>
<ListItem>
<CheckBox
checked={checked.account}
onPress={() => setChecked({ ...checked, account: !checked.account })}
/>
<Body>
<Text>Account</Text>
</Body>
</ListItem>
<ListItem>
<CheckBox
checked={checked.donations}
onPress={() => setChecked({ ...checked, donations: !checked.donations })}
/>
<Body>
<Text>Donations</Text>
</Body>
</ListItem>
</Content>
</Container>
<Link onPress={() => props.history.goBack()}>
<Icon
name='arrow-back'
color='green'
style={styles.backButton}
/>
</Link>
</View>
)
}
const styles = StyleSheet.create({
inputContainer: {
height: '100%',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
link: {
position: 'absolute',
top: 25,
left: 5,
width: '100%',
height: 50
},
backButton: {
fontSize: 50
},
header: {
marginTop: 20
}
})
export default withRouter(PushNotifications)
|
<reponame>kbore/pbis-open
/*
* Copyright (c) BeyondTrust Software. All rights reserved.
*
* Module Name:
*
* LikewiseNegotiateFilter.java
*
* Abstract:
*
* Likewise Authentication
*
* Servlet Filter performing SPNEGO
*
* Authors:
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
*
*/
package com.likewise.auth.filter.spnego;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import javax.security.auth.Subject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.net.util.SubnetUtils;
import com.likewise.auth.LikewiseGroup;
import com.likewise.auth.LikewiseUser;
import com.likewise.interop.AuthenticationAdapter;
import com.likewise.interop.GSSContext;
import com.likewise.interop.GSSResult;
/**
* Servlet authentication filter that provides SPNEGO authentication support as
* per RFC4559 {link http://tools.ietf.org/html/rfc4559}.
* <p>
* If the authentication is successful, the original servlet request is wrapped
* within a LikewiseHttpServletRequestWrapper object.
* </p>
*/
public final class LikewiseNegotiateFilter implements Filter {
private static final String AUTH_METHOD_NEGOTIATE = "Negotiate ";
private static final String AUTH_METHOD_NTLM = "NTLM ";
private static final String SAVED_USER_PRINCIPAL = "LwSavedUserPrincipal";
private static final String SUBJECT = "javax.security.auth.subject";
private static final String GSS_CONTEXT = "likewise-gss-context";
private static final byte[] NTLMSSP_SIGNATURE = {0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00};
private FilterConfig _config;
private Set<String> _allowRoles;
private Set<String> _denyRoles;
private List<SubnetUtils> _ipAddrFilters;
private boolean _debug;
/**
* Initializes the servlet filter.
*
* @param config configuration parameters specified for the filter.
*/
public void init(final FilterConfig config) throws ServletException {
this._config = config;
this.processConfig();
}
/**
* Call sequence in filter chain, where authentication is performed.
*
* @param request Incoming (HTTP) servlet request.
* @param response Outgoing (HTTP) servlet response.
* @param chain Next filter in chain.
*/
public void
doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException
{
ServletRequest requestWrapper = null;
if(this._debug) {
this._config.getServletContext().log("Processing new request ...");
}
if (
(request instanceof HttpServletRequest) &&
(((HttpServletRequest) request).getUserPrincipal() == null) && // Previously authenticated principal
acceptRequest((HttpServletRequest) request)
) {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final HttpSession session = httpRequest.getSession(false);
if(this._debug) {
this._config.getServletContext().log("The request is accepted for session: " + ((session == null) ? null : session.getId()));
}
AuthResults savedResults = null;
if(session != null) {
savedResults = (AuthResults) session.getAttribute(LikewiseNegotiateFilter.SAVED_USER_PRINCIPAL);
}
if(savedResults == null) {
savedResults = new AuthResults();
}
if (!this.authenticate(httpRequest, httpResponse, savedResults)) {
return;
}
if(savedResults.remoteUser == null) {
if(this._debug) {
this._config.getServletContext().log("Authentication failed because savedResults.remoteUser is null");
}
return;
}
if(this._debug) {
this._config.getServletContext().log("Authentication succeeded for user: " + savedResults.remoteUser.getName());
}
requestWrapper = new LikewiseHttpServletRequestWrapper(httpRequest, savedResults.remoteUser, savedResults.roles);
}
chain.doFilter(requestWrapper != null ? requestWrapper : request, response);
}
/**
* Routine to cleanup any state.
*/
public void destroy()
{
this._config = null;
}
/**
* Processes parameters specified in filter configuration.
*/
private void processConfig() {
if (this._config != null) {
final Enumeration<?> params = _config.getInitParameterNames();
while (params.hasMoreElements()) {
final String name = params.nextElement().toString();
final String value = _config.getInitParameter(name);
if (name.equals("allow-role")) {
if (this._allowRoles == null) {
this._allowRoles = new HashSet<String>();
}
this._allowRoles.add(value);
}
else {
if (name.equals("deny-role")) {
if (this._denyRoles == null) {
this._denyRoles = new HashSet<String>();
}
this._denyRoles.add(value);
}
else {
if (name.equals("remote-address-accept-filter"))
{
boolean bAdded = false;
if (this._ipAddrFilters == null) {
this._ipAddrFilters = new ArrayList<SubnetUtils>();
}
try {
final StringTokenizer comp = new StringTokenizer(value, ";");
while (comp.hasMoreElements()) {
String avalue = comp.nextToken().trim();
if (avalue.contains(",")) {
// IP Address, Subnet Mask format
final StringTokenizer tokenizer = new StringTokenizer(avalue, ", ");
final String ipAddress = tokenizer.nextToken();
final String subnetMask = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null;
if (subnetMask != null) {
this._ipAddrFilters.add(new SubnetUtils(ipAddress, subnetMask));
bAdded = true;
}
}
else {
// CIDR format or plain IP Address
this._ipAddrFilters.add(new SubnetUtils(avalue));
bAdded = true;
}
}
}
catch (IllegalArgumentException e) {
}
finally {
if (!bAdded) {
this._config.getServletContext().log(
"Skipping invalid remote-address-accept-filter [" + value + "]"
);
}
}
}
else {
if (name.equalsIgnoreCase("debug")) {
if("true".equalsIgnoreCase(value)) {
this._debug = true;
}
}
}
}
}
}
}
}
/**
* Performs authentication based on the data in the incoming servlet request
* and any session (GSS) state being preserved from earlier call.
*
* @param httpRequest Incoming (HTTP) servlet request.
* @param httpResponse Outgoing (HTTP) servlet response.
* @param savedResults Authentication results
* @return true if the remote principal was successfully authenticated.
*/
private boolean
authenticate(
final HttpServletRequest httpRequest,
final HttpServletResponse httpResponse,
final AuthResults savedResults
)
{
boolean authenticated = false;
HttpSession session = null;
boolean bKeepGssContext = false;
try {
if (savedResults.remoteUser != null) {
final HttpSession ses = httpRequest.getSession(false);
if(this._debug) {
this._config.getServletContext().log("Principal is not null in session: " + ((ses == null) ? null : ses.getId()));
}
if(this.requiresSpecialNTLMAuthorization(httpRequest)) {
if(this._debug) {
this._config.getServletContext().log("This is a POST/PUT request from IE7.");
}
if(ses != null) {
ses.removeAttribute(LikewiseNegotiateFilter.GSS_CONTEXT);
ses.removeAttribute(LikewiseNegotiateFilter.SUBJECT);
}
savedResults.remoteUser = null;
savedResults.roles = null;
return this.authenticate(httpRequest, httpResponse, savedResults);
}
authenticated = true;
}
else {
if(this._debug) {
final HttpSession ses = httpRequest.getSession(false);
this._config.getServletContext().log("Principal is null in session: " + ((ses == null) ? null : ses.getId()));
}
final String authorization = httpRequest.getHeader("Authorization");
if (authorization != null) {
if(this._debug) {
final HttpSession ses = httpRequest.getSession(false);
this._config.getServletContext().log("Authorization header is " + authorization + ". Session ID is " + ((ses == null) ? null : ses.getId()));
}
final Base64 base64Codec = new Base64(-1);
final String authType = this.getAuthType(authorization);
final String authContent = authorization.substring(authType.length());
final byte[] authContentBytes = base64Codec.decode(authContent.getBytes());
if(this._debug) {
this._config.getServletContext().log("authType is " + authType);
this._config.getServletContext().log("authContent is " + authContent);
}
session = httpRequest.getSession(true);
if(this._debug) {
final HttpSession ses = httpRequest.getSession(false);
this._config.getServletContext().log("Session ID is set to " + ((ses == null) ? null : ses.getId()));
}
GSSContext gssContext = (GSSContext) session.getAttribute(LikewiseNegotiateFilter.GSS_CONTEXT);
if (gssContext == null) {
if(this._debug) {
this._config.getServletContext().log("GSS context is not in the session.");
}
gssContext = new GSSContext();
session.setAttribute(LikewiseNegotiateFilter.GSS_CONTEXT, gssContext);
}
final GSSResult gssResult = gssContext.authenticate(authContentBytes);
final byte[] security_blob_out = gssResult.getSecurityBlob();
if (security_blob_out != null) {
if(this._debug) {
this._config.getServletContext().log("Security blob is not null.");
}
final String continueToken = new String(base64Codec.encode(security_blob_out));
httpResponse.addHeader("WWW-Authenticate", authType + continueToken);
}
if (gssResult.isContinueNeeded()) {
if(this._debug) {
this._config.getServletContext().log("Continuation is needed.");
}
httpResponse.setHeader("Connection", "keep-alive");
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.flushBuffer();
bKeepGssContext = true;
}
else {
if(this._debug) {
final HttpSession ses = httpRequest.getSession(false);
this._config.getServletContext().log("Authentication is complete for session " + ((ses == null) ? null : ses.getId()));
}
final String clientPrincipal = gssContext.getClientPrincipal();
final LikewiseUser userPrincipal = AuthenticationAdapter.findUserByName(clientPrincipal);
final List<String> roles = gssContext.getRoles();
if(this._debug) {
this._config.getServletContext().log("clientPrincipal is " + clientPrincipal + ". userPrincipal is " + userPrincipal.getName());
}
if (isAllowed(userPrincipal, roles)) {
if(this._debug) {
this._config.getServletContext().log("The user is allowed to access the content.");
}
Subject subject = (Subject) session.getAttribute(LikewiseNegotiateFilter.SUBJECT);
if (subject == null) {
if(this._debug) {
this._config.getServletContext().log("Subject is not set in the session");
}
subject = new Subject();
session.setAttribute(LikewiseNegotiateFilter.SUBJECT, subject);
}
if (subject.isReadOnly()) {
if(this._debug) {
this._config.getServletContext().log("Subject is read-only");
}
throw new ServletException("subject cannot be read-only");
}
final Set<Principal> principals = subject.getPrincipals();
principals.add(userPrincipal);
for (String role : roles) {
final LikewiseGroup grp = new LikewiseGroup(role);
if(this._debug) {
this._config.getServletContext().log("Adding role " + grp.getName());
}
principals.add(grp);
}
savedResults.remoteUser = userPrincipal;
savedResults.roles = roles;
session.setAttribute(LikewiseNegotiateFilter.SAVED_USER_PRINCIPAL, savedResults);
authenticated = true;
}
else {
if(this._debug) {
this._config.getServletContext().log("The user is not allowed to access the content.");
}
this.sendError(httpResponse, HttpServletResponse.SC_FORBIDDEN);
}
}
}
else {
session = httpRequest.getSession(false);
if(this._debug) {
this._config.getServletContext().log("Authorization header is null in session " + ((session == null) ? null : session.getId()));
}
if (session != null) {
session.removeAttribute(LikewiseNegotiateFilter.GSS_CONTEXT);
}
this.sendUnauthorizedResponse(httpResponse, true);
}
}
}
catch (Exception e) {
this._config.getServletContext().log("Authentication failed (" + this.getClass().getName() + "): " + e.getMessage());
this.sendUnauthorizedResponse(httpResponse, false);
}
finally {
if (!bKeepGssContext && (session != null)) {
if(this._debug) {
this._config.getServletContext().log("Removing GSS context.");
}
session.removeAttribute(LikewiseNegotiateFilter.GSS_CONTEXT);
}
}
return authenticated;
}
private boolean requiresSpecialNTLMAuthorization(final HttpServletRequest httpRequest)
{
boolean result = false;
final String authorization = httpRequest.getHeader("Authorization");
final String httpMethod = httpRequest.getMethod();
if(
(httpMethod != null) &&
(httpMethod.length() != 0) &&
(httpMethod.equals("POST") || httpMethod.equals("PUT")) &&
(httpRequest.getContentLength() == 0) &&
(authorization != null) &&
(authorization.length() != 0)
) {
final Base64 base64Codec = new Base64(-1);
final String authType = this.getAuthType(authorization);
final String authContent = authorization.substring(authType.length());
final byte[] authContentBytes = base64Codec.decode(authContent.getBytes());
if(this._debug) {
this._config.getServletContext().log("In IE7 check: authType is " + authType);
this._config.getServletContext().log("In IE7 check: authContent is " + authContent);
}
if (authContentBytes.length > LikewiseNegotiateFilter.NTLMSSP_SIGNATURE.length) {
boolean signatureMatches = true;
if(this._debug) {
this._config.getServletContext().log("In IE7 check: signature length is OK");
}
for (int i = 0; i < LikewiseNegotiateFilter.NTLMSSP_SIGNATURE.length; i++) {
if (authContentBytes[i] != LikewiseNegotiateFilter.NTLMSSP_SIGNATURE[i]) {
signatureMatches = false;
break;
}
}
if(this._debug) {
this._config.getServletContext().log("In IE7 check: signature matches");
}
if (signatureMatches && (authContentBytes[NTLMSSP_SIGNATURE.length] == 1)) {
if(this._debug) {
this._config.getServletContext().log("In IE7 check: this is Type1 message");
}
result = true;
}
}
}
return result;
}
/**
* Checks the remote IP Address of the request for acceptance to SPNEGO
* authentication using a configured IP Address filter. Checks the
* "X-Forwarded-For" header for the original IP Address set by an
* intermediate proxy server.
*
* @param httpRequest Incoming HTTP Servlet Request
* @return true if the request should be accepted for SPNEGO authentication
*/
private boolean acceptRequest(final HttpServletRequest httpRequest)
{
boolean bAcceptRequest = true;
if ((this._ipAddrFilters != null) && !this._ipAddrFilters.isEmpty()) {
String remoteIpAddr = null;
final String forwardHdr = httpRequest.getHeader("X-Forwarded-For");
// Whether this request was forwarded through a proxy?
// Format of this header is as follows.
// X-Forwarded-For: client1, proxy1, proxy2
if ((forwardHdr != null) && !forwardHdr.trim().equals("")) {
final StringTokenizer tokenizer = new StringTokenizer(forwardHdr, ", ");
remoteIpAddr = tokenizer.nextToken();
}
if ((remoteIpAddr == null) || remoteIpAddr.trim().equals("")) {
remoteIpAddr = httpRequest.getRemoteAddr();
}
bAcceptRequest = false;
for (SubnetUtils filter : this._ipAddrFilters) {
if (filter.getInfo().isInRange(remoteIpAddr)) {
bAcceptRequest = true;
break;
}
}
}
return bAcceptRequest;
}
/**
* Determines the authentication type of the incoming http request based on
* the authorization header.
*
* @param authorization Identifier from the HTTP authorization header.
* @return supported authentication type ("NTLM" or "Negotiate").
*/
private String getAuthType(final String authorization)
{
if (authorization.startsWith(LikewiseNegotiateFilter.AUTH_METHOD_NEGOTIATE)) {
return LikewiseNegotiateFilter.AUTH_METHOD_NEGOTIATE;
}
else {
if (authorization.startsWith(LikewiseNegotiateFilter.AUTH_METHOD_NTLM)) {
return LikewiseNegotiateFilter.AUTH_METHOD_NTLM;
}
else {
if(this._debug) {
this._config.getServletContext().log("Unsupported authentication type [" + authorization + "]");
}
throw new RuntimeException("Unsupported authentication type [" + authorization + "]");
}
}
}
/**
* Builds an unauthorized HTTP response message.
*
* @param httpResponse Outgoing (HTTP) servlet response.
* @param keepAlive Keep the connection alive?
*/
private void sendUnauthorizedResponse(final HttpServletResponse httpResponse, final boolean keepAlive)
{
try {
if(this._debug) {
this._config.getServletContext().log("Sending unauthorized response. keepAlive is " + keepAlive);
}
httpResponse.addHeader("WWW-Authenticate", "Negotiate");
httpResponse.addHeader("WWW-Authenticate", "NTLM");
httpResponse.setHeader("Connection", keepAlive ? "keep-alive" : "close");
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.flushBuffer();
}
catch (IOException e) {
if(this._debug) {
this._config.getServletContext().log("Failed to send unauthorized response: " + e.getMessage());
}
throw new RuntimeException(e);
}
}
/**
* Determines if the specified user principal or roles have been denied or
* approved in that order based on the filter's configuration parameters.
*
* @param remoteUser remote authenticated user principal.
* @param roles list of roles the remote user principal is a member of.
* @return true if the remote user principal has been approved access.
*/
private synchronized boolean isAllowed(final LikewiseUser remoteUser, final List<String> roles)
{
boolean bAllowed = true;
if (this._denyRoles != null) {
if (this._denyRoles.contains(remoteUser.getName())) {
bAllowed = false;
}
else {
for (String role : roles) {
if (this._denyRoles.contains(role)) {
bAllowed = false;
break;
}
}
}
}
if (bAllowed && (this._allowRoles != null)) {
bAllowed = false;
for (String role : roles) {
if (this._allowRoles.contains(role)) {
bAllowed = true;
break;
}
}
}
return bAllowed;
}
/**
* Builds a HTTP error response.
*
* @param httpResponse Outgoing (HTTP) servlet response
* @param status HTTP error status
*/
private void sendError(final HttpServletResponse httpResponse, final int status)
{
try
{
if(this._debug) {
this._config.getServletContext().log("Sending error response.");
}
httpResponse.sendError(status);
}
catch(final IOException e)
{
if(this._debug) {
this._config.getServletContext().log("Failed to send the error response: " + e.getMessage());
}
throw new RuntimeException(e);
}
}
/*
public static void main(String[] args) {
final LikewiseNegotiateFilter filter = new LikewiseNegotiateFilter();
boolean result = false;
String authorization = "Negotiate TlRMTVNTUAABAAAAB4IIogAAAAAAAAAAAAAAAAAAAAAFASgKAAAADw==";
final Base64 base64Codec = new Base64(-1);
final String authType = filter.getAuthType(authorization);
final String authContent = authorization.substring(authType.length());
final byte[] authContentBytes = base64Codec.decode(authContent.getBytes());
if (authContentBytes.length > LikewiseNegotiateFilter.NTLMSSP_SIGNATURE.length) {
boolean signatureMatches = true;
for (int i = 0; i < LikewiseNegotiateFilter.NTLMSSP_SIGNATURE.length; i++) {
if (authContentBytes[i] != LikewiseNegotiateFilter.NTLMSSP_SIGNATURE[i]) {
signatureMatches = false;
break;
}
}
if (signatureMatches && (authContentBytes[LikewiseNegotiateFilter.NTLMSSP_SIGNATURE.length] == 1)) {
result = true;
}
}
System.out.println("Result: " + result);
}
*/
}
class AuthResults {
protected LikewiseUser remoteUser;
protected List<String> roles;
}
|
func pushElementAtEnd(head **ListNode, val int) *ListNode {
newNode := &ListNode{Val: val, Next: nil}
if *head == nil {
// List is empty
*head = newNode
return *head
}
currentNode := *head
for currentNode.Next != nil {
currentNode = currentNode.Next
}
// Add the new node at the end
currentNode.Next = newNode
return *head
} |
<gh_stars>1-10
#ifndef __PHP_PERFORMANCE_METRICS_H__
#define __PHP_PERFORMANCE_METRICS_H__
#ifdef PHP_WIN32
# define PHP_PERFORMANCE_METRICS_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_PERFORMANCE_METRICS_API __attribute__ ((visibility("default")))
#else
# define PHP_PERFORMANCE_METRICS_API
#endif
#ifdef ZTS
# include <TSRM.h>
#endif
#if PHP_VERSION_ID < 50500
# error PHP 5.5.0 or later is required
#endif
#if HAVE_SPL
# include <ext/spl/spl_iterators.h>
# include <ext/spl/spl_exceptions.h>
#else
# error SPL must be enabled in order to build the driver
#endif
#define PHP_PERFORMANCE_METRICS_NAME "Performance Metrics"
#define PHP_PERFORMANCE_METRICS_VERSION "0.0.1"
extern zend_module_entry performance_metrics_module_entry;
#define phpext_performance_metrics_ptr &performance_metrics_module_entry
#include "php_5to7_macros.h"
#include "hdr_histogram.h"
#include "ewma.h"
/* Macro definitions to create an object for the module */
#if PHP_VERSION_ID >= 70000
# define PHP_PERFORMANCE_METRICS_BEGIN_OBJECT(type_name) typedef struct _php_performance_metrics_##type_name##_ {
# define PHP_PERFORMANCE_METRICS_END_OBJECT(type_name) zend_object zval; \
} type_name; \
\
static inline type_name* php_##type_name##_object_fetch(zend_object *obj) { \
return (type_name*) ((char*) obj - XtOffsetOf(type_name, zval)); \
}
#else
# define PHP_PERFORMANCE_METRICS_BEGIN_OBJECT(type_name) typedef struct _php_performance_metrics_##type_name##_ { \
zend_object zval;
# define PHP_PERFORMANCE_METRICS_END_OBJECT(type_name) } type_name;
#endif
/* Marco definition to simplify getting the metrics data */
#define PHP_PERFORMANCE_METRICS_GET_METRICS(self, metrics) \
self = PHP_PERFORMANCE_METRICS_GET_PERFORMANCE_METRICS(getThis()); \
if (!self->metrics) { \
zend_throw_exception_ex( \
spl_ce_RuntimeException, \
0 TSRMLS_CC, \
"Metrics data is not valid (NULL)" \
); \
} \
metrics = self->metrics;
#define PHP_PERFORMANCE_METRICS_GET_METRICS_AND_HDR(self, metrics, hdr) \
PHP_PERFORMANCE_METRICS_GET_METRICS(self, metrics) \
if (!metrics->hdr) { \
zend_throw_exception_ex( \
spl_ce_RuntimeException, \
0 TSRMLS_CC, \
"HDR histogram data is not valid (NULL)" \
); \
} \
hdr = metrics->hdr;
/* PHP base extension/module functions */
PHP_MINIT_FUNCTION(performance_metrics);
PHP_MINFO_FUNCTION(performance_metrics);
/* Global extension functions */
PHP_FUNCTION(persistent_performance_metrics_count);
/* Globals */
ZEND_BEGIN_MODULE_GLOBALS(performance_metrics)
php_size_t persistent_performance_metrics;
ZEND_END_MODULE_GLOBALS(performance_metrics)
#if PHP_VERSION_ID >= 70000
# define PERFORMANCE_METRICS_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(performance_metrics, v)
#else
# ifdef ZTS
# define PERFORMANCE_METRICS_G(v) TSRMG(performance_metrics_globals_id, zend_performance_metrics_globals*, v)
# else
# define PERFORMANCE_METRICS_G(v) (performance_metrics_globals.v)
# endif
#endif
#if defined(ZTS) && defined(COMPILE_DL_PERFORMANCE_METRICS)
ZEND_TSRMLS_CACHE_EXTERN()
#endif
/**
* Internal structure for gathering latencies and metered rate metrics
*/
typedef struct _performance_metrics_Metrics {
/**
* Mutex for ensuring synchronization
*/
hdr_mutex mutex;
/**
* HDR histogram instance
*/
struct hdr_histogram* hdr;
/**
* Time the metrics were last "ticked"
*/
uint64_t last_tick;
/**
* Time the metrics were started
*/
uint64_t start_time;
/**
* 1 minute rate (per second)
*/
Meter m1_rate;
/**
* 5 minute rate (per second)
*/
Meter m5_rate;
/**
* 15 minute rate (per second)
*/
Meter m15_rate;
} Metrics;
/**
* Persistent metrics resource
*/
static int le_performance_metrics_persistent_res;
/* PHP PerformanceMetrics internal structure */
PHP_PERFORMANCE_METRICS_BEGIN_OBJECT(PerformanceMetrics)
char* name;
php_size_t name_length;
Metrics* metrics;
PHP_PERFORMANCE_METRICS_END_OBJECT(PerformanceMetrics)
#if PHP_VERSION_ID >= 70000
# define PHP_PERFORMANCE_METRICS_GET_PERFORMANCE_METRICS(obj) php_PerformanceMetrics_object_fetch(Z_OBJ_P(obj))
#else
# define PHP_PERFORMANCE_METRICS_GET_PERFORMANCE_METRICS(obj) (PerformanceMetrics*) zend_object_store_get_object((obj) TSRMLS_CC)
#endif
/**
* PHP PerformanceMetrics class definition
*/
static zend_class_entry *php_PerformanceMetrics_ce;
/**
* PHP PerformanceMetrics class handlers
*/
static zend_object_handlers php_PerformanceMetrics_handlers;
/* PHP PerformanceMetrics helper functions */
static void define_PerformanceMetrics(TSRMLS_D);
static void php_PerformanceMetrics_dtor(php_zend_resource resource TSRMLS_DC);
static void php_PerformanceMetrics_free(php_zend_object_free *object TSRMLS_DC);
static php_zend_object php_PerformanceMetrics_new(zend_class_entry *ce TSRMLS_DC);
/* PerformanceMetrics class methods */
PHP_METHOD(PerformanceMetrics, __construct);
PHP_METHOD(PerformanceMetrics, elapsed_time);
PHP_METHOD(PerformanceMetrics, metrics);
PHP_METHOD(PerformanceMetrics, name);
PHP_METHOD(PerformanceMetrics, observe);
PHP_METHOD(PerformanceMetrics, start_timer);
PHP_METHOD(PerformanceMetrics, stop_timer);
PHP_METHOD(PerformanceMetrics, tick_rates);
#endif /* PHP_PERFORMANCE_METRICS_H */
|
<reponame>RenukaGurumurthy/Gooru-Core-API
/////////////////////////////////////////////////////////////
// UserEventlog.java
// gooru-api
// Created by Gooru on 2015
// Copyright (c) 2015 Gooru. All rights reserved.
// http://www.goorulearning.org/
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/////////////////////////////////////////////////////////////
package org.ednovo.gooru.domain.service.eventlogs;
import java.util.Iterator;
import org.ednovo.gooru.core.api.model.Identity;
import org.ednovo.gooru.core.api.model.SessionContextSupport;
import org.ednovo.gooru.core.api.model.User;
import org.ednovo.gooru.core.constant.ConstantProperties;
import org.ednovo.gooru.core.constant.ParameterProperties;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class UserEventLog implements ParameterProperties, ConstantProperties{
private static final Logger LOGGER = LoggerFactory.getLogger(UserEventLog.class);
public void getEventLogs(boolean updateProfile, boolean visitProfile, User profileVisitor, JSONObject itemData, boolean isFollow, boolean isUnfollow) {
try {
SessionContextSupport.putLogParameter(EVENT_NAME, PROFILE_ACTION);
JSONObject session = SessionContextSupport.getLog().get(SESSION) != null ? new JSONObject(SessionContextSupport.getLog().get(SESSION).toString()) : new JSONObject();
SessionContextSupport.putLogParameter(SESSION, session.toString());
JSONObject user = SessionContextSupport.getLog().get(USER) != null ? new JSONObject(SessionContextSupport.getLog().get(USER).toString()) : new JSONObject();
SessionContextSupport.putLogParameter(USER, user.toString());
JSONObject context = SessionContextSupport.getLog().get(CONTEXT) != null ? new JSONObject(SessionContextSupport.getLog().get(CONTEXT).toString()) : new JSONObject();
if (updateProfile) {
context.put("url", "/profile/edit");
} else if (visitProfile) {
context.put("url", "/profile/visit");
}
SessionContextSupport.putLogParameter(CONTEXT, context.toString());
JSONObject payLoadObject = SessionContextSupport.getLog().get(PAY_LOAD_OBJECT) != null ? new JSONObject(SessionContextSupport.getLog().get(PAY_LOAD_OBJECT).toString()) : new JSONObject();
if (updateProfile) {
payLoadObject.put(ACTION_TYPE, EDIT);
} else if (visitProfile) {
payLoadObject.put(ACTION_TYPE, VISIT);
payLoadObject.put(VISIT_UID, profileVisitor != null ? profileVisitor.getPartyUid() : null);
} else if (isFollow) {
payLoadObject.put(ACTION_TYPE, FOLLOW);
} else if (isUnfollow) {
payLoadObject.put(ACTION_TYPE, UN_FOLLOW);
}
if (itemData != null) {
payLoadObject.put("itemData", itemData.toString());
}
SessionContextSupport.putLogParameter(PAY_LOAD_OBJECT, payLoadObject.toString());
} catch (Exception e) {
LOGGER.error(_ERROR , e);
}
}
public void getEventLogs(User newUser, String source, Identity newIdentity) throws JSONException {
SessionContextSupport.putLogParameter(EVENT_NAME, USER_REG);
JSONObject context = SessionContextSupport.getLog().get(CONTEXT) != null ? new JSONObject(SessionContextSupport.getLog().get(CONTEXT).toString()) : new JSONObject();
if (source != null) {
context.put(REGISTER_TYPE, source);
} else {
context.put(REGISTER_TYPE, GOORU);
}
SessionContextSupport.putLogParameter(CONTEXT, context.toString());
JSONObject payLoadObject = SessionContextSupport.getLog().get(PAY_LOAD_OBJECT) != null ? new JSONObject(SessionContextSupport.getLog().get(PAY_LOAD_OBJECT).toString()) : new JSONObject();
if (newIdentity != null && newIdentity.getIdp() != null) {
payLoadObject.put(IDP_NAME, newIdentity.getIdp().getName());
} else {
payLoadObject.put(IDP_NAME, GOORU_API);
}
Iterator<Identity> iter = newUser.getIdentities().iterator();
if (iter != null && iter.hasNext()) {
Identity identity = iter.next();
payLoadObject.put(CREATED_TYPE, identity != null ? identity.getAccountCreatedType() : null);
}
SessionContextSupport.putLogParameter(PAY_LOAD_OBJECT, payLoadObject.toString());
JSONObject session = SessionContextSupport.getLog().get(SESSION) != null ? new JSONObject(SessionContextSupport.getLog().get(SESSION).toString()) : new JSONObject();
session.put(ORGANIZATION_UID, newUser != null && newUser.getOrganization() != null ? newUser.getOrganization().getPartyUid() : null);
SessionContextSupport.putLogParameter(SESSION, session.toString());
JSONObject user = SessionContextSupport.getLog().get(USER) != null ? new JSONObject(SessionContextSupport.getLog().get(USER).toString()) : new JSONObject();
user.put(GOORU_UID, newUser != null ? newUser.getPartyUid() : null);
SessionContextSupport.putLogParameter(USER, user.toString());
}
}
|
module C {
// Flocking and movement constants
export var NEIGHBOR_RADIUS = 50;
export var BASE_SPEED = 1.5;
// Boid-specific movement and size
export var PREY_RADIUS = 2;
export var PREY_MAX_FORCE = 0.03;
export var PREY_SPEED_FACTOR = 1;
export var PREDATOR_RADIUS = 5;
export var PREDATOR_MAX_FORCE = 0.03;
export var PREDATOR_SPEED_FACTOR = 1.15;
// Population control variables (most interesting to modify)
export var PREY_STARTING_FOOD = 300;
export var PREY_FOOD_PER_STEP = 0.53;
export var PREY_ENERGY_FOR_REPRODUCTION = 300;
export var PREY_TURNS_TO_REPRODUCE = 500;
export var PREY_AGE_FACTOR = 0.97;
export var PREDATOR_STARTING_FOOD = 1200;
export var PREDATOR_FOOD_PER_STEP = 2;
export var PREDATOR_FOOD_PER_PREY = 500;
export var PREDATOR_KILLS_FOR_REPRODUCTION = 7;
export var PREDATOR_TURNS_TO_REPRODUCE = 1000;
export var PREDATOR_AGE_FACTOR = 0.995;
export var PREDATOR_ENERGY_FOR_REPRODUCTION = PREDATOR_FOOD_PER_PREY * PREDATOR_KILLS_FOR_REPRODUCTION;
export var FOOD_STARTING_LEVEL = 1;
export var FOOD_STEPS_TO_REGEN = 8000;
export var MAXBoidS = 300;
export var COORDINATES_3D = false;
export var WEIGHT_MUTATION_CONSTANT = 0.2;
export var RADIUS_MUTATION_CONSTANT = 0.5;
export var COLOR_MUTATION_CONSTANT = 10;
export var CONSUMPTION_TIME = 30; // time a predator needs to eat its food
export var MIN_NUM_PREDATORS = 0; // predators will not die if few are left alive
export var FOOD_GRAZED_PER_STEP = 0.33; // what proportion of max food on tile is eaten each step?
} |
def find_pairs_with_sum(nums, target):
result = []
seen = set()
for num in nums:
if (target - num) in seen:
result.append([num, target-num])
seen.add(num)
return result
nums = [1,2,3,4,5]
target = 4
result = find_pairs_with_sum(nums, target)
print(result) |
Anomaly detection algorithms typically utilize clustering algorithms such as K-means, DBSCAN, OPTICS or SOM to identify clusters of similar transactions which can then used as a baseline against which to compare any new transactions. Any unseen transactions which lie outside of the specified clusters are indicative of anomalies and can be flagged for further investigation. |
class ClassName
{
const UNDEFINED = null;
public $node;
public $__typename;
public static function makeInstance($node): self
{
$instance = new self;
if ($node !== self::UNDEFINED) {
$instance->node = $node;
}
$instance->__typename = 'Query';
return $instance;
}
} |
<reponame>tarasowski/vscode-tailwindcss<gh_stars>10-100
const _ = require('lodash')
const { workspace } = require('vscode')
const { readFile } = require('fs')
const { promisify } = require('util')
const readFileAsync = promisify(readFile)
const requireFromString = require('../utils/require-from-string')
const tailwindStaticClasses = require('./static-classes')
const generateDynamicClasses = require('./dynamic-classes')
async function generateClasses() {
// Some classes are static and do not need to be generated
// whereas some need to be generated dynamically after reading the config file
const staticClasses = tailwindStaticClasses
// Find configuration file in the workspace
let configurationFileResults, configurationFilePath, configFileString
try {
configurationFileResults = await workspace.findFiles(
'tailwind.js',
'**/node_modules/**'
)
configurationFilePath = configurationFileResults[0].fsPath
configFileString = await readFileAsync(configurationFilePath, 'utf8')
} catch (error) {
// There's probably no config file present, assuming this project doesn't use tailwind and bailing
console.log(
"There's no config file present, assuming this project doesn't use tailwind and bailing",
error
)
return []
}
const config = requireFromString(configFileString, configurationFilePath)
const dynamicClasses = await generateDynamicClasses(config)
// Return all classes, combined
return _.concat(staticClasses, dynamicClasses)
}
module.exports = generateClasses
|
#!/bin/bash
#
##############################################################################
#
# Fetch timestamp and image from a configurable URL.
cd "$(dirname "$0")"
# load configuration
if [ -e "config.sh" ]; then
source config.sh
else
TMPFILE=/tmp/tmp.jerrypic.png
fi
# load utils
if [ -e "utils.sh" ]; then
source utils.sh
else
echo "Could not find utils.sh in `pwd`"
exit
fi
# load jerrypic logic
if [ -e "jerrypic.sh" ]; then
source jerrypic.sh
else
echo "Could not find jerrypic.sh in `pwd`"
exit
fi
# enable wireless if it is currently off
if [ 0 -eq `lipc-get-prop com.lab126.cmd wirelessEnable` ]; then
logger "wiFi is off, turning it on now"
lipc-set-prop com.lab126.cmd wirelessEnable 1
DISABLE_WIFI=1
fi
# wait for network to be up
TIMER=${NETWORK_TIMEOUT} # number of seconds to attempt a connection
CONNECTED=0 # whether we are currently connected
while [ 0 -eq $CONNECTED ]; do
# test whether we can ping outside
/bin/ping -c 1 $TEST_DOMAIN > /dev/null && CONNECTED=1
# if we can't, checkout timeout or sleep for 1s
if [ 0 -eq $CONNECTED ]; then
TIMER=$(($TIMER-1))
if [ 0 -eq $TIMER ]; then
logger "No internet connection after ${NETWORK_TIMEOUT} seconds, aborting."
break
else
sleep 1
fi
fi
done
if [ 1 -eq $CONNECTED ]; then
compare=0
remoteTimestamp=$(readRemoteTimestamp)
if [ -z "$remoteTimestamp" ]; then
logger "can't load remote timestamp"
else
localTimestamp=$(readLocalTimestamp)
compare=$(needsToUpdate ${remoteTimestamp} ${localTimestamp})
storeTimestamp ${remoteTimestamp}
fi
if [ 1 -eq $compare ]; then
logger "needs to update"
echo load from ${IMAGE_URL}
if curl $IMAGE_URL -o $TMPFILE; then
mv $TMPFILE $SCREENSAVERFILE
logger "screen saver image updated"
# refresh screen
lipc-get-prop com.lab126.powerd status | grep "Screen Saver" && (
logger "updating image on screen"
eips -g $SCREENSAVERFILE
)
else
logger "error updating screensaver"
if [ 1 -eq $DONOTRETRY ]; then
touch $SCREENSAVERFILE
fi
fi
else
logger "no need to update"
fi
fi
# disable wireless if necessary
if [ 1 -eq $DISABLE_WIFI ]; then
logger "Disabling WiFi"
lipc-set-prop com.lab126.cmd wirelessEnable 0
fi
|
export const ROOM_SOCKET = {
ROOM_SEND_MESSAGE: 'roomSendMessage',
ROOM_NEW_MESSAGE: 'roomNewMessage',
JOIN_ROOM: 'joinRoom',
SEND_ROOM_DELETE_MESSAGE: 'sendRoomDeleteMessage',
ROOM_DELETE_MESSAGE: 'roomDeleteMessage',
ROOM_SEND_EDIT_MESSAGE: 'roomSendEditMessage',
ROOM_EDIT_MESSAGE: 'roomEditMessage',
}
export const ME_SOCKET = {
ONLINE: 'online',
SEND_FRIEND_REQUEST: 'sendFriendRequest',
SEND_ACCEPT_FRIEND_REQUEST: 'sendFriendAcceptRequest',
LOGOUT: 'logOut',
}
|
package cyclops.container.immutable.tuple;
import cyclops.container.immutable.impl.HashMap;
import cyclops.container.transformable.To;
import cyclops.function.cacheable.Memoize;
import cyclops.function.companion.Comparators;
import cyclops.function.enhanced.Function8;
import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
/*
A Tuple implementation that can be lazyEither eager / strict or lazy
*/
public class Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> implements To<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>>, Serializable,
Comparable<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>> {
private static final long serialVersionUID = 1L;
private final T1 _1;
private final T2 _2;
private final T3 _3;
private final T4 _4;
private final T5 _5;
private final T6 _6;
private final T7 _7;
private final T8 _8;
public Tuple8(T1 t1,
T2 t2,
T3 t3,
T4 t4,
T5 t5,
T6 t6,
T7 t7,
T8 t8) {
_1 = t1;
_2 = t2;
_3 = t3;
_4 = t4;
_5 = t5;
_6 = t6;
_7 = t7;
_8 = t8;
}
public static <T1, T2, T3, T4, T5, T6, T7, T8> Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> of(T1 value1,
T2 value2,
T3 value3,
T4 value4,
T5 value5,
T6 value6,
T7 value7,
T8 value8) {
return new Tuple8<>(value1,
value2,
value3,
value4,
value5,
value6,
value7,
value8);
}
public static <T1, T2, T3, T4, T5, T6, T7, T8> Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> lazy(Supplier<? extends T1> supplier1,
Supplier<? extends T2> supplier2,
Supplier<? extends T3> supplier3,
Supplier<? extends T4> supplier4,
Supplier<? extends T5> supplier5,
Supplier<? extends T6> supplier6,
Supplier<? extends T7> supplier7,
Supplier<? extends T8> supplier8) {
return new Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>(null,
null,
null,
null,
null,
null,
null,
null) {
@Override
public T1 _1() {
return supplier1.get();
}
@Override
public T2 _2() {
return supplier2.get();
}
@Override
public T3 _3() {
return supplier3.get();
}
@Override
public T4 _4() {
return supplier4.get();
}
@Override
public T5 _5() {
return supplier5.get();
}
@Override
public T6 _6() {
return supplier6.get();
}
@Override
public T7 _7() {
return supplier7.get();
}
@Override
public T8 _8() {
return supplier8.get();
}
};
}
public T1 _1() {
return _1;
}
public T2 _2() {
return _2;
}
public T3 _3() {
return _3;
}
public T4 _4() {
return _4;
}
public T5 _5() {
return _5;
}
public T6 _6() {
return _6;
}
public T7 _7() {
return _7;
}
public T8 _8() {
return _8;
}
public Tuple1<T1> first() {
return Tuple.tuple(_1());
}
public Tuple1<T2> second() {
return Tuple.tuple(_2());
}
public Tuple1<T3> third() {
return Tuple.tuple(_3());
}
public Tuple1<T4> fourth() {
return Tuple.tuple(_4());
}
public Tuple1<T5> fifth() {
return Tuple.tuple(_5());
}
public Tuple1<T6> sixth() {
return Tuple.tuple(_6());
}
public Tuple1<T7> seventh() {
return Tuple.tuple(_7());
}
public Tuple1<T8> eighth() {
return Tuple.tuple(_8());
}
@Override
public int compareTo(Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> o) {
int result = Comparators.naturalOrderIdentityComparator()
.compare(_1(),
o._1());
if (result == 0) {
result = Comparators.naturalOrderIdentityComparator()
.compare(_2(),
o._2());
if (result == 0) {
result = Comparators.naturalOrderIdentityComparator()
.compare(_3(),
o._3());
if (result == 0) {
result = Comparators.naturalOrderIdentityComparator()
.compare(_4(),
o._4());
if (result == 0) {
result = Comparators.naturalOrderIdentityComparator()
.compare(_5(),
o._5());
if (result == 0) {
result = Comparators.naturalOrderIdentityComparator()
.compare(_6(),
o._6());
if (result == 0) {
result = Comparators.naturalOrderIdentityComparator()
.compare(_7(),
o._7());
if (result == 0) {
result = Comparators.naturalOrderIdentityComparator()
.compare(_8(),
o._8());
}
}
}
}
}
}
}
return result;
}
public <R1> R1 transform(Function8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R1> fn) {
return fn.apply(_1(),
_2(),
_3(),
_4(),
_5(),
_6(),
_7(),
_8());
}
public Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> eager() {
return of(_1(),
_2(),
_3(),
_4(),
_5(),
_6(),
_7(),
_8());
}
public Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> memo() {
Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> host = this;
return new Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>(null,
null,
null,
null,
null,
null,
null,
null) {
final Supplier<T1> memo1 = Memoize.memoizeSupplier(host::_1);
final Supplier<T2> memo2 = Memoize.memoizeSupplier(host::_2);
final Supplier<T3> memo3 = Memoize.memoizeSupplier(host::_3);
final Supplier<T4> memo4 = Memoize.memoizeSupplier(host::_4);
final Supplier<T5> memo5 = Memoize.memoizeSupplier(host::_5);
final Supplier<T6> memo6 = Memoize.memoizeSupplier(host::_6);
final Supplier<T7> memo7 = Memoize.memoizeSupplier(host::_7);
final Supplier<T8> memo8 = Memoize.memoizeSupplier(host::_8);
@Override
public T1 _1() {
return memo1.get();
}
@Override
public T2 _2() {
return memo2.get();
}
@Override
public T3 _3() {
return memo3.get();
}
@Override
public T4 _4() {
return memo4.get();
}
@Override
public T5 _5() {
return memo5.get();
}
@Override
public T6 _6() {
return memo6.get();
}
@Override
public T7 _7() {
return memo7.get();
}
@Override
public T8 _8() {
return memo8.get();
}
};
}
public <R1, R2, R3, R4, R5, R6, R7, R8> Tuple8<R1, R2, R3, R4, R5, R6, R7, R8> mapAll(Function<? super T1, ? extends R1> fn1,
Function<? super T2, ? extends R2> fn2,
Function<? super T3, ? extends R3> fn3,
Function<? super T4, ? extends R4> fn4,
Function<? super T5, ? extends R5> fn5,
Function<? super T6, ? extends R6> fn6,
Function<? super T7, ? extends R7> fn7,
Function<? super T8, ? extends R8> fn8) {
return of(fn1.apply(_1()),
fn2.apply(_2()),
fn3.apply(_3()),
fn4.apply(_4()),
fn5.apply(_5()),
fn6.apply(_6()),
fn7.apply(_7()),
fn8.apply(_8()));
}
public <R1, R2, R3, R4, R5, R6, R7, R8> Tuple8<R1, R2, R3, R4, R5, R6, R7, R8> lazyMapAll(Function<? super T1, ? extends R1> fn1,
Function<? super T2, ? extends R2> fn2,
Function<? super T3, ? extends R3> fn3,
Function<? super T4, ? extends R4> fn4,
Function<? super T5, ? extends R5> fn5,
Function<? super T6, ? extends R6> fn6,
Function<? super T7, ? extends R7> fn7,
Function<? super T8, ? extends R8> fn8) {
return lazy(() -> (fn1.apply(_1())),
() -> fn2.apply(_2()),
() -> fn3.apply(_3()),
() -> fn4.apply(_4()),
() -> fn5.apply(_5()),
() -> fn6.apply(_6()),
() -> fn7.apply(_7()),
() -> fn8.apply(_8()));
}
public <R> Tuple8<R, T2, T3, T4, T5, T6, T7, T8> map1(Function<? super T1, ? extends R> fn) {
return of(fn.apply(_1()),
_2(),
_3(),
_4(),
_5(),
_6(),
_7(),
_8());
}
public <R> Tuple8<R, T2, T3, T4, T5, T6, T7, T8> lazyMap1(Function<? super T1, ? extends R> fn) {
return lazy(() -> fn.apply(_1()),
() -> _2(),
() -> _3(),
() -> _4(),
() -> _5(),
() -> _6(),
() -> _7(),
() -> _8());
}
public <R> Tuple8<T1, R, T3, T4, T5, T6, T7, T8> map2(Function<? super T2, ? extends R> fn) {
return of(_1(),
fn.apply(_2()),
_3(),
_4(),
_5(),
_6(),
_7(),
_8());
}
public <R> Tuple8<T1, R, T3, T4, T5, T6, T7, T8> lazyMap2(Function<? super T2, ? extends R> fn) {
return lazy(() -> _1(),
() -> fn.apply(_2()),
() -> _3(),
() -> _4(),
() -> _5(),
() -> _6(),
() -> _7(),
() -> _8());
}
public <R> Tuple8<T1, T2, R, T4, T5, T6, T7, T8> map3(Function<? super T3, ? extends R> fn) {
return of(_1(),
_2(),
fn.apply(_3()),
_4(),
_5(),
_6(),
_7(),
_8());
}
public <R> Tuple8<T1, T2, R, T4, T5, T6, T7, T8> lazyMap3(Function<? super T3, ? extends R> fn) {
return lazy(() -> _1(),
() -> _2(),
() -> fn.apply(_3()),
() -> _4(),
() -> _5(),
() -> _6(),
() -> _7(),
() -> _8());
}
public <R> Tuple8<T1, T2, T3, R, T5, T6, T7, T8> map4(Function<? super T4, ? extends R> fn) {
return of(_1(),
_2(),
_3(),
fn.apply(_4()),
_5(),
_6(),
_7(),
_8());
}
public <R> Tuple8<T1, T2, T3, R, T5, T6, T7, T8> lazyMap4(Function<? super T4, ? extends R> fn) {
return lazy(() -> _1(),
() -> _2(),
() -> _3(),
() -> fn.apply(_4()),
() -> _5(),
() -> _6(),
() -> _7(),
() -> _8());
}
public <R> Tuple8<T1, T2, T3, T4, R, T6, T7, T8> map5(Function<? super T5, ? extends R> fn) {
return of(_1(),
_2(),
_3(),
_4(),
fn.apply(_5()),
_6(),
_7(),
_8());
}
public <R> Tuple8<T1, T2, T3, T4, R, T6, T7, T8> lazyMap5(Function<? super T5, ? extends R> fn) {
return lazy(() -> _1(),
() -> _2(),
() -> _3(),
() -> _4(),
() -> fn.apply(_5()),
() -> _6(),
() -> _7(),
() -> _8());
}
public <R> Tuple8<T1, T2, T3, T4, T5, R, T7, T8> map6(Function<? super T6, ? extends R> fn) {
return of(_1(),
_2(),
_3(),
_4(),
_5(),
fn.apply(_6()),
_7(),
_8());
}
public <R> Tuple8<T1, T2, T3, T4, T5, R, T7, T8> lazyMap6(Function<? super T6, ? extends R> fn) {
return lazy(() -> _1(),
() -> _2(),
() -> _3(),
() -> _4(),
() -> _5(),
() -> fn.apply(_6()),
() -> _7(),
() -> _8());
}
public <R> Tuple8<T1, T2, T3, T4, T5, T6, R, T8> map7(Function<? super T7, ? extends R> fn) {
return of(_1(),
_2(),
_3(),
_4(),
_5(),
_6(),
fn.apply(_7()),
_8());
}
public <R> Tuple8<T1, T2, T3, T4, T5, T6, R, T8> lazyMap7(Function<? super T7, ? extends R> fn) {
return lazy(() -> _1(),
() -> _2(),
() -> _3(),
() -> _4(),
() -> _5(),
() -> _6(),
() -> fn.apply(_7()),
() -> _8());
}
public <R> Tuple8<T1, T2, T3, T4, T5, T6, T7, R> map8(Function<? super T8, ? extends R> fn) {
return of(_1(),
_2(),
_3(),
_4(),
_5(),
_6(),
_7(),
fn.apply(_8()));
}
public <R> Tuple8<T1, T2, T3, T4, T5, T6, T7, R> lazyMap8(Function<? super T8, ? extends R> fn) {
return lazy(() -> _1(),
() -> _2(),
() -> _3(),
() -> _4(),
() -> _5(),
() -> _6(),
() -> _7(),
() -> fn.apply(_8()));
}
public <R> R fold(Function8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> fn) {
return fn.apply(_1(),
_2(),
_3(),
_4(),
_5(),
_6(),
_7(),
_8());
}
@Override
public String toString() {
return String.format("[%s,%s,%s,%s,%s,%s,%s,%s]",
_1(),
_2(),
_3(),
_4(),
_5(),
_6(),
_7(),
_8());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !(o instanceof Tuple8)) {
return false;
}
Tuple8<?, ?, ?, ?, ?, ?, ?, ?> tuple8 = (Tuple8<?, ?, ?, ?, ?, ?, ?, ?>) o;
return Objects.equals(_1(),
tuple8._1()) && Objects.equals(_2(),
tuple8._2()) && Objects.equals(_3(),
tuple8._3()) && Objects.equals(_4(),
tuple8._4())
&& Objects.equals(_5(),
tuple8._5()) && Objects.equals(_6(),
tuple8._6()) && Objects.equals(_7(),
tuple8._7()) && Objects.equals(_8(),
tuple8._8());
}
@Override
public int hashCode() {
return Objects.hash(_1(),
_2(),
_3(),
_4(),
_5(),
_6(),
_7(),
_8());
}
public HashMap<T1, T2> toHashMap() {
return HashMap.<T1, T2>empty().put(_1(),
_2());
}
public Map<T1, T2> toMap() {
java.util.HashMap<T1, T2> res = new java.util.HashMap();
res.put(_1(),
_2());
return res;
}
public final Object[] toArray() {
return new Object[]{_1(), _2(), _3(), _4(), _5(), _6(), _7(), _8()};
}
}
|
<reponame>RohanNagar/op-connect-sdk-java
package com.sanctionco.opconnect.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import java.util.StringJoiner;
/**
* Represents a URL contained in an item.
*/
public class URL {
private final String url;
private final Boolean primary;
@JsonCreator
URL(@JsonProperty("href") String url,
@JsonProperty("primary") Boolean primary) {
this.url = url;
this.primary = primary;
}
/**
* Get the actual string URL.
*
* @return the string URL
*/
@JsonProperty("href")
public String getUrl() {
return url;
}
/**
* Get whether this URL is a primary URL address or not.
*
* @return true if this URL is primary, false otherwise
*/
public Boolean getPrimary() {
return primary;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
URL url1 = (URL) o;
return Objects.equals(url, url1.url) && Objects.equals(primary, url1.primary);
}
@Override
public int hashCode() {
return Objects.hash(url, primary);
}
@Override
public String toString() {
return new StringJoiner(", ", URL.class.getSimpleName() + "[", "]")
.add("url='" + url + "'")
.add("primary=" + primary)
.toString();
}
/**
* Create a new primary URL from the given string.
*
* @param url the string URL
* @return a new instance of {@code URL}
*/
public static URL primary(String url) {
return new URL(url, true);
}
/**
* Create a new non-primary URL from the given string.
*
* @param url the string URL
* @return a new instance of {@code URL}
*/
public static URL standard(String url) {
return new URL(url, false);
}
}
|
python3 train_Donly.py --name=D0 --warpN=0 --pertFG=0.2
for w in {1..5}; do
python3 train_STGAN.py --loadD=0/D0_warp0_it50000 --warpN=$w;
done
|
package store;
import org.apache.commons.lang3.SerializationUtils;
import utils.StringUtil;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
public class Node implements Serializable {
private static final long serialVersionUID = 5559685098267757690L;
private byte[] hash;
private byte[][] children;
private byte[] value;
// branch
public Node() {
children = new byte[16][];
calculateHash();
}
// leaf
public Node(byte[] value) {
this.value = value;
calculateHash();
}
public void addChild(int index, byte[] child) {
children[index] = child;
calculateHash();
}
private void calculateHash() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try{
if(children != null) {
for (byte[] child : children) {
if (child != null)
stream.write(child);
}
}
if(value != null)
stream.write(value);
}catch (Exception ex) {
ex.printStackTrace();
}
hash = StringUtil.applyKeccak(stream.toByteArray());
}
public byte[] serialize() {
return SerializationUtils.serialize(this);
}
public byte[] getChild(int index) {
return children[index];
}
public byte[] getHash(){
return hash;
};
public byte[] getValue() {
return value;
};
}
|
package com.hapramp.ui.fragments;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hapramp.R;
import com.hapramp.datastore.DataStore;
import com.hapramp.datastore.callbacks.CompetitionsListCallback;
import com.hapramp.models.CompetitionListResponse;
import com.hapramp.models.CompetitionModel;
import com.hapramp.preferences.HaprampPreferenceManager;
import com.hapramp.ui.adapters.CompetitionsListRecyclerAdapter;
import com.hapramp.utils.ViewItemDecoration;
import com.hapramp.views.competition.CompetitionFeedItemView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class MyCompetitionsFragment extends Fragment implements CompetitionsListCallback, CompetitionFeedItemView.CompetitionItemDeleteListener, CompetitionsListRecyclerAdapter.LoadMoreCompetitionsCallback {
Context mContext;
Unbinder unbinder;
@BindView(R.id.competition_list)
RecyclerView competitionList;
@BindView(R.id.messagePanel)
TextView messagePanel;
@BindView(R.id.loading_progress_bar)
ProgressBar loadingProgressBar;
@BindView(R.id.swipe_refresh)
SwipeRefreshLayout swipeRefresh;
private DataStore dataStore;
private CompetitionsListRecyclerAdapter competitionsListRecyclerAdapter;
private String lastCompetitionId = "";
private String lastLoadedOrLoadingId = "";
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mContext = context;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_competitions_fragment, container, false);
unbinder = ButterKnife.bind(this, view);
initializeList();
return view;
}
private void initializeList() {
dataStore = new DataStore();
Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.post_item_divider_view);
ViewItemDecoration viewItemDecoration = new ViewItemDecoration(drawable);
viewItemDecoration.setWantTopOffset(false, 0);
competitionsListRecyclerAdapter = new CompetitionsListRecyclerAdapter(mContext);
competitionsListRecyclerAdapter.setDeleteListener(this);
competitionsListRecyclerAdapter.setLoadMoreCallback(this);
competitionList.setLayoutManager(new LinearLayoutManager(mContext));
competitionList.addItemDecoration(viewItemDecoration);
competitionList.setAdapter(competitionsListRecyclerAdapter);
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshCompetitions();
}
});
}
private void refreshCompetitions() {
dataStore.requestCompetitionLists(this);
}
@Override
public void onResume() {
super.onResume();
fetchCompetitions();
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
private void fetchCompetitions() {
setProgressVisibility(true);
dataStore.requestCompetitionLists(this);
}
private void setProgressVisibility(boolean show) {
if (loadingProgressBar != null) {
if (show) {
loadingProgressBar.setVisibility(View.VISIBLE);
} else {
loadingProgressBar.setVisibility(View.GONE);
}
}
}
@Override
public void onCompetitionsListAvailable(CompetitionListResponse competitionsResponse, boolean isAppendable) {
List<CompetitionModel> myContests = filterMyCompetitions(competitionsResponse.getCompetitionModels());
try {
lastCompetitionId = competitionsResponse.getLastId();
if (isAppendable) {
if (myContests != null) {
if (myContests.size() > 0) {
competitionsListRecyclerAdapter.appendCompetitions((ArrayList<CompetitionModel>) myContests);
} else {
competitionsListRecyclerAdapter.noMoreCompetitionsAvailableToLoad();
}
} else {
competitionsListRecyclerAdapter.noMoreCompetitionsAvailableToLoad();
}
} else {
if (swipeRefresh.isRefreshing()) {
swipeRefresh.setRefreshing(false);
}
setProgressVisibility(false);
if (myContests != null) {
if (myContests.size() == 0) {
setMessagePanel(true, "No competitions!");
} else {
setMessagePanel(false, "");
competitionsListRecyclerAdapter.setCompetitions(myContests);
}
} else {
setMessagePanel(true, "Something went wrong!");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCompetitionsFetchError() {
try {
if (swipeRefresh.isRefreshing()) {
swipeRefresh.setRefreshing(false);
}
setProgressVisibility(false);
setMessagePanel(true, "Something went wrong!");
}
catch (Exception e) {
}
}
private List<CompetitionModel> filterMyCompetitions(List<CompetitionModel> competitions) {
String myUsername = HaprampPreferenceManager.getInstance().getCurrentSteemUsername();
List<CompetitionModel> myCompetitions = new ArrayList<>();
for (int i = 0; i < competitions.size(); i++) {
if (competitions.get(i).getmAdmin().getmUsername().equals(myUsername)) {
myCompetitions.add(competitions.get(i));
}
}
return myCompetitions;
}
private void setMessagePanel(boolean show, String msg) {
if (messagePanel != null) {
if (show) {
messagePanel.setText(msg);
messagePanel.setVisibility(View.VISIBLE);
} else {
messagePanel.setVisibility(View.GONE);
}
}
}
@Override
public void onCompetitionItemDeleted() {
fetchCompetitions();
}
@Override
public void loadMoreCompetitions() {
fetchMoreCompetitions();
}
private void fetchMoreCompetitions() {
if (lastLoadedOrLoadingId != lastCompetitionId) {
dataStore.requestCompetitionLists(lastCompetitionId, this);
lastLoadedOrLoadingId = lastCompetitionId;
}
}
}
|
<filename>genericmodel/generic_processing.py
import librosa
import numpy as np
NOTE_HISTORY = 4
import pickle
import os
np.set_printoptions(precision=4,suppress=True, floatmode="fixed", sign=" ")
SAMPLE_RATE = 22050
SPECT_SKIP = 128
AUDIO_BEFORE_LEN = SAMPLE_RATE//SPECT_SKIP
AUDIO_AFTER_LEN = SAMPLE_RATE//SPECT_SKIP//4
PADDING = 8
def sec_to_id(seconds):
return round((seconds+PADDING)*(SAMPLE_RATE/SPECT_SKIP))
def beat_find(time_point):
for tt in [48, 24, 16, 12, 8, 6, 4, 3, 2, 1]: #time_resolution of individual notes
if time_point%tt == 0:
return tt
raise Exception(f"beat_frac {time_point} not int")
def try_pickle(cache_name):
if os.path.exists(cache_name):
try:
return pickle.load(open(cache_name,"rb"))
except:
print("Corrupted pickle")
return None
def cachename(data_file,primaryname,skip=True):
if skip:
name = primaryname+"_"+str(SAMPLE_RATE//1000)+"khz_"+str(SPECT_SKIP)+".p"
else:
name = primaryname+"_"+str(SAMPLE_RATE//1000)+"khz.p"
return os.path.join(os.path.dirname(data_file),name)
def load_song(data_file, songfile):
cache = cachename(data_file,"song_padded",skip=False)
song = try_pickle(cache)
if song is None:
with librosa.warnings.catch_warnings():
librosa.warnings.simplefilter("ignore")
song, sr = librosa.load(songfile, sr=SAMPLE_RATE, mono=True)
assert(sr == SAMPLE_RATE)
song = np.pad(song,SAMPLE_RATE*PADDING)
pickle.dump(song, open(cache,"wb"))
return song
def load_constq_spectogram(data_file,songfile):
cache_spect = cachename(data_file,"constq_spect")
l_spec = try_pickle(cache_spect)
if l_spec is None:
raw_audio = load_song(data_file, songfile)
l_spec = librosa.core.cqt(raw_audio, sr=SAMPLE_RATE, hop_length=SPECT_SKIP)
l_spec = librosa.amplitude_to_db(np.abs(l_spec),ref=np.max)
pickle.dump(l_spec, open(cache_spect,"wb"))
return l_spec
def normalize_data(arr):
ret_arr = arr.flatten()
max_n = ret_arr.max()
min_n = ret_arr.min()
return (ret_arr-min_n)/(max_n-min_n)
def normalize_db(arr):
init_arr = arr.flatten()
ret_arr = librosa.amplitude_to_db(init_arr,ref=np.max)
max_n = ret_arr.max()
min_n = ret_arr.min()
return (ret_arr-min_n)/(max_n-min_n)
def onset_strengths(data_file, songfile):
cache_rms_stft = cachename(data_file,"rms_stft")
rms_stft = try_pickle(cache_rms_stft)
cache_sp_band = cachename(data_file,"sp_band")
sp_band = try_pickle(cache_sp_band)
cache_sp_cent = cachename(data_file,"sp_cent")
sp_cent = try_pickle(cache_sp_cent)
cache_sp_flat = cachename(data_file,"sp_flat")
sp_flat = try_pickle(cache_sp_flat)
cache_onset_mel = cachename(data_file,"onsets_mel")
onsets_mel = try_pickle(cache_onset_mel)
if any(v is None for v in (rms_stft,sp_band,sp_cent,sp_flat,onsets_mel)):
cache_stft_complex = cachename(data_file,"stft_mag")
stft = try_pickle(cache_stft_complex)
if stft is None:
raw_audio = load_song(data_file, songfile)
stft_complex = librosa.stft(raw_audio, hop_length=SPECT_SKIP)
stft = np.abs(stft_complex)
pickle.dump(stft, open(cache_stft_complex,"wb"))
if rms_stft is None:
rms_stft = normalize_data(librosa.feature.rms(S=stft))
pickle.dump(rms_stft, open(cache_rms_stft,"wb"))
if sp_band is None:
sp_band = normalize_db(librosa.feature.spectral_bandwidth(S=stft,sr=SAMPLE_RATE,hop_length=SPECT_SKIP))
pickle.dump(sp_band, open(cache_sp_band,"wb"))
if sp_cent is None:
sp_cent = normalize_db(librosa.feature.spectral_centroid(S=stft,sr=SAMPLE_RATE,hop_length=SPECT_SKIP))
pickle.dump(sp_cent, open(cache_sp_cent,"wb"))
if sp_flat is None:
sp_flat = normalize_db(librosa.feature.spectral_flatness(S=stft))
pickle.dump(sp_flat, open(cache_sp_flat,"wb"))
if onsets_mel is None:
melspect = librosa.feature.melspectrogram(S=stft**2, sr=SAMPLE_RATE, hop_length=SPECT_SKIP)
onsets_mel = normalize_data(librosa.onset.onset_strength(S=melspect))
pickle.dump(onsets_mel, open(cache_onset_mel,"wb"))
cache_onset_cqt = cachename(data_file,"onsets_cqt")
onsets_cqt = try_pickle(cache_onset_cqt)
if onsets_cqt is None:
spect_cqt = load_constq_spectogram(data_file,songfile)
onsets_cqt = normalize_data(librosa.onset.onset_strength(S=spect_cqt))
pickle.dump(onsets_cqt, open(cache_onset_cqt,"wb"))
cache_zero_rate = cachename(data_file,"zero_rate")
zero_rate = try_pickle(cache_zero_rate)
if zero_rate is None:
song = load_song(data_file,songfile)
zero_rate = librosa.feature.zero_crossing_rate(y=song,hop_length=SPECT_SKIP).flatten()
pickle.dump(zero_rate, open(cache_zero_rate,"wb"))
mel_on_len = onsets_mel.shape[0]
cqt_on_len = onsets_cqt.shape[0]
zcr_len = zero_rate.shape[0]
rms_stft_len = rms_stft.shape[0]
band_len = sp_band.shape[0]
cent_len = sp_cent.shape[0]
flat_len = sp_flat.shape[0]
max_len = max([mel_on_len,cqt_on_len,rms_stft_len,band_len,cent_len,flat_len,zcr_len])
min_len = min([mel_on_len,cqt_on_len,rms_stft_len,band_len,cent_len,flat_len,zcr_len])
assert(max_len-min_len <= 1)
if (max_len > min_len):
onsets_mel= np.pad(onsets_mel, ((0,max_len-mel_on_len)))
onsets_cqt = np.pad(onsets_cqt,((0,max_len-cqt_on_len)))
zero_rate = np.pad(zero_rate, ((0,max_len-zcr_len)))
rms_stft = np.pad(rms_stft, ((0,max_len-rms_stft_len)))
sp_band = np.pad(sp_band, ((0,max_len-band_len)))
sp_cent = np.pad(sp_cent, ((0,max_len-cent_len)))
sp_flat = np.pad(sp_flat, ((0,max_len-flat_len)))
return np.stack((onsets_mel,onsets_cqt,zero_rate,rms_stft,sp_band,sp_cent,sp_flat),axis=-1)
def bpm_split(text):
x = text.split("=")
assert (len(x) == 2)
return (float(x[0]),float(x[1]))
def process_bpm(data_in):
bpm_text = data_in.split(",")
bpm_list = list(map(bpm_split,bpm_text))
bpm_list.append((float("inf"),0))
return bpm_list
def song_relpath(path):
return os.path.relpath(path,os.path.dirname(os.path.dirname(os.path.dirname(path)))) |
#!/usr/bin/env bash
cd $(cd -P -- "$(dirname -- "$0")" && pwd -P)
export TAGNAME="v1.4_cuda-11.2_ubuntu-20.04"
###################### build, run and push full image ##########################
echo
echo
echo "build, run and push full image with tag $TAGNAME."
bash generate-Dockerfile.sh
docker build --no-cache -t jnfinitym/gpu-jupyter:$TAGNAME .build/
export IMG_ID=$(docker image ls | grep $TAGNAME | grep -v _python-only | grep -v _slim | head -1 | awk '{print $3}')
echo "push image with ID $IMG_ID and Tag $TAGNAME ."
docker tag $IMG_ID cschranz/gpu-jupyter:$TAGNAME
docker rm -f gpu-jupyter_1
docker run --gpus all -d -it -p 8848:8888 -v $(pwd)/data:/home/jovyan/work -e GRANT_SUDO=yes -e JUPYTER_ENABLE_LAB=yes --user root --restart always --name gpu-jupyter_1 cschranz/gpu-jupyter:$TAGNAME
docker push cschranz/gpu-jupyter:$TAGNAME
###################### build and push slim image ##########################
echo
echo
echo "build and push slim image with tag ${TAGNAME}_slim."
bash generate-Dockerfile.sh --slim
docker build -t cschranz/gpu-jupyter:${TAGNAME}_slim .build/
export IMG_ID=$(docker image ls | grep ${TAGNAME}_slim | head -1 | awk '{print $3}')
echo "push image with ID $IMG_ID and Tag ${TAGNAME}_slim."
docker tag $IMG_ID cschranz/gpu-jupyter:${TAGNAME}_slim
docker push cschranz/gpu-jupyter:${TAGNAME}_slim
###################### build and push python-only image ##########################
echo
echo
echo "build and push slim image with tag ${TAGNAME}_python-only."
bash generate-Dockerfile.sh --python-only
docker build -t cschranz/gpu-jupyter:${TAGNAME}_python-only .build/
export IMG_ID=$(docker image ls | grep ${TAGNAME}_python-only | head -1 | awk '{print $3}')
echo "push image with ID $IMG_ID and Tag ${TAGNAME}_python-only."
docker tag $IMG_ID cschranz/gpu-jupyter:${TAGNAME}_python-only
docker push cschranz/gpu-jupyter:${TAGNAME}_python-only
|
<filename>src/test/java/de/codecentric/batch/BatchTest.java
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.codecentric.batch;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This is a test class to run a batch. It is needed to have a running HSQLDB server to store the metadata. Details of
* the run can be viewed in the spring-batch-admin view, i.e. at http://localhost:8080
*
* @author <NAME>
*/
@ContextConfiguration(classes = { TestBatchConfiguration.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class BatchTest {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job job;
@Test
public void startBatch() throws Exception {
jobLauncher.run(job, new JobParameters());
}
}
|
<filename>pkg/server/disk/server.go
package disk
import (
"context"
"fmt"
"strconv"
"github.com/kubernetes-csi/csi-proxy/client/apiversion"
"github.com/kubernetes-csi/csi-proxy/pkg/os/disk"
internal "github.com/kubernetes-csi/csi-proxy/pkg/server/disk/impl"
"k8s.io/klog/v2"
)
type Server struct {
hostAPI disk.API
}
// check that Server implements internal.ServerInterface
var _ internal.ServerInterface = &Server{}
func NewServer(hostAPI disk.API) (*Server, error) {
return &Server{
hostAPI: hostAPI,
}, nil
}
func (s *Server) ListDiskLocations(context context.Context, request *internal.ListDiskLocationsRequest, version apiversion.Version) (*internal.ListDiskLocationsResponse, error) {
klog.V(2).Infof("Request: ListDiskLocations: %+v", request)
response := &internal.ListDiskLocationsResponse{}
m, err := s.hostAPI.ListDiskLocations()
if err != nil {
klog.Errorf("ListDiskLocations failed: %v", err)
return response, err
}
response.DiskLocations = make(map[uint32]*internal.DiskLocation)
for k, v := range m {
d := &internal.DiskLocation{}
d.Adapter = v.Adapter
d.Bus = v.Bus
d.Target = v.Target
d.LUNID = v.LUNID
response.DiskLocations[k] = d
}
return response, nil
}
func (s *Server) PartitionDisk(context context.Context, request *internal.PartitionDiskRequest, version apiversion.Version) (*internal.PartitionDiskResponse, error) {
klog.V(2).Infof("Request: PartitionDisk with diskNumber=%d", request.DiskNumber)
response := &internal.PartitionDiskResponse{}
diskNumber := request.DiskNumber
initialized, err := s.hostAPI.IsDiskInitialized(diskNumber)
if err != nil {
klog.Errorf("IsDiskInitialized failed: %v", err)
return response, err
}
if !initialized {
klog.V(4).Infof("Initializing disk %d", diskNumber)
err = s.hostAPI.InitializeDisk(diskNumber)
if err != nil {
klog.Errorf("failed InitializeDisk %v", err)
return response, err
}
} else {
klog.V(4).Infof("Disk %d already initialized", diskNumber)
}
klog.V(4).Infof("Checking if disk %d has basic partitions", diskNumber)
partitioned, err := s.hostAPI.BasicPartitionsExist(diskNumber)
if err != nil {
klog.Errorf("failed check BasicPartitionsExist %v", err)
return response, err
}
if !partitioned {
klog.V(4).Infof("Creating basic partition on disk %d", diskNumber)
err = s.hostAPI.CreateBasicPartition(diskNumber)
if err != nil {
klog.Errorf("failed CreateBasicPartition %v", err)
return response, err
}
} else {
klog.V(4).Infof("Disk %d already partitioned", diskNumber)
}
return response, nil
}
func (s *Server) Rescan(context context.Context, request *internal.RescanRequest, version apiversion.Version) (*internal.RescanResponse, error) {
klog.V(2).Infof("Request: Rescan")
response := &internal.RescanResponse{}
err := s.hostAPI.Rescan()
if err != nil {
klog.Errorf("Rescan failed %v", err)
return nil, err
}
return response, nil
}
func (s *Server) GetDiskNumberByName(context context.Context, request *internal.GetDiskNumberByNameRequest, version apiversion.Version) (*internal.GetDiskNumberByNameResponse, error) {
klog.V(4).Infof("Request: GetDiskNumberByName with diskName %q", request.DiskName)
response := &internal.GetDiskNumberByNameResponse{}
diskName := request.DiskName
number, err := s.hostAPI.GetDiskNumberByName(diskName)
if err != nil {
klog.Errorf("GetDiskNumberByName failed: %v", err)
return nil, err
}
response.DiskNumber = number
return response, nil
}
func (s *Server) ListDiskIDs(context context.Context, request *internal.ListDiskIDsRequest, version apiversion.Version) (*internal.ListDiskIDsResponse, error) {
klog.V(4).Infof("Request: ListDiskIDs")
minimumVersion := apiversion.NewVersionOrPanic("v1beta1")
if version.Compare(minimumVersion) < 0 {
return nil, fmt.Errorf("ListDiskIDs requires CSI-Proxy API version v1beta1 or greater")
}
diskIDs, err := s.hostAPI.ListDiskIDs()
if err != nil {
klog.Errorf("ListDiskIDs failed: %v", err)
return nil, err
}
// Convert from shared to internal type
responseDiskIDs := make(map[uint32]*internal.DiskIDs)
for k, v := range diskIDs {
responseDiskIDs[k] = &internal.DiskIDs{
Page83: v.Page83,
SerialNumber: v.SerialNumber,
}
}
response := &internal.ListDiskIDsResponse{DiskIDs: responseDiskIDs}
klog.V(5).Infof("Response=%v", response)
return response, nil
}
func (s *Server) DiskStats(context context.Context, request *internal.DiskStatsRequest, version apiversion.Version) (*internal.DiskStatsResponse, error) {
klog.V(2).Infof("Request: DiskStats: diskNumber=%d", request.DiskID)
minimumVersion := apiversion.NewVersionOrPanic("v1beta1")
if version.Compare(minimumVersion) < 0 {
return nil, fmt.Errorf("DiskStats requires CSI-Proxy API version v1beta1 or greater")
}
// forward to GetDiskStats
diskNumber, err := strconv.ParseUint(request.DiskID, 10, 64)
if err != nil {
return nil, fmt.Errorf("Failed to format DiskStatsRequest.DiskID with err: %w", err)
}
getDiskStatsRequest := &internal.GetDiskStatsRequest{
DiskNumber: uint32(diskNumber),
}
getDiskStatsResponse, err := s.GetDiskStats(context, getDiskStatsRequest, version)
if err != nil {
klog.Errorf("Forward to GetDiskStats failed: %+v", err)
return nil, err
}
return &internal.DiskStatsResponse{
DiskSize: getDiskStatsResponse.TotalBytes,
}, nil
}
func (s *Server) GetDiskStats(context context.Context, request *internal.GetDiskStatsRequest, version apiversion.Version) (*internal.GetDiskStatsResponse, error) {
klog.V(2).Infof("Request: GetDiskStats: diskNumber=%d", request.DiskNumber)
diskNumber := request.DiskNumber
totalBytes, err := s.hostAPI.GetDiskStats(diskNumber)
if err != nil {
klog.Errorf("GetDiskStats failed: %v", err)
return nil, err
}
return &internal.GetDiskStatsResponse{
TotalBytes: totalBytes,
}, nil
}
func (s *Server) SetAttachState(context context.Context, request *internal.SetAttachStateRequest, version apiversion.Version) (*internal.SetAttachStateResponse, error) {
klog.V(2).Infof("Request: SetAttachState: %+v", request)
minimumVersion := apiversion.NewVersionOrPanic("v1beta2")
if version.Compare(minimumVersion) < 0 {
return nil, fmt.Errorf("SetAttachState requires CSI-Proxy API version v1beta2 or greater")
}
// forward to SetDiskState
diskNumber, err := strconv.ParseUint(request.DiskID, 10, 64)
if err != nil {
return nil, fmt.Errorf("Failed to format SetAttachStateRequest.DiskID with err: %w", err)
}
setDiskStateRequest := &internal.SetDiskStateRequest{
DiskNumber: uint32(diskNumber),
IsOnline: request.IsOnline,
}
_, err = s.SetDiskState(context, setDiskStateRequest, version)
if err != nil {
klog.Errorf("Forward to SetDiskState failed with: %+v", err)
return nil, err
}
return &internal.SetAttachStateResponse{}, nil
}
func (s *Server) SetDiskState(context context.Context, request *internal.SetDiskStateRequest, version apiversion.Version) (*internal.SetDiskStateResponse, error) {
klog.V(2).Infof("Request: SetDiskState with diskNumber=%d and isOnline=%v", request.DiskNumber, request.IsOnline)
err := s.hostAPI.SetDiskState(request.DiskNumber, request.IsOnline)
if err != nil {
klog.Errorf("SetDiskState failed: %v", err)
return nil, err
}
return &internal.SetDiskStateResponse{}, nil
}
func (s *Server) GetAttachState(context context.Context, request *internal.GetAttachStateRequest, version apiversion.Version) (*internal.GetAttachStateResponse, error) {
klog.V(2).Infof("Request: GetAttachState: %+v", request)
minimumVersion := apiversion.NewVersionOrPanic("v1beta2")
if version.Compare(minimumVersion) < 0 {
return nil, fmt.Errorf("GetAttachState requires CSI-Proxy API version v1beta2 or greater")
}
// forward to GetDiskState
diskNumber, err := strconv.ParseUint(request.DiskID, 10, 64)
if err != nil {
return nil, fmt.Errorf("Failed to format GetAttachStateRequest.DiskID with err: %w", err)
}
getDiskStateRequest := &internal.GetDiskStateRequest{
DiskNumber: uint32(diskNumber),
}
getDiskStateResponse, err := s.GetDiskState(context, getDiskStateRequest, version)
if err != nil {
klog.Errorf("Forward to GetDiskState failed with: %+v", err)
return nil, err
}
return &internal.GetAttachStateResponse{
IsOnline: getDiskStateResponse.IsOnline,
}, nil
}
func (s *Server) GetDiskState(context context.Context, request *internal.GetDiskStateRequest, version apiversion.Version) (*internal.GetDiskStateResponse, error) {
klog.V(4).Infof("Request: GetDiskState with diskNumber=%d", request.DiskNumber)
isOnline, err := s.hostAPI.GetDiskState(request.DiskNumber)
if err != nil {
klog.Errorf("GetDiskState failed with: %v", err)
return nil, err
}
return &internal.GetDiskStateResponse{IsOnline: isOnline}, nil
}
|
<filename>chapter07/Exercise_7_10.java
package com.company;
import java.util.Scanner;
public class Exercise_7_10 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
double[] array = new double[10];
for (int i = 0; i < 10; i++)
array[i] = input.nextDouble();
System.out.println("The index of smallest element is " + indexOfSmallestElement(array));
}
public static int indexOfSmallestElement(double[] array) {
int index = 0;
double min = array[0];
for(int i=1; i< array.length; i++) {
if(array[i] < min) {
min = array[i];
index = i;
}
}
return index;
}
}
|
<filename>app/src/main/java/com/goldencarp/lingqianbao/view/adapter/ItemListAdapter.java<gh_stars>10-100
package com.goldencarp.lingqianbao.view.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.goldencarp.lingqianbao.R;
import com.goldencarp.lingqianbao.model.net.Item;
import com.goldencarp.lingqianbao.view.LQBApp;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by dale on 2018/2/18.
*/
public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.MyViewHolder> {
List<Item> images;
public ItemListAdapter(List<Item> images) {
this.images = images;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(LQBApp.getApp()).inflate(R.layout.grid_item, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.descriptionTv.setText(images.get(position).description);
Glide.with(LQBApp.getApp()).load(images.get(position).imageUrl).into(holder.imageIv);
}
@Override
public int getItemCount() {
return images == null ? 0 : images.size();
}
public void setImages(List<Item> images) {
this.images = images;
notifyDataSetChanged();
}
static class MyViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.imageIv)
ImageView imageIv;
@BindView(R.id.descriptionTv)
TextView descriptionTv;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
|
<reponame>davidyu62/egovframe-runtime
package org.egovframe.rte.fdl.cmmn.cnamespace;
public class Bar {
}
|
python3 -m venv venv
venv/bin/pip install -U pip
venv/bin/pip install -r requirements.txt
# do the same thing as brownie init
mkdir -p build/contracts
mkdir -p build/deployments
mkdir -p build/interfaces
mkdir -p contracts
mkdir -p interfaces
mkdir -p reports
mkdir -p scripts
mkdir -p tests |
echo "label,probability" > result_pred_1.txt
cat result_list.txt | grep "1," >> result_pred_1.txt
python show_flow_model_eval_result.py |
function printSumOfMatrixNumbers(matrix) {
let sum = 0;
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
console.log(sum);
}
printSumOfMatrixNumbers([
[1, 2],
[3, 4]
]); |
<!DOCTYPE html>
<html>
<head>
<title>Books Table</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<table>
<tr>
<th>Author</th>
<th>Title</th>
</tr>
<tr>
<td>Herman Melville</td>
<td>Moby Dick</td>
</tr>
<tr>
<td>J.D. Salinger</td>
<td>Catcher in the Rye</td>
</tr>
<tr>
<td>J.R.R. Tolkien</td>
<td>The Lord of the Rings</td>
</tr>
<tr>
<td>William Shakespeare</td>
<td>Romeo and Juliet</td>
</tr>
</table>
</body>
</html> |
/*!
* months <https://github.com/jonschlinkert/months>
*
* Copyright (c) 2014 <NAME>, contributors.
* Licensed under the MIT license.
*/
module.exports = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
module.exports.abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
<gh_stars>0
package org.kr.scala.z80.opcode.handler
import org.kr.scala.z80.opcode.{OpCode, UnknownOperationException}
import org.kr.scala.z80.system.{Debugger, Regs, SystemChange, Z80System}
object Unknown extends OpCodeHandler {
override def handle(code: OpCode)(implicit system: Z80System, debugger:Debugger): (List[SystemChange], Int, Int) = {
throw new UnknownOperationException(f"Unknown operation $code at ${system.getRegValue(Regs.PC)}")
}
}
|
#!/bin/bash
export server_port=8888
export server_monitor_port=8889
server_settings_file_path="./conf/server.settings.yml"
if [ ! -f "$server_settings_file_path" ]; then
server_settings_file_path="./target/classes/server.settings.yml"
fi
parse_server_port_conf() {
if [ ! -f "$server_settings_file_path" ]; then
return
fi
new_server_port=`sed -n -e '/\s*server\.port/p' $server_settings_file_path | awk -F':' '{print $2}' | sed 's/\s*//g'`
new_server_monitor_port=`sed -n -e '/\s*server\.monitor\.port/p' $server_settings_file_path | awk -F':' '{print $2}' | sed 's/\s*//g'`
if [ ! -z "$new_server_port" ]; then
server_port="$new_server_port"
fi
if [ ! -z "$new_server_monitor_port" ]; then
server_monitor_port="$new_server_monitor_port"
fi
}
parse_server_port_conf |
var NAVTREEINDEX9 =
{
"dir_261e4925013eef98fcad776398f07228.html":[5,0,0,7,0],
"dir_267d90f063632c5e444535df04eb0c5e.html":[5,0,0,9,4,1],
"dir_275e0c4d023ff2f8f3984ab9050e8675.html":[5,0,0,7,2,0],
"dir_2dc87123beec9660d74b2cd6730c6845.html":[5,0,0,7,4],
"dir_3191169b8875823c165347786b03157d.html":[5,0,0,8,0,0,0],
"dir_3b3271d5e4029486768ebbbd03f3282a.html":[5,0,0,8],
"dir_3e860d8341d65f62f3b51cef99301122.html":[5,0,0,9,1,2],
"dir_4061f66aa0a103b911ae1f7030fa8ccb.html":[5,0,0,8,0],
"dir_40ef099ca2623b849365d87c81fc5655.html":[5,0,0,9,4,0],
"dir_4162662aac229d4da97d771ff950e80c.html":[5,0,0,7,6,2],
"dir_447cb223aa3d1b27adeb1a160cbe4428.html":[5,0,0,7,5,0],
"dir_4522633b8d7d9b4e1e5cc2f1db07d69a.html":[5,0,0,9,4],
"dir_46e9d0899ddaf8263d010c5ddd4179db.html":[5,0,0,5,2,0],
"dir_49aa22ee49a654e58ccfa75a7f184c8a.html":[5,0,0,5],
"dir_4aad17e7f879d52197c36498e35e46fd.html":[5,0,0,7,6],
"dir_4f6666a8f2ab10bc970eb7559668f031.html":[5,0,0],
"dir_5159cee89dc446b21718ac23fb1243c3.html":[5,0,0,7,6,1,0],
"dir_56e3fbc2949d6fccba7f5d92fa9ef5fc.html":[5,0,0,9,1],
"dir_57f1dc2c59d2c93b901fbfd79af41b4a.html":[5,0,0,7,4,0],
"dir_6422e9fc987e2e5b3d5ec474fb13d3ec.html":[5,0,0,9,2,6],
"dir_674c85f90df50db76c703856a5977c71.html":[5,0,0,9,0],
"dir_677d9e4741015c1bbd312b7c32e0660e.html":[5,0,0,9,3],
"dir_68be5a2cc396b3af374923467758c720.html":[5,0,0,0,0,0],
"dir_69527fc557422024e55e0f729487314e.html":[5,0,0,7,1,1],
"dir_69c3929d05f2b18e9dfff9e2a1b67e3b.html":[5,0,0,7,1],
"dir_6b0bd19914cb829c695047384b32c3ff.html":[5,0,0,0],
"dir_72e30cb13ec7f0b6aa475169ab72c9f9.html":[5,0,0,2],
"dir_7565fd6518e85e5ff5263551ce65e647.html":[5,0,0,5,0],
"dir_7a491fbf7842116da2df46cef1f4f38b.html":[5,0,0,1],
"dir_7d9dbb9f72e8c60c2e8af5928379d6e3.html":[5,0,0,7,5],
"dir_7f9883c7ec7b82b70ec005ad074cfede.html":[5,0,0,9,2,4],
"dir_80d95b843cf1a796cca7290d00977a7e.html":[5,0,0,1,0],
"dir_82b13d9626651e5889be4a9ab3f51f8f.html":[5,0,0,9,1,4,0],
"dir_8473b6a254087efd87d54f5ad0c98280.html":[5,0,0,8,0,0],
"dir_84bd7fac24f9828d630973fde92f31e9.html":[5,0,0,7,6,7],
"dir_8a7626d726fc61067864041ab0931ca1.html":[5,0,0,7,6,5],
"dir_8b4797a5a3a28724f013e5fdfb34e4d7.html":[5,0,0,9,1,2,1,0],
"dir_8b9b7253a96c90583f213aa4e73f2a61.html":[5,0,0,9,1,1],
"dir_903698d701ee154dcbd127064b4b76ea.html":[5,0,0,7,3,0],
"dir_925eebaa00165f3f3d927fb23540d836.html":[5,0,0,7,2],
"dir_a0748bd932d374c0d46fdb7c444164ed.html":[5,0,0,7,6,6],
"dir_a1c0d35bdc43327d18e2d24d49e37618.html":[5,0,0,0,0],
"dir_a2491733fe50143706812de39333e14b.html":[5,0,0,6],
"dir_a9b01f4fe05ca5c17593a1992fcd4b5e.html":[5,0,0,9,2,1],
"dir_b366ffc79af0aceb94e57904927b4c46.html":[5,0,0,7,6,1],
"dir_b741367f462fedd63cd9713080c6987d.html":[5,0,0,9,2,0],
"dir_ba88ba041a6b74ca6e2273f23eed33eb.html":[5,0,0,9,2,2],
"dir_c13000e629f933bcd3956698cc4aa71f.html":[5,0,0,9,1,2,2],
"dir_c3022be545dd9a8ff52ca40c03d684ea.html":[5,0,0,7,3],
"dir_c945ea9c9f16f9e74624ce5805c12c8c.html":[5,0,0,9,2,5],
"dir_c9eadb85a3143b14eaf5fe5839688323.html":[5,0,0,9,2],
"dir_cf32ae25775577cc9bcf7558bb2e5dff.html":[5,0,0,0,2],
"dir_cf3cc4011d38ffeb68dfbccd0525c6b9.html":[5,0,0,5,1,0],
"dir_d4864b0f6b0f652f9d7801baec5895c8.html":[5,0,0,7,3,3],
"dir_d8da6fe6dddc6eeb0ed1e78a961648bc.html":[5,0,0,9],
"dir_dad51767212e34935e9eb7f6f4794250.html":[5,0,0,7,6,1,0,0],
"dir_db7ea4ca1d9f944502362365705b0cc4.html":[5,0,0,9,1,0],
"dir_dbb99c36e7b32afd8999435cc4d3ed70.html":[5,0,0,4],
"dir_e1154fb7d5516339a5b0bb11c29c244b.html":[5,0,0,7,1,0],
"dir_e3e392c7a4b6e7fa7df092e76e9963c2.html":[5,0,0,5,0,0],
"dir_e7b42abf374bf0b664711ec674aae9db.html":[5,0,0,3],
"dir_ee354ff3b3144d2b594dc80e4c5a0549.html":[5,0,0,7,6,4],
"dir_eee95c9bc759bacbc156c0acd2a7138a.html":[5,0,0,9,1,2,1],
"dir_ef4c85bba1145a3e019f03aefaba4c48.html":[5,0,0,0,1],
"dir_f76b7d29d9147939685f8614f6348f82.html":[5,0,0,9,5],
"dir_faaba18fd3a3716878541fc20fd5db77.html":[5,0,0,4,0],
"dir_fe5eabb93ea070993dff4963a5a0e611.html":[5,0,0,9,1,2,0],
"files.html":[5,0],
"functions.html":[4,3,0,0],
"functions.html":[4,3,0],
"functions_a.html":[4,3,0,1],
"functions_b.html":[4,3,0,2],
"functions_c.html":[4,3,0,3],
"functions_d.html":[4,3,0,4],
"functions_e.html":[4,3,0,5],
"functions_evnt.html":[4,3,4],
"functions_f.html":[4,3,0,6],
"functions_func.html":[4,3,1],
"functions_func.html":[4,3,1,0],
"functions_func_a.html":[4,3,1,1],
"functions_func_b.html":[4,3,1,2],
"functions_func_c.html":[4,3,1,3],
"functions_func_d.html":[4,3,1,4],
"functions_func_e.html":[4,3,1,5],
"functions_func_f.html":[4,3,1,6],
"functions_func_g.html":[4,3,1,7],
"functions_func_i.html":[4,3,1,8],
"functions_func_k.html":[4,3,1,9],
"functions_func_l.html":[4,3,1,10],
"functions_func_m.html":[4,3,1,11],
"functions_func_n.html":[4,3,1,12],
"functions_func_o.html":[4,3,1,13],
"functions_func_p.html":[4,3,1,14],
"functions_func_r.html":[4,3,1,15],
"functions_func_s.html":[4,3,1,16],
"functions_func_t.html":[4,3,1,17],
"functions_func_u.html":[4,3,1,18],
"functions_func_v.html":[4,3,1,19],
"functions_g.html":[4,3,0,7],
"functions_h.html":[4,3,0,8],
"functions_i.html":[4,3,0,9],
"functions_k.html":[4,3,0,10],
"functions_l.html":[4,3,0,11],
"functions_m.html":[4,3,0,12],
"functions_n.html":[4,3,0,13],
"functions_o.html":[4,3,0,14],
"functions_p.html":[4,3,0,15],
"functions_prop.html":[4,3,3],
"functions_prop.html":[4,3,3,0],
"functions_prop_b.html":[4,3,3,1],
"functions_prop_c.html":[4,3,3,2],
"functions_prop_d.html":[4,3,3,3],
"functions_prop_e.html":[4,3,3,4],
"functions_prop_f.html":[4,3,3,5],
"functions_prop_g.html":[4,3,3,6],
"functions_prop_h.html":[4,3,3,7],
"functions_prop_i.html":[4,3,3,8],
"functions_prop_l.html":[4,3,3,9],
"functions_prop_m.html":[4,3,3,10],
"functions_prop_n.html":[4,3,3,11],
"functions_prop_o.html":[4,3,3,12],
"functions_prop_p.html":[4,3,3,13],
"functions_prop_q.html":[4,3,3,14],
"functions_prop_r.html":[4,3,3,15],
"functions_prop_s.html":[4,3,3,16],
"functions_prop_t.html":[4,3,3,17],
"functions_prop_u.html":[4,3,3,18],
"functions_prop_v.html":[4,3,3,19],
"functions_prop_w.html":[4,3,3,20],
"functions_prop_x.html":[4,3,3,21],
"functions_prop_y.html":[4,3,3,22],
"functions_prop_z.html":[4,3,3,23],
"functions_q.html":[4,3,0,16],
"functions_r.html":[4,3,0,17],
"functions_s.html":[4,3,0,18],
"functions_t.html":[4,3,0,19],
"functions_u.html":[4,3,0,20],
"functions_v.html":[4,3,0,21],
"functions_vars.html":[4,3,2,0],
"functions_vars.html":[4,3,2],
"functions_vars_a.html":[4,3,2,1],
"functions_vars_b.html":[4,3,2,2],
"functions_vars_c.html":[4,3,2,3],
"functions_vars_i.html":[4,3,2,4],
"functions_vars_l.html":[4,3,2,5],
"functions_vars_n.html":[4,3,2,6],
"functions_vars_r.html":[4,3,2,7],
"functions_vars_s.html":[4,3,2,8],
"functions_vars_t.html":[4,3,2,9],
"functions_vars_u.html":[4,3,2,10],
"functions_vars_w.html":[4,3,2,11],
"functions_w.html":[4,3,0,22],
"functions_x.html":[4,3,0,23],
"functions_y.html":[4,3,0,24],
"functions_z.html":[4,3,0,25],
"globals.html":[5,1,0],
"globals_type.html":[5,1,1],
"hierarchy.html":[4,2],
"index.html":[],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html":[4,0,0,0,1,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#a09ec943f53ec550a9f87602799915452":[4,0,0,0,1,0,10],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#a1c48e890a01621ca1195baa5cb52a571":[4,0,0,0,1,0,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#a2647cc3e11f9f2a6e89ac309d9be7276":[4,0,0,0,1,0,4],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#a4cfbf855f0f5c2fc455fd7871dd0fc61":[4,0,0,0,1,0,6],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#a81652aea3e78cf4bcb5e7fbae9485ebf":[4,0,0,0,1,0,7],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#a90bcdd455ca09c53b7c34732c8f690b5":[4,0,0,0,1,0,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#aa20fad0380fba41a271214563f44b796":[4,0,0,0,1,0,12],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#aae92cae3d2b3bd61b47206b250d6afcc":[4,0,0,0,1,0,5],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#ac1c0fe6deeceba359cd1c0048d474bf1":[4,0,0,0,1,0,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#adb640eb2f9482c9302205d3b968afe55":[4,0,0,0,1,0,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#ae45ce5352dceef09d8585a669f564bbd":[4,0,0,0,1,0,9],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#aed013bade948fc62e6be34260d627935":[4,0,0,0,1,0,8],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_abstract_prototyping_environment.html#afddc4e04b76ddc1fc4911220019e06ab":[4,0,0,0,1,0,11],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actor.html":[4,0,0,0,1,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actor.html#a0dfc23977330aeb1d9ed657ac0cf3fce":[4,0,0,0,1,1,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actor.html#a11a60dcdb87319a7e45183e62647596f":[4,0,0,0,1,1,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actor.html#a8dc8f32fb44ed1db19a6f0aa3673ff99":[4,0,0,0,1,1,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actor.html#af7976f672d5f1ddc2fc90d85ee2b5ec1":[4,0,0,0,1,1,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actorised_prototyping_environment.html":[4,0,0,0,1,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actuator.html":[4,0,0,0,1,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actuator.html#a06f733fa57fb44398789d85e9e041f9a":[4,0,0,0,1,3,4],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actuator.html#a19ecee1a5d553567f997ffaae7d6edc8":[4,0,0,0,1,3,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actuator.html#aacc15b1d4601f558a825a5006c47c447":[4,0,0,0,1,3,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actuator.html#aaf774f134889b7272f063f0999a80906":[4,0,0,0,1,3,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_actuator.html#abc015f37120e82b13c5b656f88d9be42":[4,0,0,0,1,3,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_category_provider.html":[4,0,0,0,1,4],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_category_provider.html#a45132fa3d419e5d48b6b7de479af01a6":[4,0,0,0,1,4,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_color_provider.html":[4,0,0,0,1,5],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_color_provider.html#a3d78f5130f66a594c7dc65f883d4bc5c":[4,0,0,0,1,5,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html":[4,0,0,0,1,6],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html#a0c74cdf003404891800a8ae6aea90335":[4,0,0,0,1,6,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html#a1149ce82fd4b7c51c0db30d28acf7e82":[4,0,0,0,1,6,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html#a13b40b5c7315c369fcee35c1f0957f37":[4,0,0,0,1,6,4],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html#a6995ba0b40888ba3d8d08e195b7f86e6":[4,0,0,0,1,6,5],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html#a7d8c5f5507182855e4e5f79741dc58f6":[4,0,0,0,1,6,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html#adf1e3f9cb733d926208d6b26cdec5385":[4,0,0,0,1,6,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable.html#af038d4f19e3bd541c49dd300abb554b5":[4,0,0,0,1,6,6],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable_configuration.html":[4,0,0,0,1,7],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable_configuration.html#a5f4e453074c02625b6b9b21663e72f53":[4,0,0,0,1,7,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable_configuration.html#ac6c70a4b47c641032fd8a99ceb6d4351":[4,0,0,0,1,7,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_configurable_configuration.html#ad7935f2c1ff952ed7ca5ab781fb41512":[4,0,0,0,1,7,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html":[4,0,0,0,1,8],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a1d99e6f6e7d0d9d7670482ba2d249148":[4,0,0,0,1,8,6],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a268d816557d37a22c0dd273380a7f565":[4,0,0,0,1,8,4],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a2fabd681cece06680ba44848f93e25e0":[4,0,0,0,1,8,10],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a3f10e8303d8fd9ca3594ebb34b92c8cc":[4,0,0,0,1,8,9],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a5009d515148d494745a40ac1bfeb969a":[4,0,0,0,1,8,8],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a76c830ee3093a1dd4a51f5a513422d08":[4,0,0,0,1,8,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a94adf8bfddda725c7902ccd6490ea5d2":[4,0,0,0,1,8,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#a9ee091f50dee8b4e7294d460f5a2b229":[4,0,0,0,1,8,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#ad48e21ca9aafb92597d072a5a4b958a5":[4,0,0,0,1,8,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#adc86dd0b39b6fef3cc8f7614ca188981":[4,0,0,0,1,8,7],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_displayer.html#ae55768d90e386044f38e3cad6a1d2055":[4,0,0,0,1,8,5],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html":[4,0,0,0,1,9],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#a07aea2b83b8989a3ef6ec56ca5a65326":[4,0,0,0,1,9,9],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#a27927adf73c7ef6da6bfcfbfee6a16f5":[4,0,0,0,1,9,7],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#a51031c36ad49f818d2d2013976e8385b":[4,0,0,0,1,9,8],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#a53a2adbbfac8da4b2a47e91da597d45c":[4,0,0,0,1,9,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#a63febdd99931aa0aaed3fec6657815c0":[4,0,0,0,1,9,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#a8454805ab86d9f8c5a5dab14a6fd623a":[4,0,0,0,1,9,6],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#a8458fc5fc8bd9b12afabaa55f2ab3d2f":[4,0,0,0,1,9,10],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#aad9c124e8f2e5988d3862aa92e80f20f":[4,0,0,0,1,9,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#abcb359421bd75055dd7c480a92bf4c50":[4,0,0,0,1,9,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#aca37c2511f57f0b88bb64ae329b0524c":[4,0,0,0,1,9,4],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment.html#ad73abc5443d2d41ac022795d6158e047":[4,0,0,0,1,9,5],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment_listener.html":[4,0,0,0,1,10],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment_listener.html#a0f087f0eb71655829da31042cff2b64b":[4,0,0,0,1,10,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment_listener.html#a47920dd501a5b17046ba535c6a102f0d":[4,0,0,0,1,10,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment_listener.html#a6c80e49036d5f319011b3c2a46141c1f":[4,0,0,0,1,10,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_environment_listener.html#acd0b42064436c20e5e300d1f97e6b434":[4,0,0,0,1,10,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_byte_array.html":[4,0,0,0,1,11],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_byte_array.html#a9f97d405791e3dcbbc289775815e2382":[4,0,0,0,1,11,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_byte_array.html#ac476a6f32e078c26cb833798d7b7e9e2":[4,0,0,0,1,11,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_byte_array.html#aedd2b14c54b46bc33aa2f27e2e0aa8fe":[4,0,0,0,1,11,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_double.html":[4,0,0,0,1,12],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_double.html#a0208b2b18ece83f4b885c66ac05fcddf":[4,0,0,0,1,12,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_double.html#aa0a1f62b320f5fa736ba5336797d9776":[4,0,0,0,1,12,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_double_array.html":[4,0,0,0,1,13],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_double_array.html#a18e8b5e55a6be19dc039d7f0744271ec":[4,0,0,0,1,13,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_double_array.html#aa0cf53a9fc5b7dc31a715692fb0e8fef":[4,0,0,0,1,13,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html":[4,0,0,0,1,14],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html#a39216330ee8ea3f1113ec514ead6d4a6":[4,0,0,0,1,14,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html#a9baa57b52d761818a224db323efabcad":[4,0,0,0,1,14,5],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html#aa7d045b0acc0b7aea2544c0a16c0d8cf":[4,0,0,0,1,14,4],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html#ab7c62c6b0bc5b3ce972752ec62b42643":[4,0,0,0,1,14,2],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html#ab9966bbfff7ee9ef0aa0d9242a68151d":[4,0,0,0,1,14,3],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_euler_transform.html#ac2feba7a31456885ddf69173cfcab82e":[4,0,0,0,1,14,0],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_float_array.html":[4,0,0,0,1,15],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_float_array.html#a404b6e085fd2cf9871b22f1857572bf4":[4,0,0,0,1,15,1],
"interfacedroid_1_1_runtime_1_1_interfaces_1_1_i_has_float_array.html#ae3601df4cdd0d9c5491557e6c4893de5":[4,0,0,0,1,15,0]
};
|
const { CREDIT_NOTE } = require('../../../helpers/constants');
const UtilsPdfHelper = require('./utils');
const UtilsHelper = require('../../../helpers/utils');
exports.getSubscriptionTableBody = creditNote => [
[{ text: 'Service', bold: true }, { text: 'Prix unitaire TTC', bold: true }, { text: 'Total TTC*', bold: true }],
[creditNote.subscription.service, creditNote.subscription.unitInclTaxes, creditNote.netInclTaxes],
];
exports.getSubscriptionTable = (creditNote) => {
const customerIdentity = UtilsHelper.formatIdentity(creditNote.customer.identity, 'TFL');
const { fullAddress } = creditNote.customer.contact.primaryAddress;
return [
{ text: `Prestations réalisées chez ${customerIdentity}, ${fullAddress}.` },
{
table: { body: exports.getSubscriptionTableBody(creditNote), widths: ['*', 'auto', 'auto'] },
margin: [0, 8, 0, 8],
layout: { hLineWidth: () => 0.5, vLineWidth: () => 0.5 },
},
{ text: '*ce total intègre les financements, majorations et éventuelles remises.' },
];
};
exports.getBillingItemsTable = (creditNote) => {
const billingItemsTableBody = [
[
{ text: 'Intitulé', bold: true },
{ text: 'Prix unitaire TTC', bold: true },
{ text: 'Volume', bold: true },
{ text: 'Total TTC', bold: true },
],
];
creditNote.billingItems.forEach((bi) => {
billingItemsTableBody.push(
[
{ text: `${bi.name}${bi.vat ? ` (TVA ${UtilsHelper.formatPercentage(bi.vat / 100)})` : ''}` },
{ text: UtilsPdfHelper.formatBillingPrice(bi.unitInclTaxes) },
{ text: `${bi.count}` },
{ text: UtilsPdfHelper.formatBillingPrice(bi.inclTaxes) },
]
);
});
return [
{
table: { body: billingItemsTableBody, widths: ['*', 'auto', 'auto', 'auto'] },
margin: [0, 8, 0, 8],
layout: { hLineWidth: () => 0.5, vLineWidth: () => 0.5 },
},
];
};
exports.getPdfContent = async (data) => {
const { creditNote } = data;
const content = [await UtilsPdfHelper.getHeader(creditNote.company, creditNote, CREDIT_NOTE)];
content.push(...(creditNote.misc ? [{ text: `Motif de l'avoir : ${creditNote.misc}`, marginBottom: 16 }] : []));
if (creditNote.formattedEvents) {
content.push(
UtilsPdfHelper.getPriceTable(creditNote),
UtilsPdfHelper.getEventsTable(creditNote, !creditNote.forTpp)
);
} else if (creditNote.subscription) {
content.push(exports.getSubscriptionTable(creditNote));
} else if (creditNote.billingItems) {
content.push(
exports.getBillingItemsTable(creditNote),
UtilsPdfHelper.getPriceTable(creditNote)
);
}
return {
content: content.flat(),
defaultStyle: { font: 'Avenir', fontSize: 11 },
styles: { marginRightLarge: { marginRight: 24 } },
};
};
|
from .price_volume import PriceVolumeFeeder |
<reponame>housnberg/taskana<filename>web/src/app/administration/workbasket/details/distribution-targets/dual-list/dual-list.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { WorkbasketSummary } from 'app/models/workbasket-summary';
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';
import { FilterModel } from 'app/models/filter';
import { filter } from 'rxjs/operators';
import { Side } from '../distribution-targets.component';
@Component({
selector: 'taskana-dual-list',
templateUrl: './dual-list.component.html',
styleUrls: ['./dual-list.component.scss'],
animations: [
trigger('toggle', [
state('*', style({ opacity: '1' })),
state('void', style({ opacity: '0' })),
transition('void => *', animate('300ms ease-in', keyframes([
style({ opacity: 0, height: '0px' }),
style({ opacity: 0.5, height: '50px' }),
style({ opacity: 1, height: '*' })]))),
transition('* => void', animate('300ms ease-out', keyframes([
style({ opacity: 1, height: '*' }),
style({ opacity: 0.5, height: '50px' }),
style({ opacity: 0, height: '0px' })])))
]
)],
})
export class DualListComponent implements OnInit {
@Input() distributionTargets: Array<WorkbasketSummary>;
@Output() distributionTargetsChange = new EventEmitter<Array<WorkbasketSummary>>();
@Input() distributionTargetsSelected: Array<WorkbasketSummary>;
@Output() performDualListFilter = new EventEmitter<{ filterBy: FilterModel, side: Side }>();
@Input() requestInProgress = false;
@Input() side: Side;
sideNumber = 0;
toggleDtl = false;
toolbarState = false;
constructor() { }
ngOnInit() {
this.sideNumber = this.side === Side.LEFT ? 0 : 1;
}
selectAll(selected: boolean) {
this.distributionTargets.forEach((element: any) => {
element.selected = selected;
});
}
performAvailableFilter(filterModel: FilterModel) {
this.performDualListFilter.emit({ filterBy: filterModel, side: this.side });
}
}
|
#!/usr/bin/env bash
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
cd $SCRIPTPATH
cd ../../../
. config.profile
# check the enviroment info
nvidia-smi
export PYTHONPATH="$PWD":$PYTHONPATH
DATA_DIR="${DATA_ROOT}/cityscapes"
SAVE_DIR="${DATA_ROOT}/seg_result/cityscapes/"
BACKBONE="deepbase_resnet101_dilated8"
CONFIGS="configs/cityscapes/${BACKBONE}_ohem.json"
CONFIGS_TEST="configs/cityscapes/${BACKBONE}_test.json"
MODEL_NAME="spatial_ocrnet"
LOSS_TYPE="fs_auxohemce_loss"
CHECKPOINTS_NAME="${MODEL_NAME}_${BACKBONE}_trainval_mapillary_coarse_"$2
LOG_FILE="./log/cityscapes/${CHECKPOINTS_NAME}.log"
echo "Logging to $LOG_FILE"
mkdir -p `dirname $LOG_FILE`
MAX_ITERS=50000
PRETRAINED_MODEL="./checkpoints/cityscapes/spatial_ocrnet_deepbase_resnet101_dilated8_trainval_mapillary_1_latest.pth"
if [ "$1"x == "train"x ]; then
${PYTHON} -u main.py --configs ${CONFIGS} \
--drop_last y \
--only_coarse y \
--base_lr 0.0001 \
--phase train --gathered n --loss_balance y --log_to_file n \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --gpu 0 1 2 3 \
--data_dir ${DATA_DIR} --loss_type ${LOSS_TYPE} --max_iters ${MAX_ITERS} \
--resume ${PRETRAINED_MODEL} \
--checkpoints_name ${CHECKPOINTS_NAME} \
2>&1 | tee ${LOG_FILE}
elif [ "$1"x == "resume"x ]; then
${PYTHON} -u main.py --configs ${CONFIGS} --drop_last y --only_coarse y --base_lr 0.0001 \
--phase train --gathered n --loss_balance y --log_to_file n \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --max_iters ${MAX_ITERS} \
--data_dir ${DATA_DIR} --loss_type ${LOSS_TYPE} --gpu 0 1 2 3 \
--resume_continue y --resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--checkpoints_name ${CHECKPOINTS_NAME} \
2>&1 | tee -a ${LOG_FILE}
elif [ "$1"x == "debug"x ]; then
${PYTHON} -u main.py --configs ${CONFIGS} --drop_last y \
--phase debug --gpu 0 --log_to_file n 2>&1 | tee ${LOG_FILE}
elif [ "$1"x == "val"x ]; then
${PYTHON} -u main.py --configs ${CONFIGS} --drop_last y --data_dir ${DATA_DIR} \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --checkpoints_name ${CHECKPOINTS_NAME} \
--phase test --gpu 0 --resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--test_dir ${DATA_DIR}/val/image --log_to_file n --out_dir val 2>&1 | tee -a ${LOG_FILE}
cd lib/metrics
${PYTHON} -u cityscapes_evaluator.py --pred_dir ../../results/cityscapes/test_dir/${CHECKPOINTS_NAME}/val/label \
--gt_dir ${DATA_DIR}/val/label >> "../../"${LOG_FILE} 2>&1
elif [ "$1"x == "test"x ]; then
if [ "$3"x == "ss"x ]; then
echo "[single scale] test"
${PYTHON} -u main.py --configs ${CONFIGS} --drop_last y \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --checkpoints_name ${CHECKPOINTS_NAME} \
--phase test --gpu 0 1 2 3 --resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--test_dir ${DATA_DIR}/test --log_to_file n \
--out_dir ${SAVE_DIR}${CHECKPOINTS_NAME}_test_ss
else
echo "[multiple scale + flip] test"
${PYTHON} -u main.py --configs ${CONFIGS_TEST} --drop_last y \
--backbone ${BACKBONE} --model_name ${MODEL_NAME} --checkpoints_name ${CHECKPOINTS_NAME} \
--phase test --gpu 0 1 2 3 --resume ./checkpoints/cityscapes/${CHECKPOINTS_NAME}_latest.pth \
--test_dir ${DATA_DIR}/test --log_to_file n \
--out_dir ${SAVE_DIR}${CHECKPOINTS_NAME}_test_ms
fi
else
echo "$1"x" is invalid..."
fi
|
import unittest
from scrapydd.nodes import NodeManager, AnonymousNodeDisabled
from scrapydd.models import init_database, session_scope, Session
from scrapydd.config import Config
class NodeManagerTest(unittest.TestCase):
def setUp(self) -> None:
config = Config(values={'database_url': 'sqlite:///test.db'})
init_database(config)
def test_node_online(self):
target = NodeManager(None)
node_id = None
client_ip = '127.0.0.2'
tags = None
with session_scope() as session:
node = target.node_online(session, node_id, client_ip, tags)
self.assertIsNotNone(node.id)
self.assertIsNotNone(node.name)
self.assertEqual(node.client_ip, client_ip)
self.assertEqual(node.tags, tags)
def test_node_online_authentication(self):
target = NodeManager(None, enable_authentication=True)
node_id = None
client_ip = '127.0.0.2'
tags = None
with session_scope() as session:
try:
node = target.node_online(session, node_id, client_ip, tags)
self.fail('No exception caught')
except AnonymousNodeDisabled:
pass
def test_create_node_session(self):
target = NodeManager(None)
session = Session()
node_session = target.create_node_session(session)
self.assertIsNotNone(node_session)
class AuthenticatedNodeManager(unittest.TestCase):
def setUp(self) -> None:
config = Config(values={'database_url': 'sqlite:///test.db'})
init_database(config)
def get_target(self):
target = NodeManager(None, enable_authentication=True)
return target
def test_create_node_session(self):
target = self.get_target()
session = Session()
try:
node_session = target.create_node_session(session)
self.fail('Exception not caught')
except Exception:
pass
|
#!/usr/bin/env bash
definir -e # script de parada no erro
fazer site
bundle exec htmlproofer --allow-hash-href \
--assume-extension ./_site \
--url-ignore "/\/apple-touch*.*/,/\/images/logo/favicon.ico/,/#*/" \
--disable-externo \
-apenas_4xx
|
#! /usr/bin/env node
'use strict';
process.env.DEPLOY_ENV = 'production';
require('../').deploy();
|
#!/usr/bin/env bash
echo "$@" | # input text
openssl enc \
-e `# encode` \
-aes-256-cbc `# ciphername` \
-base64 `# base64` \
-salt # use salt (randomly generated or provide with -S option) when encrypting (this is the default).
|
#!/bin/sh
# Generate expected output
./flow-remove-types test/source.js > test/expected.js;
# Generate expected output with --pretty flag
./flow-remove-types --pretty test/source.js > test/expected-pretty.js;
# Test expected source maps with --pretty --sourcemaps
./flow-remove-types --pretty --sourcemaps test/source.js -d test/expected-with-maps;
# Test expected source maps with --pretty --sourcemaps inline
./flow-remove-types --pretty --sourcemaps inline test/source.js > test/expected-pretty-inlinemap.js;
|
#!/bin/bash
set -e
autoconf
config_mpi=""
if [ "x$mpi" != "xnompi" ]; then
export CC=mpicc
export LIBSHARP_MPI=1
config_mpi="--enable-mpi"
fi
./configure ${config_mpi} \
--enable-openmp \
--enable-noisy-make \
--enable-pic \
--prefix="${PREFIX}"
make -j${CPU_COUNT}
# Do the install by hand (not included in package)
mkdir -p ${PREFIX}/include
mkdir -p ${PREFIX}/lib
mkdir -p ${PREFIX}/bin
cp -R auto/include/* ${PREFIX}/include
cp -R auto/lib/* ${PREFIX}/lib
cp -R auto/bin/* ${PREFIX}/bin
# Manually run the installed tests rather than using
# the "make test" target. This allows us to control
# the MPI launching of the test commands.
declare -a testcoms=("acctest" "test healpix 2048 -1 1024 -1 0 1" "test fejer1 2047 -1 -1 4096 2 1" "test gauss 2047 -1 -1 4096 0 2")
export OMP_NUM_THREADS=2
if [ "x$mpi" = "xopenmpi" ]; then
# Using OpenMPI
for com in "${testcoms[@]}"; do
echo mpirun --allow-run-as-root \
--mca btl self,tcp \
--mca plm isolated \
--mca rmaps_base_oversubscribe yes \
--mca btl_vader_single_copy_mechanism none \
-np 2 sharp_testsuite ${com}
mpirun --allow-run-as-root \
--mca btl self,tcp \
--mca plm isolated \
--mca rmaps_base_oversubscribe yes \
--mca btl_vader_single_copy_mechanism none \
-np 2 sharp_testsuite ${com}
done
else
if [ "x$mpi" = "xmpich" ]; then
# Using MPICH
for com in "${testcoms[@]}"; do
export HYDRA_LAUNCHER=fork
echo mpirun -np 2 sharp_testsuite ${com}
mpirun -np 2 sharp_testsuite ${com}
done
else
# No MPI
for com in "${testcoms[@]}"; do
echo sharp_testsuite ${com}
sharp_testsuite ${com}
done
fi
fi
# Install python bindings
cd python
export LIBSHARP="${PREFIX}"
export LDSHARED="${CC} -shared"
${PYTHON} -m pip install . --no-deps --ignore-installed --no-cache-dir -vvv
|
#!/bin/sh
# crontab radiko rec shell
# 2020.02.08
# 2020.02.25 Del PREFIX Date
# 2020.05.29 del tee log
#
# 大橋彩香のAnyBeat!
# Sun 21:00
# 59 20 * * 0
# Common
REC_ROOT=/recorder
# Recording Info
STATION=QRR
REC_MIN=31
PREFIX=AYAKA
# Radiko Account Info
R_ID=(ID)
R_PW=(PW)
/usr/bin/docker run --rm -v $REC_ROOT:/var/radiko radiko_recorder:1.1 $STATION $REC_MIN $R_ID $R_PW . $PREFIX
|
<filename>external/iotivity/iotivity_1.2-rel/cloud/account/src/main/java/org/iotivity/cloud/accountserver/db/AclTable.java
/*
* //******************************************************************
* //
* // Copyright 2016 Samsung Electronics 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.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
package org.iotivity.cloud.accountserver.db;
import java.util.List;
import org.iotivity.cloud.accountserver.resources.acl.id.Ace;
public class AclTable {
private String aclid;
private String oid;
private String di;
private String rowneruuid;
private List<Ace> aclist;
public AclTable(String aclid, String oid, String di, String rowneruuid,
List<Ace> aclist) {
this.aclid = aclid;
this.oid = oid;
this.di = di;
this.rowneruuid = rowneruuid;
this.aclist = aclist;
}
public AclTable() {
}
public String getAclid() {
return aclid;
}
public void setAclid(String aclid) {
this.aclid = aclid;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public String getDi() {
return di;
}
public void setDi(String di) {
this.di = di;
}
public String getRowneruuid() {
return rowneruuid;
}
public void setRowneruuid(String rowneruuid) {
this.rowneruuid = rowneruuid;
}
public List<Ace> getAclist() {
return aclist;
}
public void setAclist(List<Ace> aclist) {
this.aclist = aclist;
}
}
|
<filename>mobileNav.js
var opened = false;
window.onload = function() {
var nav = document.getElementsByClassName("navbar")[0]
var items = nav.childNodes;
for (var i = 0; i < items.length; i++) {
items[i].className += " hide-small";
}
var menuItem = document.createElement("li");
menuItem.className = "hide-medium hide-large";
var menuButton = document.createElement("a");
menuButton.href="javascript:void(0)";
menuButton.onclick = openOrClose;
menuButton.style = "text-align: left";
var menuIcon = document.createElement("i");
menuIcon.className = "fa fa-bars"
nav.insertBefore(menuItem, nav.firstChild);
menuItem.appendChild(menuButton);
menuButton.appendChild(menuIcon);
}
function removeClass(element, remove) {
var newClassName = "";
var i;
var classes = element.className.split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] !== remove) {
newClassName += classes[i] + " ";
}
}
element.className = newClassName;
}
function openOrClose() {
var items = document.getElementsByClassName("navbar")[0].childNodes;
if (!opened) {
for (var i = 0; i < items.length; i++) {
removeClass(items[i], "hide-small");
}
opened = true;
} else {
for (var i = 1; i < items.length; i++) {
items[i].className += " hide-small";
}
opened = false;
}
}
|
// Copyright 2007 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.integration.app1.pages;
import org.apache.tapestry5.Block;
import org.apache.tapestry5.annotations.Id;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Retain;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import java.util.Map;
public class BlockDemo
{
@Inject @Id("fred")
private Block fredBlock;
@Inject
private Block barney;
// Blocks not injected until page load, so must lazily initialize the map.
@Retain
private Map<String, Block> blocks = null;
@Persist
private String blockName;
public Block getBlockToRender()
{
if (blocks == null)
{
blocks = CollectionFactory.newMap();
blocks.put("fred", fredBlock);
blocks.put("barney", barney);
}
return blocks.get(blockName);
}
public String getBlockName()
{
return blockName;
}
public void setBlockName(String blockName)
{
this.blockName = blockName;
}
}
|
import {
Column,
Entity,
PrimaryGeneratedColumn,
} from 'typeorm';
@Entity('report_hourly_counts')
export class ReportHourlyCount {
@PrimaryGeneratedColumn()
id: number;
@Column({ name: 'station_id' })
stationId: number;
@Column({ name: 'hour' })
hour: Date;
@Column({ name: 'messages_count' })
messagesCount: number;
}
|
import matplotlib.pyplot as plt
def visualize_parking_data(result_unrotated_roi_boundary_x, result_unrotated_roi_boundary_y, result_parking_spot_x, result_parking_spot_y, result_roi_boundary_x, result_roi_boundary_y):
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(result_unrotated_roi_boundary_x, result_unrotated_roi_boundary_y, label='Unrotated ROI Boundary')
ax1.scatter(result_parking_spot_x, result_parking_spot_y, label='Parking Spots')
ax1.set_title('Unrotated ROI and Parking Spots')
ax1.legend()
ax2 = fig.add_subplot(212)
ax2.scatter(result_roi_boundary_x, result_roi_boundary_y, label='Rotated ROI Boundary')
ax2.set_title('Rotated ROI Boundary')
ax2.legend()
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
# Example usage
result_unrotated_roi_boundary_x = [10, 20, 30, 40, 10]
result_unrotated_roi_boundary_y = [20, 30, 20, 10, 20]
result_parking_spot_x = [15, 25, 35]
result_parking_spot_y = [25, 15, 25]
result_roi_boundary_x = [12, 22, 32, 42, 12]
result_roi_boundary_y = [22, 32, 22, 12, 22]
visualize_parking_data(result_unrotated_roi_boundary_x, result_unrotated_roi_boundary_y, result_parking_spot_x, result_parking_spot_y, result_roi_boundary_x, result_roi_boundary_y) |
<gh_stars>0
import Vue from "vue";
import Vuex from "vuex";
import MarketplaceItemModel from "./models/MarketplaceItemModel";
import performItemsFiltering from "./utils/filter";
import { resetPaging, addNextPage } from "./utils/pager";
import CategoryModel from "./models/CategoryModel";
import { initStoreWithItems } from "./utils/items";
import { initStoreWithTags } from "./utils/tags";
import { initStoreWithCategories } from "./utils/categories";
import {
initStoreWithKenticoVersions,
KENTICO_VERSION_ALL_VERSIONS
} from "./utils/kenticoVersions";
import { shuffle } from './utils/shuffle';
export const updateAllItemsMutation = "updateAllItems";
export const updateFilteredItemsMutation = "updateFilteredItems";
export const updateItemsToShowMutation = "updateItemsToShow";
export const updateTagsCountMutation = "updateTagsCount";
export const updateKenticoVersionsFilterMutation =
"updateKenticoVersionsFilter";
export const updateCategoriesMutation = "updateCategories";
export const updateFilterSearchPhraseMutation = "updateFilterSearchPhrase";
export const updateSelectedCategoriesMutation = "updateSelectedCategories";
export const updateSelectedKenticoVersionMutation =
"updateSelectedKenticoVersion";
export const toggleCategoryInSelectedCategoriesMutation =
"toggleCategoryInSelectedCategories";
export const addNextPageInPagerListingMutation = "addNextPageInPagerListing";
export const updatePagerLastItemIndexMutation = "updatePagerLastItemIndex";
export const initItemsStateAction = "initItemsState";
export const addPageAction = "addPage";
export const updateSearchPhraseAction = "updateFilterPassphrase";
export const updateSelectedCategoriesAction = "updateSelectedCategories";
Vue.use(Vuex);
export async function initializeStoreWithItemsAndNavigateNext(next: any) {
await fetch(
"https://raw.githubusercontent.com/Kentico/devnet.kentico.com/master/marketplace/extensions.json" +
"?t=" +
new Date().valueOf()
).then(async response => {
return response.json().then(json => {
const allItems = json as MarketplaceItemModel[];
allItems.sort((a: MarketplaceItemModel, b: MarketplaceItemModel) =>
a.name.localeCompare(b.name)
);
initStore(shuffle(allItems));
next();
});
});
}
export function initStore(allItems: Array<MarketplaceItemModel>) {
initStoreWithItems(allItems);
initStoreWithTags(allItems);
initStoreWithCategories(allItems);
initStoreWithKenticoVersions(allItems);
}
export default new Vuex.Store({
state: {
data: {
allItems: Array<MarketplaceItemModel>(),
filteredItems: Array<MarketplaceItemModel>(),
itemsToShow: Array<MarketplaceItemModel>(),
tagsCount: new Map<string, number>(),
categories: new Array<CategoryModel>(),
kenticoVersions: new Array<string>()
},
filter: {
searchPhrase: "",
selectedCategories: new Array<string>(),
selectedKenticoVersion: KENTICO_VERSION_ALL_VERSIONS
},
pager: {
lastItemIndex: 0
}
},
mutations: {
updateAllItems(state, allItems: Array<MarketplaceItemModel>) {
state.data.allItems = allItems;
},
updateFilteredItems(state, filteredItems: Array<MarketplaceItemModel>) {
state.data.filteredItems = filteredItems;
},
updateItemsToShow(state, itemsToShow: Array<MarketplaceItemModel>) {
state.data.itemsToShow = itemsToShow;
},
updateTagsCount(state, tagsCount: Map<string, number>) {
state.data.tagsCount = tagsCount;
},
updateCategories(state, categories: Array<CategoryModel>) {
state.data.categories = categories;
},
updateFilterSearchPhrase(state, newSearchPhrase: string) {
state.filter.searchPhrase = newSearchPhrase;
},
updateSelectedCategories(state, selectedCategories: Array<string>) {
state.filter.selectedCategories = selectedCategories;
},
updateSelectedKenticoVersion(state, selectedKenticoVersion: string) {
state.filter.selectedKenticoVersion = selectedKenticoVersion;
},
updateKenticoVersionsFilter(state, kenticoVersions: Array<string>) {
state.data.kenticoVersions = kenticoVersions;
},
updatePagerLastItemIndex(state, lastItemIndex) {
state.pager.lastItemIndex = lastItemIndex;
}
},
getters: {
allItems: state => state.data.allItems,
filteredItems: state => state.data.filteredItems,
itemsToShow: state => state.data.itemsToShow,
tagsCount: state => state.data.tagsCount,
categories: state => state.data.categories,
kenticoVersions: state => state.data.kenticoVersions,
filterSearchphrase: state => state.filter.searchPhrase,
selectedCategories: state => state.filter.selectedCategories,
selectedKenticoVersion: state => state.filter.selectedKenticoVersion,
pagerLastItemIndex: state => state.pager.lastItemIndex
},
actions: {
initItemsState(context, allItems) {
context.commit(updateAllItemsMutation, allItems);
performItemsFiltering();
resetPaging();
},
updateFilterPassphrase(context, newSearchPhrase: string) {
context.commit(updateFilterSearchPhraseMutation, newSearchPhrase);
},
updateSelectedCategories(context, newSelectedCategories: Array<string>) {
context.commit(updateSelectedCategoriesMutation, newSelectedCategories);
},
filterItems(_) {
performItemsFiltering();
},
addPage(_) {
addNextPage();
}
}
});
|
<gh_stars>10-100
class JobResolver
include Singleton
class Noop
def self.perform_later(*args)
self
end
def self.set(*args)
self
end
end
def initialize
@jobs = UberDictionary.new ->(params) {
jobs = []
[
"saas/app/#{params[:controller]}_#{params[:action]}_job",
"#{params[:controller]}_#{params[:action]}_job",
"#{params[:controller]}_job",
].each do |job_name|
job_class = job_name.classify.safe_constantize
jobs << job_class if job_class
end
jobs.empty? ? [Noop] : jobs
}
@events = UberDictionary.new ->(params) {
[
"saas/app/#{params[:type].pluralize}_#{params[:action]}_#{params[:type]}_job",
"saas/api/#{params[:type].pluralize}_#{params[:action]}_#{params[:type]}_job",
"api/#{params[:type].pluralize}_#{params[:action]}_#{params[:type]}_job",
"api/#{params[:type].pluralize}_#{params[:action]}_job",
"api/#{params[:type].pluralize}_edit_issue_job",
].each do |job_name|
job_class = job_name.classify.safe_constantize
return job_class if job_class
end
return Noop
}
@mutex = Mutex.new
end
def find_jobs(params)
with_mutex do
@jobs[{controller: params[:controller], action: params[:action]}]
end
end
def self.find_jobs(params)
instance.find_jobs params
end
def find_event(type, action)
with_mutex do
@events[{type: type, action: action}]
end
end
def self.find_event(type, action)
instance.find_event type, action
end
private
def with_mutex
@mutex.synchronize { yield }
end
end
|
<gh_stars>0
import React from 'react';
import PropTypes from 'prop-types';
import throttle from 'lodash.throttle';
import { inViewForReact } from 'utils/common';
import TopBar from './TopBar/TopBar';
import Navigation from './Navigation/Navigation';
import Masthead from './Masthead/Masthead';
import NavList from '../../common/NavList/NavList';
class Header extends React.Component {
constructor() {
super();
this.state = {
stickyHeader: false,
};
}
componentDidMount() {
window.addEventListener('scroll', this.monitorScroll());
}
componentWillUnmount() {
window.removeEventListener('scroll', this.monitorScroll());
}
monitorScroll = () => throttle(this.handleScrollEvent, 100);
handleScrollEvent = () => {
let stickyHeader = false;
const elem =
document.getElementById('header-masthead') ||
document.getElementById('top-bar-container');
if (elem && !inViewForReact(elem, 0, true)) {
stickyHeader = true;
}
const refreshButton = document.getElementById('refresh-button');
if (refreshButton && stickyHeader) {
refreshButton.classList.add('sticky');
} else if (refreshButton && !stickyHeader) {
refreshButton.classList.remove('sticky');
}
window.isStickyHeader = stickyHeader;
this.setState({ stickyHeader });
};
render() {
const {
headerData = {},
hideCyclicNav,
showWeatherInC,
enablePrimeFlow,
isPrime,
killSwitchStatus,
hideLogoMastHead,
showToiPlusEntryPoints,
} = this.props;
const {
navigation,
masthead,
videomasthead,
hideTimeStamp,
promotionalL2,
} = headerData;
const isMastheadToiLogo = masthead && masthead.type === 'toiLogo';
const theme = headerData.colorTheme || this.props.colorTheme;
return (
<div className="header-container contentwrapper">
{}
<TopBar
isWapView={this.props.isWapView}
hideTimeStamp={hideTimeStamp}
editionSwitch={this.props.headerData?.editionSwitch}
hideTimesPointPopup={this.props.hideTimesPointPopup}
isPrime={isPrime}
colorTheme={theme}
showWeatherInC={showWeatherInC}
enablePrimeFlow={enablePrimeFlow}
pageType={this.props.pageType}
showToiPlusEntryPoints={showToiPlusEntryPoints}
/>
{(masthead || videomasthead) && (
<Masthead
config={masthead}
videomasthead={isPrime ? {} : videomasthead}
colorTheme={theme}
earplugAdsRight={headerData.earPlugAdsRight}
earplugAdsLeft={headerData.earPlugAdsLeft}
leaderboard={headerData.leaderboard}
poweredBy={headerData.poweredBy}
hideLogoMastHead={hideLogoMastHead}
/>
)}
<Navigation
hideCyclicNav={hideCyclicNav}
l2navigationChild={this.props.l2navigationChild}
allMenu={headerData.allMenu}
colorTheme={theme}
navigationData={navigation}
isWapView={this.props.isWapView}
stickyHeader={this.state.stickyHeader}
showHomeOnlyWhenSticky={isMastheadToiLogo}
pageType={this.props.pageType}
killSwitchStatus={killSwitchStatus}
geolocation={this.props.geolocation}
showToiPlusEntryPoints={showToiPlusEntryPoints}
/>
{promotionalL2 && (
<div className="contentwrapper">
<NavList data={promotionalL2} />
</div>
)}
</div>
);
}
}
// const mapStateToProps = state => ({
// navigationData: state.header.data,
// });
Header.propTypes = {
hideCyclicNav: PropTypes.bool,
l2navigationChild: PropTypes.shape({}),
promotionalL2: PropTypes.shape({}),
headerData: PropTypes.shape({
editionSwitch: PropTypes.shape({}),
}).isRequired,
isWapView: PropTypes.bool.isRequired,
hideTimesPointPopup: PropTypes.bool,
showWeatherInC: PropTypes.bool,
enablePrimeFlow: PropTypes.bool,
pageType: PropTypes.string,
killSwitchStatus: PropTypes.objectOf({}),
geolocation: PropTypes.string,
showToiPlusEntryPoints: PropTypes.bool,
hideLogoMastHead: PropTypes.bool,
colorTheme: PropTypes.string,
};
Header.defaultProps = {
hideCyclicNav: false,
l2navigationChild: null,
hideTimesPointPopup: false,
promotionalL2: { items: [] },
showWeatherInC: false,
enablePrimeFlow: false,
pageType: '',
killSwitchStatus: null,
geolocation: '1',
showToiPlusEntryPoints: false,
hideLogoMastHead: false,
colorTheme: '',
};
export default Header;
|
<gh_stars>1-10
/* The MIT License (MIT)
*
* Copyright (c) 2014 - 2021, <NAME>
* http://www.blue-andi.de
* <EMAIL>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
/*******************************************************************************
DESCRIPTION
*******************************************************************************/
/**
@brief Control
@file vscp_evt_control.h
@author <NAME>, http://www.blue-andi.de
@section desc Description
Control functionality. One of the main concepts of VSCP is that it is an event driven protocol.
Commands are sent out as events to the network not as events to specific devices. A device can
belong to a zone which select limit events of interest for the particular node.. If there is a need
to control a specific device the registry model should be used. This is the only way to directly
control a device.
This file is automatically generated. Don't change it manually.
*******************************************************************************/
#ifndef __VSCP_EVT_CONTROL_H__
#define __VSCP_EVT_CONTROL_H__
/*******************************************************************************
INCLUDES
*******************************************************************************/
#include <stdint.h>
#include "..\user\vscp_platform.h"
/*******************************************************************************
COMPILER SWITCHES
*******************************************************************************/
/*******************************************************************************
CONSTANTS
*******************************************************************************/
/*******************************************************************************
MACROS
*******************************************************************************/
/*******************************************************************************
TYPES AND STRUCTURES
*******************************************************************************/
/*******************************************************************************
VARIABLES
*******************************************************************************/
/*******************************************************************************
FUNCTIONS
*******************************************************************************/
/**
* General event
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendGeneralEvent(void);
/**
* Mute on/off
*
* @param[in] command If equal to zero no mute else mute.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMuteOnOff(uint8_t command, uint8_t zone, uint8_t subZone);
/**
* (All) Lamp(s) on/off
*
* @param[in] state If equal to zero off else on.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendAllLampSOnOff(uint8_t state, uint8_t zone, uint8_t subZone);
/**
* Open
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendOpen(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Close
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendClose(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* TurnOn
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendTurnon(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* TurnOff
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendTurnoff(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Start
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendStart(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Stop
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendStop(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Reset
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendReset(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Interrupt
*
* @param[in] interruptLevel Interrupt level. (0 – 255 , zero is lowest interrupt level. ).
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendInterrupt(uint8_t interruptLevel, uint8_t zone, uint8_t subZone);
/**
* Sleep
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSleep(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Wakeup
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendWakeup(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Resume
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendResume(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Pause
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendPause(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Activate
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendActivate(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Deactivate
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendDeactivate(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/* "Reserved for future use" not supported. No frame defined. */
/* "Reserved for future use" not supported. No frame defined. */
/* "Reserved for future use" not supported. No frame defined. */
/**
* Dim lamp(s)
*
* @param[in] value Value (0 – 100) . 0 = off, 100 = full on. 254 dim down one step. 255 dim up one
* step.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendDimLampS(uint8_t value, uint8_t zone, uint8_t subZone);
/**
* Change Channel
*
* @param[in] channel A value between 0 and 127 indicates the channel number. A value between 128 to
* 157 is change down by the specified number of channels. A value between 160 to 191 is change up by
* the specified number of channels. A value of 255 means that this is an extended change channel
* event and that the channel number is sent in byte 3 and after if needed.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendChangeChannel(uint8_t channel, uint8_t zone, uint8_t subZone);
/**
* Change Level
*
* @param[in] level Absolute level.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendChangeLevel(uint8_t level, uint8_t zone, uint8_t subZone);
/**
* Relative Change Level
*
* @param[in] level Relative level.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendRelativeChangeLevel(uint8_t level, uint8_t zone, uint8_t subZone);
/**
* Measurement Request
*
* @param[in] index Zero indicates all measurements supported by node should be sent (as separate
* events). Non-zero indicates a node specific index specifying which measurement to send.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMeasurementRequest(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* Stream Data
*
* @param[in] index Sequence number which is increase by one for each stream data event sent.
* @param[in] data Stream data. (optional) (array[7])
* @param[in] datasize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendStreamData(uint8_t index, uint8_t const * const data, uint8_t dataSize);
/**
* Sync
*
* @param[in] index Sensor index for a sensor within a module (see data coding). 255 is all sensors.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSync(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* Zoned Stream Data
*
* @param[in] index Sequence number which is increase by one for each stream data event sent.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] data Stream data. (optional) (array[5])
* @param[in] datasize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendZonedStreamData(uint8_t index, uint8_t zone, uint8_t subZone, uint8_t const * const data, uint8_t dataSize);
/**
* Set Pre-set
*
* @param[in] presetCode Code for pre-set to set.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSetPreSet(uint8_t presetCode, uint8_t zone, uint8_t subZone);
/**
* Toggle state
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendToggleState(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Timed pulse on
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] control Control byte.
* @param[in] time Set time as a long with MSB in the first byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendTimedPulseOn(uint8_t userSpecific, uint8_t zone, uint8_t subZone, uint8_t control, uint32_t time);
/**
* Timed pulse off
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] control Control byte.
* @param[in] time Set time as a long with MSB in the first byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendTimedPulseOff(uint8_t userSpecific, uint8_t zone, uint8_t subZone, uint8_t control, uint32_t time);
/**
* Set country/language
*
* @param[in] code Country/Language code.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] codeSpecific Country/Language code specific (array[4])
* @param[in] codeSpecificsize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSetCountryLanguage(uint8_t code, uint8_t zone, uint8_t subZone, uint8_t const * const codeSpecific, uint8_t codeSpecificSize);
/**
* Big Change level
*
* @param[in] index Index.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] level Level as signed Integer. The range can be adjusted by the user by sending the
* needed number of bytes 1-5.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendBigChangeLevel(uint8_t index, uint8_t zone, uint8_t subZone, int32_t level);
/**
* Move shutter up
*
* @param[in] index Index.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMoveShutterUp(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* Move shutter down
*
* @param[in] index Index.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMoveShutterDown(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* Move shutter left
*
* @param[in] index Index.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMoveShutterLeft(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* Move shutter right
*
* @param[in] index Index.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMoveShutterRight(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* Move shutter to middle position
*
* @param[in] index Index.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMoveShutterToMiddlePosition(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* Move shutter to preset position
*
* @param[in] index Index.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendMoveShutterToPresetPosition(uint8_t index, uint8_t zone, uint8_t subZone);
/**
* (All) Lamp(s) on
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendAllLampSOn(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* (All) Lamp(s) off
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendAllLampSOff(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Lock
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendLock(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* Unlock
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-Zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendUnlock(uint8_t userSpecific, uint8_t zone, uint8_t subZone);
/**
* PWM set
*
* @param[in] repeats Repeat/counter: 0=repeat forever, >0 number of repeats
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] control Control byte.
* @param[in] timeOn Time-On
* @param[in] timeOff Time-Off
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendPwmSet(uint8_t repeats, uint8_t zone, uint8_t subZone, uint8_t control, uint16_t timeOn, uint16_t timeOff);
/**
* Lock with token
*
* @param[in] reserved Not used.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] token Token. This token can be 1-5 bytes and length of event is set accordingly. It
* should be interpreted as an unsigned integer in the range 0-1099511627775. MSB byte is stored in
* first byte. (array[5])
* @param[in] tokensize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendLockWithToken(uint8_t reserved, uint8_t zone, uint8_t subZone, uint8_t const * const token, uint8_t tokenSize);
/**
* Unlock with token
*
* @param[in] reserved Not used.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] token Token. This token can be 1-5 bytes and length of event is set accordingly. It
* should be interpreted as an unsigned integer in the range 0-1099511627775. MSB byte is stored in
* first byte. (array[5])
* @param[in] tokensize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendUnlockWithToken(uint8_t reserved, uint8_t zone, uint8_t subZone, uint8_t const * const token, uint8_t tokenSize);
/**
* Set security level
*
* @param[in] securityLevel Security level to set. 0-255 (Higher value is higher security level).
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSetSecurityLevel(uint8_t securityLevel, uint8_t zone, uint8_t subZone);
/**
* Set security pin
*
* @param[in] reserved Not used.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] securityPin Security pin. This pin can be 1-5 bytes and length of event is set
* accordingly. It should be interpreted as an unsigned integer in the range 0-1099511627775. MSB byte
* is stored in first byte. (array[5])
* @param[in] securityPinsize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSetSecurityPin(uint8_t reserved, uint8_t zone, uint8_t subZone, uint8_t const * const securityPin, uint8_t securityPinSize);
/**
* Set security password
*
* @param[in] reserved Not used.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] securityPassword Security password. This password can be 1-5 bytes and length of event
* is set accordingly. It should be interpreted as an UTF-8 string with a length set bt event data
* length - 3 (array[5])
* @param[in] securityPasswordsize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSetSecurityPassword(uint8_t reserved, uint8_t zone, uint8_t subZone, uint8_t const * const securityPassword, uint8_t securityPasswordSize);
/**
* Set security token
*
* @param[in] reserved Not used.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
* @param[in] token Token. This token can be 1-5 bytes and length of event is set accordingly. It
* should be interpreted as an unsigned integer in the range 0-1099511627775. MSB byte is stored in
* first byte. (array[5])
* @param[in] tokensize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendSetSecurityToken(uint8_t reserved, uint8_t zone, uint8_t subZone, uint8_t const * const token, uint8_t tokenSize);
/**
* Request new security token
*
* @param[in] reserved Not used.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones.
* @param[in] subZone Sub-zone for which event applies to (0-255). 255 is all sub-zones.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendRequestNewSecurityToken(uint8_t reserved, uint8_t zone, uint8_t subZone);
/**
* Increment
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones
* @param[in] subzone Sub-zone for which event applies to (0-255). 255 is all sub-zones
* @param[in] incrementValue Increment as unsigned integer. The range can be adjusted by the user by
* sending just the needed number of bytes (1-5) which form the unsigned integer (MSB first). If
* omitted (or 0) 1 is assumed as default increment value (optional) (array[5])
* @param[in] incrementValuesize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendIncrement(uint8_t userSpecific, uint8_t zone, uint8_t subzone, uint8_t const * const incrementValue, uint8_t incrementValueSize);
/**
* Decrement
*
* @param[in] userSpecific User specific value.
* @param[in] zone Zone for which event applies to (0-255). 255 is all zones
* @param[in] subzone Sub-zone for which event applies to (0-255). 255 is all sub-zones
* @param[in] decrementValue Decrement as unsigned integer. The range can be adjusted by the user by
* sending just the needed number of bytes (1-5) which form the unsigned integer (MSB first). If
* omitted (or 0) 1 is assumed as default decrement value (optional) (array[5])
* @param[in] decrementValuesize Size in byte.
*
* @return If event is sent, it will return TRUE otherwise FALSE.
*/
extern BOOL vscp_evt_control_sendDecrement(uint8_t userSpecific, uint8_t zone, uint8_t subzone, uint8_t const * const decrementValue, uint8_t decrementValueSize);
#endif /* __VSCP_EVT_CONTROL_H__ */
|
#!/bin/sh
env="MPE"
scenario="rel_formation_form_error"
num_landmarks=1
num_agents=4
algo="rmappo"
exp="08-14-rel-formation-form-nav10-train-mpe-3600-R"
seed_max=1
echo "env is ${env}, scenario is ${scenario}, algo is ${algo}, exp is ${exp}, max seed is ${seed_max}"
for seed in `seq ${seed_max}`;
do
let "seed=$seed+1"
echo "seed is ${seed}:"
CUDA_VISIBLE_DEVICES=0 python render/render_mpe.py \
--env_name ${env} \
--algorithm_name ${algo} \
--experiment_name ${exp} \
--scenario_name ${scenario} \
--num_agents ${num_agents} \
--num_landmarks ${num_landmarks} \
--seed ${seed} \
--n_training_threads 1 \
--n_rollout_threads 1 \
--avoid-rew-weight 5 \
--form-rew-weight 0.05 \
--nav-rew-weight 10 \
--num_static_obs 10 \
--use_render \
--episode_length 250 \
--render_episodes 5 \
--num_static_obs 0 \
--model_dir "/home/yanyz/yanyz/gitlab/onpolicy/onpolicy/scripts/results/MPE/rel_formation_form_error/rmappo/08-14-rel-formation-form-nav10-train-mpe-3600/run1/models" \
--save_gifs \
--eval_interval 250 \
--map-max-size 3600
done |
<reponame>Project-XPolaris/YouComuic-Studio
// export function getImageUniqUrl() {
//
// }
|
/**
* Copyright 2020 The Magma Authors.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* 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.
*
* @flow strict-local
* @format
*/
jest.mock('@fbcnms/sequelize-models');
import {Organization} from '@fbcnms/sequelize-models';
import {getOrganization} from '@fbcnms/express-middleware/organizationMiddleware';
const ORGS = [
{
id: 1,
name: 'custom_domain_org',
customDomains: ['subdomain.localtest.me'],
networkIDs: [],
csvCharset: '',
ssoCert: '',
ssoEntrypoint: '',
ssoIssuer: '',
},
{
id: 2,
name: 'subdomain',
customDomains: [],
networkIDs: [],
csvCharset: '',
ssoCert: '',
ssoEntrypoint: '',
ssoIssuer: '',
},
];
describe('organization tests', () => {
beforeAll(async () => {
ORGS.forEach(async organization => await Organization.create(organization));
});
it('should allow custom domain', async () => {
const request = {
get: () => 'subdomain.localtest.me',
};
const org = await getOrganization(request);
expect(org.name).toBe('custom_domain_org');
});
it('should allow org by subdomain', async () => {
const request = {
get: () => 'subdomain.phbcloud.io',
};
const org = await getOrganization(request);
expect(org.name).toBe('subdomain');
});
it('should throw an exception when no org is found', async () => {
const request = {
get: () => 'unknowndomain.com',
};
await expect(getOrganization(request)).rejects.toThrow();
});
});
|
import React from 'react'
import { View, Text, TouchableOpacity, StyleSheet, Alert } from 'react-native'
import { Layout, Common, Images, Colors } from '@/Theme'
import { useTranslation } from 'react-i18next'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { useState } from 'react/cjs/react.development'
import { SharedElement } from 'react-native-shared-element'
import FastImage from 'react-native-fast-image'
import { useFirebase } from 'react-redux-firebase'
import FormInput from '@/Components/FormInput'
const ForgotPasswordScreen = ({ navigation }) => {
const { t } = useTranslation()
const [email, setEmail] = useState('')
const firebase = useFirebase()
const onLoginPress = async () => {
try {
await firebase.resetPassword(email)
Alert.alert(
t('auth_forgot_password_success'),
t('auth_forgot_password_success_message'),
)
navigation.pop()
} catch (ex) {
Alert.alert(t('auth_login_failed'), t('auth_login_failed_message'))
}
}
return (
<View style={[Layout.fill, Layout.row]}>
<KeyboardAwareScrollView
style={{ flex: 1, width: '100%' }}
keyboardShouldPersistTaps="handled"
>
<View style={styles.container}>
<SharedElement id="animation">
<FastImage source={Images.logo} style={styles.logo} />
</SharedElement>
<View style={styles.titleContainer}>
<Text style={[Common.text, styles.title]}>
{t('auth_forgot_password_title')}
</Text>
<Text style={[Common.text, styles.description]}>
{t('auth_forgot_password_des')}
</Text>
</View>
<View style={[Layout.fill, Layout.fullSize, styles.inputContainer]}>
<FormInput
placeholder={t('auth_profile_email')}
placeholderTextColor={Colors.placeholder}
onChangeText={(text) => setEmail(text)}
value={email}
underlineColorAndroid="transparent"
autoCapitalize="none"
iconType="user"
/>
<TouchableOpacity
style={[Common.button, styles.loginButton]}
onPress={() => onLoginPress()}
>
<Text style={Common.buttonTitle}>
{t('auth_forgot_password_button')}
</Text>
</TouchableOpacity>
</View>
</View>
</KeyboardAwareScrollView>
</View>
)
}
ForgotPasswordScreen.sharedElements = () => [
{ id: 'image' },
{ id: 'text', animation: 'fade' },
]
export default ForgotPasswordScreen
const styles = StyleSheet.create({
container: {
alignItems: 'center',
paddingHorizontal: 60,
paddingTop: 60,
},
animation: {
width: 300,
height: 300,
marginHorizontal: 'auto',
},
logo: {
width: 100,
height: 100,
marginBottom: 30,
},
titleContainer: {
alignContent: 'center',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 20,
},
title: {
color: Colors.primary,
fontSize: 24,
textAlign: 'center',
},
description: {
color: Colors.text,
fontSize: 14,
textAlign: 'center',
},
appName: {
color: Colors.primary,
},
loginButton: {
marginTop: 10,
},
forgotButton: {
marginTop: 10,
alignSelf: 'flex-end',
},
navButtonText: {
fontWeight: '500',
color: Colors.primary,
},
})
|
require('./bootstrap');
import React ,{ Component }from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { Provider } from 'react-redux';
import Master from './components/Master';
import Example from './components/Example';
import Test_Router_react from './components/Test_Router_react';
import Search from './components/TestAd/Search';
import Table from './components/TestAd/Table';
import Them from './components/TestAd/Them';
import TestRedux from './components/TestRedux';
import DataUser from './components/TestAd/data.json'
import store1 from './components/Store'
import CreateItem from './components/CreateItem';
import DisplayItemS from './components/DisplayItem';
import Home from './components/Home';
import DisplayItem from './components/DisplayItem';
import Chat_rom from './components/Chat_rom';
// Echo.private('chat')
// .listen('MessageSent', (e) => {
// // console.log(e.update);
// console.log(e);
// })
render(<Chat_rom />, document.getElementById('chat'));
render(<Master/>,document.getElementById('master_react'));
// render(<Example name="ahihi" />, document.getElementById('example'));
// render(<Test_Router_react />, document.getElementById('Test_Router_react'));
// render(<Search />, document.getElementById('Search'));
// render(<Table />, document.getElementById('Table'));
// render(<Them />, document.getElementById('Them'));
export default app;
|
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const router = express.Router();
router.post('/signup', (req, res) => {
const { name, email, password } = req.body;
const hashedPassword = bcrypt.hash(password, 10);
// Database query here to save user information
res.json({
message: 'User Created',
token: jwt.sign({ userId: 1 }, process.env.SECRET)
});
});
router.post('/login', (req, res) => {
const { email, password } = req.body;
// Database query to retrieve user with matching email
const isCorrectPassword = bcrypt.compareSync(password, dbUser.password);
if (isCorrectPassword) {
res.json({
message: 'Logged in successfully',
token: jwt.sign({ userId: dbUser.id }, process.env.SECRET)
});
} else {
res.json({
message: 'Invalid credentials'
});
}
});
module.exports = router; |
<gh_stars>0
import React, { FunctionComponent, ReactNode } from 'react';
import { EuiIcon } from '../../../../src/components/icon';
import { EuiCode } from '../../../../src/components/code';
import { EuiText } from '../../../../src/components/text';
import {
computed,
EuiThemeProvider,
useEuiTheme,
} from '../../../../src/services';
import { shade, tint } from '../../../../src/services/color';
interface ThemeExtensions {
colors: {
customColorPrimary: string;
customColorPrimaryHighlight: string;
customColorPrimaryText: string;
};
}
const Box: FunctionComponent<{ children: ReactNode }> = ({ children }) => {
const { euiTheme } = useEuiTheme<ThemeExtensions>();
return (
<EuiText
css={{
background: euiTheme.colors.customColorPrimaryHighlight,
padding: euiTheme.size.xl,
color: euiTheme.colors.customColorPrimaryText,
}}
>
<p>
<EuiIcon type="stopFilled" color={euiTheme.colors.customColorPrimary} />{' '}
{children}
</p>
</EuiText>
);
};
export default () => {
const primaryOverrides = {
colors: {
LIGHT: {
customColorPrimary: 'rgb(29, 222, 204)',
customColorPrimaryHighlight: computed(
(customColorPrimary) => tint(customColorPrimary, 0.8),
'colors.customColorPrimary'
),
customColorPrimaryText: computed(
(customColorPrimary) => shade(customColorPrimary, 0.8),
'colors.customColorPrimary'
),
},
DARK: {
customColorPrimary: 'rgb(29, 222, 204)',
customColorPrimaryHighlight: computed(
([customColorPrimary]) => shade(customColorPrimary, 0.8),
['colors.customColorPrimary']
),
customColorPrimaryText: computed(
([customColorPrimary]) => tint(customColorPrimary, 0.8),
['colors.customColorPrimary']
),
},
},
};
return (
<div>
<EuiThemeProvider modify={primaryOverrides}>
<Box>
A new key of <EuiCode>customColorPrimary</EuiCode> has been added as{' '}
<EuiCode>rgb(29, 222, 204)</EuiCode>.
<br />
<br />
There is also two new computed color keys create off of this for
better contrast.
</Box>
</EuiThemeProvider>
</div>
);
};
|
def createWisecrack(input):
movie_name = input[0]
# create wisecrack based on input
# ...
return wisecrack |
#!/usr/bin/env bash
CURDIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CURDIR"/../shell_config.sh
REPLICAS=3
for i in $(seq $REPLICAS); do
$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS concurrent_alter_add_drop_$i"
done
for i in $(seq $REPLICAS); do
$CLICKHOUSE_CLIENT --query "CREATE TABLE concurrent_alter_add_drop_$i (key UInt64, value0 UInt8) ENGINE = ReplicatedMergeTree('/clickhouse/tables/$CLICKHOUSE_TEST_ZOOKEEPER_PREFIX/concurrent_alter_add_drop_column', '$i') ORDER BY key SETTINGS max_replicated_mutations_in_queue=1000, number_of_free_entries_in_pool_to_execute_mutation=0,max_replicated_merges_in_queue=1000"
done
$CLICKHOUSE_CLIENT --query "INSERT INTO concurrent_alter_add_drop_1 SELECT number, number + 10 from numbers(100000)"
for i in $(seq $REPLICAS); do
$CLICKHOUSE_CLIENT --query "SYSTEM SYNC REPLICA concurrent_alter_add_drop_$i"
done
function alter_thread()
{
while true; do
REPLICA=$(($RANDOM % 3 + 1))
ADD=$(($RANDOM % 5 + 1))
$CLICKHOUSE_CLIENT --query "ALTER TABLE concurrent_alter_add_drop_$REPLICA ADD COLUMN value$ADD UInt32 DEFAULT 42 SETTINGS replication_alter_partitions_sync=0"; # additionaly we don't wait anything for more heavy concurrency
DROP=$(($RANDOM % 5 + 1))
$CLICKHOUSE_CLIENT --query "ALTER TABLE concurrent_alter_add_drop_$REPLICA DROP COLUMN value$DROP SETTINGS replication_alter_partitions_sync=0"; # additionaly we don't wait anything for more heavy concurrency
sleep 0.$RANDOM
done
}
function optimize_thread()
{
while true; do
REPLICA=$(($RANDOM % 3 + 1))
$CLICKHOUSE_CLIENT --query "OPTIMIZE TABLE concurrent_alter_add_drop_$REPLICA FINAL SETTINGS replication_alter_partitions_sync=0";
sleep 0.$RANDOM
done
}
function insert_thread()
{
while true; do
REPLICA=$(($RANDOM % 3 + 1))
$CLICKHOUSE_CLIENT --query "INSERT INTO concurrent_alter_add_drop_$REPLICA VALUES($RANDOM, 7)"
sleep 0.$RANDOM
done
}
echo "Starting alters"
export -f alter_thread;
export -f optimize_thread;
export -f insert_thread;
TIMEOUT=30
# Sometimes we detach and attach tables
timeout $TIMEOUT bash -c alter_thread 2> /dev/null &
timeout $TIMEOUT bash -c alter_thread 2> /dev/null &
timeout $TIMEOUT bash -c alter_thread 2> /dev/null &
timeout $TIMEOUT bash -c optimize_thread 2> /dev/null &
timeout $TIMEOUT bash -c optimize_thread 2> /dev/null &
timeout $TIMEOUT bash -c optimize_thread 2> /dev/null &
timeout $TIMEOUT bash -c insert_thread 2> /dev/null &
timeout $TIMEOUT bash -c insert_thread 2> /dev/null &
timeout $TIMEOUT bash -c insert_thread 2> /dev/null &
timeout $TIMEOUT bash -c insert_thread 2> /dev/null &
timeout $TIMEOUT bash -c insert_thread 2> /dev/null &
wait
echo "Finishing alters"
columns1=$($CLICKHOUSE_CLIENT --query "select count() from system.columns where table='concurrent_alter_add_drop_1'" 2> /dev/null)
columns2=$($CLICKHOUSE_CLIENT --query "select count() from system.columns where table='concurrent_alter_add_drop_2'" 2> /dev/null)
columns3=$($CLICKHOUSE_CLIENT --query "select count() from system.columns where table='concurrent_alter_add_drop_3'" 2> /dev/null)
while [ "$columns1" != "$columns2" ] || [ "$columns2" != "$columns3" ]; do
columns1=$($CLICKHOUSE_CLIENT --query "select count() from system.columns where table='concurrent_alter_add_drop_1'" 2> /dev/null)
columns2=$($CLICKHOUSE_CLIENT --query "select count() from system.columns where table='concurrent_alter_add_drop_2'" 2> /dev/null)
columns3=$($CLICKHOUSE_CLIENT --query "select count() from system.columns where table='concurrent_alter_add_drop_3'" 2> /dev/null)
sleep 1
done
echo "Equal number of columns"
# This alter will finish all previous, but replica 1 maybe still not up-to-date
while [[ $(timeout 120 ${CLICKHOUSE_CLIENT} --query "ALTER TABLE concurrent_alter_add_drop_1 MODIFY COLUMN value0 String SETTINGS replication_alter_partitions_sync=2" 2>&1) ]]; do
sleep 1
done
for i in $(seq $REPLICAS); do
$CLICKHOUSE_CLIENT --query "SYSTEM SYNC REPLICA concurrent_alter_add_drop_$i"
$CLICKHOUSE_CLIENT --query "SELECT COUNT() FROM system.mutations WHERE is_done = 0 and table = 'concurrent_alter_add_drop_$i'"
$CLICKHOUSE_CLIENT --query "SELECT * FROM system.mutations WHERE is_done = 0 and table = 'concurrent_alter_add_drop_$i'"
$CLICKHOUSE_CLIENT --query "SELECT COUNT() FROM system.replication_queue WHERE table = 'concurrent_alter_add_drop_$i'"
$CLICKHOUSE_CLIENT --query "SELECT * FROM system.replication_queue WHERE table = 'concurrent_alter_add_drop_$i' and (type = 'ALTER_METADATA' or type = 'MUTATE_PART')"
$CLICKHOUSE_CLIENT --query "DROP TABLE IF EXISTS concurrent_alter_add_drop_$i"
done
|
<reponame>Isaquehg/algorithms_and_data_structures
//T(n) = n/2
#include <iostream>
using namespace std;
int main(){
int i, j;//contadores
int x;//aux
int cont = 0;
int n;//tamanho do problema
cin >> n;
for(i = 0; i < n; i += 2){
x = i * 2;
cont ++;
}
cout << cont << endl;
return 0;
} |
package uk.joshiejack.husbandry.note;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import uk.joshiejack.husbandry.Husbandry;
import uk.joshiejack.husbandry.entity.stats.Species;
import uk.joshiejack.penguinlib.note.Note;
import uk.joshiejack.penguinlib.note.type.NoteType;
import javax.annotation.Nonnull;
import java.util.List;
public class LifespanNoteType extends NoteType {
private ITextComponent component;
public LifespanNoteType() {
super("lifespan");
}
@Nonnull
public ITextComponent getText(Note note) {
if (component != null) return component;
component = note.getText();
List<ITextComponent> list = component.getSiblings();
Species.TYPES.forEach((type, species) -> {
list.add(new StringTextComponent("\n ")); //newline before
list.add(new TranslationTextComponent("note.type.husbandry.lifespan", type.getDescription(),
(species.getMinAge() / Husbandry.HusbandryConfig.daysPerYear.get()),
(species.getMaxAge() / Husbandry.HusbandryConfig.daysPerYear.get())));
});
return component;
}
} |
<gh_stars>0
#!/usr/bin/python
import execnet, execnet.gateway, execnet.multi
class SshPortGateway(execnet.gateway.SshGateway):
def __init__(self, sshaddress, id, remotepython = None,
ssh_config=None,
ssh_port=None,
ssh_identity=None,
ssh_batchmode=None):
self.remoteaddress = sshaddress
if not remotepython: remotepython = "python"
args = ['ssh', '-C' ]
if ssh_config: args.extend(['-F', ssh_config])
if ssh_port: args.extend(['-p', ssh_port])
if ssh_identity: args.extend(['-i', ssh_identity])
if ssh_batchmode: args.extend(["-o", "BatchMode yes"])
remotecmd = '%s -c "%s"' % (remotepython, execnet.gateway.popen_bootstrapline)
args.extend([sshaddress, remotecmd])
execnet.gateway.PopenCmdGateway.__init__(self, args, id=id)
def makeportgateway(self, spec):
spec = execnet.XSpec(spec)
self.allocate_id(spec)
gw = SshPortGateway(spec.ssh,
remotepython=spec.python,
ssh_config=spec.ssh_config,
id=spec.id,
ssh_port=spec.ssh_port,
ssh_identity=spec.ssh_identity,
ssh_batchmode=spec.ssh_batchmode)
gw.spec = spec
self._register(gw)
# TODO add spec.{chdir,nice,env}
return gw
execnet.multi.Group.makeportgateway = makeportgateway
execnet.makeportgateway = execnet.multi.default_group.makeportgateway
# originally posted as http://code.activestate.com/recipes/577545-monkey-patch-execnet-with-more-ssh-settings-port-i/
|
export default class DateTime {
constructor(date = new Date()) {
this.date = new Date(date);
}
/**
* Get milliseconds elapsed since 1 January 1970 00:00:00 UTC.
* @return {number}
*/
getTime() {
return this.date.getTime();
}
/**
* Get month. 0 for january ... 11 for december.
* @return {number}
*/
getMonth() {
return this.date.getMonth();
}
/**
* Get year.
* @return {number}
*/
getYear() {
return this.date.getFullYear();
}
/**
* Set day.
* @param {number} day Day to be established.
* @return {DateTime}
*/
setDay(day) {
this.date = new Date(this.date.setDate(day));
return this;
}
}
|
<reponame>minazukihotaru/tiny-spring
package com.example.test;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.example.beans.BeanDefinition;
import com.example.beans.BeanReference;
import com.example.beans.PropertyValue;
import com.example.beans.PropertyValues;
import com.example.beans.factory.AutowireCapableBeanFactory;
import com.example.beans.io.ResourceLoader;
import com.example.beans.io.UrlResourceLoader;
import com.example.beans.xml.XmlBeanDefinitionReader;
public class TestApplication {
/*
*
* @ IOC容器实现
* @ 2019-12-12
*/
@Test
public void testIOC() throws Exception {
// 初始化工厂
AutowireCapableBeanFactory beanFactory = new AutowireCapableBeanFactory();
// 定义UserInfo类的bean
BeanDefinition beanDefinition_UserInfo = new BeanDefinition();
beanDefinition_UserInfo.setBeanClassName("com.example.test.UserInfo");
beanDefinition_UserInfo.setBeanClass(Class.forName("com.example.test.UserInfo"));
// 将UserInfo类的属性列表放入UserInfo的bean定义中
PropertyValue pv_UserInfo_info = new PropertyValue("info", "用户信息");
PropertyValues pvs_UserInfo = new PropertyValues();
pvs_UserInfo.addPropertyValue(pv_UserInfo_info);
beanDefinition_UserInfo.setPropertyValues(pvs_UserInfo);
// 在工厂注册UserInfo的bean定义,可通过getBean("getuserinfo")获取一个UserInfo类型的bean
beanFactory.registerBeanDefinition("getuserinfo", beanDefinition_UserInfo);
// 定义User类的bean
BeanDefinition beanDefinition_User = new BeanDefinition();
beanDefinition_User.setBeanClassName("com.example.test.User");
beanDefinition_User.setBeanClass(Class.forName("com.example.test.User"));
// User类的属性列表中有ref
BeanReference ref = new BeanReference("getuserinfo");
// 将User类的属性列表放入User的bean定义中
PropertyValue pv_User_id = new PropertyValue("id", "4396");
PropertyValue pv_User_name = new PropertyValue("name", "小明");
PropertyValue pv_User_userInfo = new PropertyValue("userInfo", ref);
PropertyValues pvs_User = new PropertyValues();
pvs_User.addPropertyValue(pv_User_id);
pvs_User.addPropertyValue(pv_User_name);
pvs_User.addPropertyValue(pv_User_userInfo);
beanDefinition_User.setPropertyValues(pvs_User);
// 在工厂注册User的bean定义,可通过getBean("getuser")获取一个User类型的bean
beanFactory.registerBeanDefinition("getuser", beanDefinition_User);
User user1 = (User) beanFactory.getBean("getuser");
System.out.println(user1);
}
/*
* @测试从Xml文件中获取bean定义
* @ 2019-12-13
*/
@Test
public void testXmlIOC() throws Exception {
XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new UrlResourceLoader());
xmlBeanDefinitionReader.loadBeanDefinitions("testXmlIoc.xml");
Map<String, BeanDefinition> xmlRegistry = xmlBeanDefinitionReader.getRegistry();
AutowireCapableBeanFactory factory = new AutowireCapableBeanFactory();
for(String beanName : xmlRegistry.keySet()) {
factory.registerBeanDefinition(beanName, xmlRegistry.get(beanName));
}
User XiaoMing = (User) factory.getBean("userXiaoMing");
System.out.println(XiaoMing);
/*
<bean id="userXiaoMing" class="com.example.test.User">
<property name="id" value="4396"/>
<property name="name" value="小明"/>
<property name="userInfo" ref="infoXiaoMing"/>
</bean>
<bean id="infoXiaoMing" class="com.example.test.UserInfo">
<property name="info" value="小明的用户信息"/>
</bean>
*/
}
/*
*
* @测试读取xml文件
*
*
*/
@Test
public void testReadXml() throws IOException, ParserConfigurationException, SAXException {
URL url = getClass().getClassLoader().getResource("testXmlIoc.xml");
URLConnection connection = url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
NodeList beanList = doc.getElementsByTagName("bean");
System.out.println("beanListsize="+beanList.getLength());
Node bean_1 = beanList.item(0);
Element ele_bean_1 = (Element)bean_1;
System.out.println("bean1 id="+ele_bean_1.getAttribute("id"));
NodeList propertyList = ele_bean_1.getElementsByTagName("property");// element.get...方法获取element的子节点
Node property_1 = propertyList.item(0);
Element ele_property_1 = (Element) property_1;
System.out.println("property1 name="+ ele_property_1.getAttribute("name"));
}
}
|
#!/usr/bin/env bats
load ../helpers
function teardown() {
swarm_manage_cleanup
stop_docker
}
@test "docker stop" {
start_docker_with_busybox 2
swarm_manage
# run
docker_swarm run -d --name test_container busybox sleep 500
# make sure container is up before stop
# FIXME(#748): Retry required because of race condition.
retry 5 0.5 eval "[ -n $(docker_swarm ps -q --filter=name=test_container --filter=status=running) ]"
# stop
docker_swarm stop test_container
# verify
# FIXME(#748): Retry required because of race condition.
retry 5 0.5 eval "[ -n $(docker_swarm ps -q --filter=name=test_container --filter=status=exited) ]"
}
|
#!/usr/bin/env bash
#
# The copyright header is deliberately placed below the shebang line because
# the OS only looks at the first two bytes to determine which executable to use.
#
# Copyright Yahoo 2021
# Licensed under the terms of the Apache License 2.0.
# See LICENSE file in project root for terms.
#
# This script should only be invoked by "go generate"
# because it makes sure that the current working directory is the project root,
# so the tool binaries will be placed inside the bin directory of this project,
# and they will be git-ignored.
set -euo pipefail
main() {
# Since different projects may have different versions of mockgen,
# we first install mockgen of the version specified in the go.mod of this project,
# and the binary will be placed under the bin directory of this project and git-ignored.
GOBIN=$(pwd)/bin
export GOBIN
go install github.com/golang/mock/mockgen
# Make sure that we are using the mockgen which is just built to generate mocks code.
export PATH=$GOBIN:$PATH
mockgen -package mocks -destination ../mocks/driver_mock.go database/sql/driver Driver
mockgen -package mocks -destination ../mocks/conn_pool_mgr_mock.go . ConnPoolMgr
mockgen -package mocks -destination ../mocks/storage_mock.go . Storage
mockgen -package mocks -destination ../mocks/credentials_creator_mock.go . CredentialsCreator
mockgen -package storage -destination storage_creator_mock_test.go . StorageCreator
}
main
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Bliss(Package):
"""bliss: A Tool for Computing Automorphism Groups and Canonical
Labelings of Graphs"""
homepage = "http://www.tcs.hut.fi/Software/bliss/"
url = "http://www.tcs.hut.fi/Software/bliss/bliss-0.73.zip"
version('0.73', '72f2e310786923b5c398ba0fc40b42ce')
# Note: Bliss can also be built without gmp, but we don't support this yet
depends_on("gmp")
depends_on("libtool", type='build')
patch("Makefile.spack.patch")
def install(self, spec, prefix):
# The Makefile isn't portable; use our own instead
makeargs = ["-f", "Makefile.spack",
"PREFIX=%s" % prefix, "GMP_PREFIX=%s" % spec["gmp"].prefix]
make(*makeargs)
make("install", *makeargs)
|
<reponame>rawheel/My-Unfollowers-App<filename>src/services/index.js<gh_stars>1-10
import * as myunfollowersapi from './api-services/myunfollowersapi'
export default{
myunfollowersapi
} |
//
// PDNetworkPluginManager.h
// PDNetworking
//
// Created by liang on 2021/3/4.
//
#import <Foundation/Foundation.h>
#import "PDNetworkPlugin.h"
NS_ASSUME_NONNULL_BEGIN
@protocol PDNetworkPluginNotify <NSObject>
- (void)requestWillStartLoad:(PDNetworkRequest *)request;
- (void)requestDidFinishLoad:(PDNetworkRequest *)request withResponse:(id<PDNetworkResponse>)response;
- (void)requestDidFinishUpload:(PDNetworkRequest *)request withResponse:(id<PDNetworkUploadResponse>)response;
- (void)requestDidFinishDownload:(PDNetworkRequest *)request withResponse:(id<PDNetworkDownloadResponse>)response;
@end
@interface PDNetworkPluginManager : NSObject <PDNetworkPluginNotify>
@property (class, strong, readonly) PDNetworkPluginManager *defaultManager;
@property (nonatomic, copy, readonly) NSDictionary<NSString *, id<PDNetworkPlugin>> *pluginMap;
@property (nonatomic, copy, readonly) NSArray<id<PDNetworkPlugin>> *plugins;
@end
NS_ASSUME_NONNULL_END
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.