text
stringlengths 27
775k
|
|---|
CREATE PROCEDURE [dbo].[prc_BatchUpdateChangeGroupsStatus]
@SessionUniqueId uniqueidentifier,
@SourceUniqueId uniqueidentifier,
@CurrStatus int,
@NewStatus int
AS
UPDATE [dbo].[RUNTIME_CHANGE_GROUPS]
SET Status = @NewStatus
WHERE SessionUniqueId = @SessionUniqueId
AND SourceUniqueId = @SourceUniqueId
AND Status = @CurrStatus
SELECT *
FROM [dbo].[RUNTIME_CHANGE_GROUPS]
WHERE SessionUniqueId = @SessionUniqueId
AND SourceUniqueId = @SourceUniqueId
AND Status = @CurrStatus
|
resolvers += "phData Releases" at "https://repository.phdata.io/artifactory/libs-release"
classpathTypes += "maven-plugin"
addSbtPlugin("io.phdata" % "sbt-os-detector" % "0.2.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.15.0")
|
/* CONFIG.GO SHOULD BE GITIGNORED -- DB & PORT INFO */
package config
var Port string = ":8000"
var DB string = "mongodb://localhost:27017/"
var DBName string = "sudopost"
var Secret string = ""
var JwtSecret string = ""
var Email = &mail{"emailname", "password", "smtp.gmail.com", 587}
type mail struct {
Username string
Password string
EmailServer string
Port int
}
|
import React from 'react'
import PropTypes from 'prop-types'
import cssModules from 'react-css-modules'
import styles from './AnimeList.module.scss'
import classNames from 'classnames/bind'
import { Tag, Icon, Tooltip } from 'antd'
import { SORTS } from '@/utils/constant'
const cx = classNames.bind(styles)
let Item = ({
date,
type,
subtitle,
title,
size,
magnet,
link,
isChoosing,
index,
toggleChoose,
id,
isChosen
}) => {
return (
<li className={cx('anime-item', { chosen: isChosen })}>
<div styleName="date">{date}</div>
<div styleName="type">
<Tag color="#2db7f5" style={{ margin: 0 }}>
{type}
</Tag>
</div>
<div styleName="subtitle">
{subtitle ? (
<Tag
color="magenta"
style={{
margin: 0,
maxWidth: 100,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
}}
>
{subtitle}
</Tag>
) : null}
</div>
<div styleName="title">
{title}
<a href={link} target="__blank" style={{ marginLeft: 5 }}>
<Icon type="link" />
</a>
</div>
<div styleName="size">
<Tag color="#108ee9">{size}</Tag>
</div>
<div styleName="magnet">
{isChoosing ? (
<Icon
type="check-square"
onClick={() => {
toggleChoose(id, index)
}}
className={cx('chosen-square')}
/>
) : (
<a
href={magnet}
download={magnet}
target="__blank"
style={{ padding: 5 }}
>
<Icon type="download" />
</a>
)}
</div>
</li>
)
}
Item = cssModules(Item, styles)
let Head = ({ sort, onClick, setMode, isChoosing, onConfirm, onCancel }) => (
<li className={cx('anime-item', 'header')}>
<div styleName="date" onClick={() => onClick('date', sort)}>
日期
<div styleName="sort-box">
<Icon
type="caret-up"
style={{ color: sort === SORTS.DATE_ASC ? '#fb7299' : '#888' }}
/>
<Icon
type="caret-down"
style={{ color: sort === SORTS.DATE_DESC ? '#fb7299' : '#888' }}
/>
</div>
</div>
<div styleName="type">类别</div>
<div styleName="subtitle">字幕组</div>
<div styleName="title">标题</div>
<div styleName="size" onClick={() => onClick('size', sort)}>
大小
<div styleName="sort-box">
<Icon
type="caret-up"
style={{ color: sort === SORTS.SIZE_ASC ? '#fb7299' : '#888' }}
/>
<Icon
type="caret-down"
style={{ color: sort === SORTS.SIZE_DESC ? '#fb7299' : '#888' }}
/>
</div>
</div>
<div styleName="magnet">
{isChoosing ? (
<div styleName="sm-box">
<Tooltip title="批量下载">
<Icon type="download" onClick={onConfirm} />
</Tooltip>
<Tooltip title="取消">
<Icon type="close" onClick={onCancel} />
</Tooltip>
</div>
) : (
<Tooltip title="点击批量选择">
<i
className="iconfont icon-cili"
onClick={setMode}
style={{ fontSize: 18 }}
/>
</Tooltip>
)}
</div>
</li>
)
Head = cssModules(Head, styles)
const AnimeList = props => {
const {
data,
sort,
onSortClick,
isChoosing,
setMode,
toggleChoose,
chosenList,
onConfirm,
onCancel
} = props
const handleSort = (type, st) => {
let value
if (type === 'date') {
value = st === SORTS.DATE_DESC ? SORTS.DATE_ASC : SORTS.DATE_DESC
} else {
value = st === SORTS.SIZE_DESC ? SORTS.SIZE_ASC : SORTS.SIZE_DESC
}
onSortClick(value)
}
return (
<div>
<ul styleName="anime-list">
<Head
sort={sort}
onClick={handleSort}
setMode={setMode}
isChoosing={isChoosing}
onCancel={onCancel}
onConfirm={onConfirm}
/>
{data.map((v, index) => (
<Item
toggleChoose={toggleChoose}
{...v}
key={v.magnet}
isChoosing={isChoosing}
index={index}
isChosen={isChoosing && chosenList.indexOf(v.id) > -1}
/>
))}
</ul>
</div>
)
}
AnimeList.propTypes = {
data: PropTypes.array.isRequired,
sort: PropTypes.number,
onSortClick: PropTypes.func,
isChoosing: PropTypes.bool,
setMode: PropTypes.func,
toggleChoose: PropTypes.func,
chosenList: PropTypes.array,
onConfirm: PropTypes.func,
onCancel: PropTypes.func,
}
export default cssModules(AnimeList, styles)
|
# ieee80211
This is a library for parsing IEEE 802.11 WiFi packets into zero-cost data structures.
- Zero-cost abstraction: No parsing work is done until methods are called.
- Idiomatic rust: match-friendly enums for many types
- Fast: built with speed in mind
[Documentation](https://spiralp.github.io/rust-ieee80211/ieee80211/index.html)
## Example
Getting some info out of a beacon packet.
```rust
use ieee80211::*;
const BEACON_PACKET: &[u8] = &[
0x80, 0x00, 0x00, 0x70, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0xe3, 0x41, 0xbd, 0x6e,
0x00, 0x01, 0xe3, 0x41, 0xbd, 0x6e, 0x10, 0xf0, 0x84, 0x21, 0x1a, 0x69, 0x02, 0x00, 0x00, 0x00,
0x64, 0x00, 0x11, 0x04, 0x00, 0x09, 0x6d, 0x61, 0x72, 0x74, 0x69, 0x6e, 0x65, 0x74, 0x33, 0x01,
0x08, 0x82, 0x84, 0x8b, 0x96, 0x24, 0x30, 0x48, 0x6c, 0x03, 0x01, 0x0b, 0x05, 0x04, 0x00, 0x01,
0x00, 0x00, 0x2a, 0x01, 0x04, 0x2f, 0x01, 0x04, 0x32, 0x04, 0x0c, 0x12, 0x18, 0x60, 0xdd, 0x06,
0x00, 0x10, 0x18, 0x01, 0x01, 0x00, 0xdd, 0x16, 0x00, 0x50, 0xf2, 0x01, 0x01, 0x00, 0x00, 0x50,
0xf2, 0x02, 0x01, 0x00, 0x00, 0x50, 0xf2, 0x02, 0x01, 0x00, 0x00, 0x50, 0xf2, 0x02,
];
fn main() {
let frame = Frame::new(&BEACON_PACKET);
let receiver_address = frame.receiver_address();
println!("receiver_address: {}", receiver_address);
// receiver_address: ff-ff-ff-ff-ff-ff
let layer = frame.next_layer().unwrap();
let transmitter_address = match layer {
FrameLayer::Management(ref management_frame) => management_frame.transmitter_address(),
FrameLayer::Control(ref control_frame) => control_frame.transmitter_address(),
FrameLayer::Data(ref data_frame) => data_frame.transmitter_address(),
};
if let Some(transmitter_address) = transmitter_address {
println!("transmitter_address: {}", transmitter_address);
// transmitter_address: 00-01-e3-41-bd-6e
}
if let FrameLayer::Management(ref management_frame) = layer {
let management_frame_layer = management_frame.next_layer().unwrap();
if let ManagementFrameLayer::Beacon(ref beacon_frame) = management_frame_layer {
let ssid = String::from_utf8(beacon_frame.ssid().unwrap()).unwrap();
println!("ssid: {}", ssid);
// ssid: martinet3
println!(
"channel: {}",
beacon_frame.tagged_parameters().channel().unwrap()
);
// channel: 11
println!("privacy: {}", beacon_frame.capabilities_info().privacy);
// privacy: true
}
}
}
```
## License
MIT
|
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// Restrictions:
/// By making use of the Software for military purposes, you choose to make
/// a Bunny unhappy.
///
/// 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.
///
/// @ref gtx_associated_min_max
/// @file glm/gtx/associated_min_max.hpp
/// @date 2008-03-10 / 2014-10-11
/// @author Christophe Riccio
///
/// @see core (dependence)
/// @see gtx_extented_min_max (dependence)
///
/// @defgroup gtx_associated_min_max GLM_GTX_associated_min_max
/// @ingroup gtx
///
/// @brief Min and max functions that return associated values not the compared onces.
/// <glm/gtx/associated_min_max.hpp> need to be included to use these functionalities.
///////////////////////////////////////////////////////////////////////////////////
#pragma once
// Dependency:
#include "../glm.hpp"
#if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED))
# pragma message("GLM: GLM_GTX_associated_min_max extension included")
#endif
namespace glm
{
/// @addtogroup gtx_associated_min_max
/// @{
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P>
GLM_FUNC_DECL U associatedMin(T x, U a, T y, U b);
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL tvec2<U, P> associatedMin(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b);
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
T x, const vecType<U, P>& a,
T y, const vecType<U, P>& b);
/// Minimum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b);
/// Minimum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMin(
T x, U a,
T y, U b,
T z, U c);
/// Minimum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMin(
T x, U a,
T y, U b,
T z, U c,
T w, U d);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c,
vecType<T, P> const & w, vecType<U, P> const & d);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b,
T z, vecType<U, P> const & c,
T w, vecType<U, P> const & d);
/// Minimum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMin(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b,
vecType<T, P> const & z, U c,
vecType<T, P> const & w, U d);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMax(T x, U a, T y, U b);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL tvec2<U, P> associatedMax(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<T, P> associatedMax(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b);
/// Maximum comparison between 2 variables and returns 2 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMax(
T x, U a,
T y, U b,
T z, U c);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<T, P> associatedMax(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b,
T z, vecType<U, P> const & c);
/// Maximum comparison between 3 variables and returns 3 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b,
vecType<T, P> const & z, U c);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U>
GLM_FUNC_DECL U associatedMax(
T x, U a,
T y, U b,
T z, U c,
T w, U d);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, vecType<U, P> const & a,
vecType<T, P> const & y, vecType<U, P> const & b,
vecType<T, P> const & z, vecType<U, P> const & c,
vecType<T, P> const & w, vecType<U, P> const & d);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
T x, vecType<U, P> const & a,
T y, vecType<U, P> const & b,
T z, vecType<U, P> const & c,
T w, vecType<U, P> const & d);
/// Maximum comparison between 4 variables and returns 4 associated variable values
/// @see gtx_associated_min_max
template<typename T, typename U, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<U, P> associatedMax(
vecType<T, P> const & x, U a,
vecType<T, P> const & y, U b,
vecType<T, P> const & z, U c,
vecType<T, P> const & w, U d);
/// @}
} //namespace glm
#include "associated_min_max.inl"
|
import 'package:built_collection/built_collection.dart';
import 'package:flutter/material.dart';
import 'package:fusemodel/fusemodel.dart';
import '../../../services/localutilities.dart';
import '../../player/playertilebasketball.dart';
/// Callback for when a player is selected.
typedef PlayerSelectFunction = void Function(String uid, bool selected);
/// Check to see if this player is selected.
typedef PlayerIsSelected = bool Function(String uid);
///
/// Shows the players as a nice grid to be able to select from to setup who
/// is currently playing.
///
class PlayerMultiselect extends StatelessWidget {
/// Game to get the players for.
final Game game;
/// The season to get the players for.
final Season season;
/// If the player is selected check
final PlayerIsSelected isSelected;
/// Select the specific player.
final PlayerSelectFunction selectPlayer;
/// Orientation to display the users,
final Orientation orientation;
/// Any specific additional players to pass in.
final Map<String, Player> additionalPlayers;
/// The full player details.
final BuiltMap<String, Player> fullPlayerDetails;
List<Widget> _populateList(BuildContext context, Orientation o) {
var players = game.players.keys.toSet();
var seasonPlayers =
season != null ? season.playersData.keys.toList() : <String>[];
seasonPlayers
.removeWhere((element) => (game.ignoreFromSeason.contains(element)));
players.addAll(game.opponents.keys);
players.addAll(seasonPlayers);
if (additionalPlayers != null) {
players.addAll(additionalPlayers.keys);
}
var ordered = players.toList();
ordered.sort((String a, String b) {
var aSummary = game.players[a] ?? game.opponents[a];
var bSummary = game.players[b] ?? game.opponents[b];
var aFull = fullPlayerDetails != null ? fullPlayerDetails[a] : null;
var bFull = fullPlayerDetails != null ? fullPlayerDetails[b] : null;
if (aSummary == null || bSummary == null) {
return 0;
}
if (aSummary.currentlyPlaying) {
if (!bSummary.currentlyPlaying) {
return -1;
}
} else if (bSummary.currentlyPlaying) {
return 1;
}
// Sort by number or name.
if (bSummary.jerseyNumber.isEmpty && aSummary.jerseyNumber.isEmpty) {
// Order by name.
if (aFull != null && bFull != null) {
return aFull.name.compareTo(bFull.name);
}
}
return bSummary.jerseyNumber.compareTo(aSummary.jerseyNumber);
});
Color mainColor;
Color mainColorSelected;
Color selectedBorder;
Color unSelectedBorder;
if (LocalUtilities.isDark(context)) {
mainColor = Theme.of(context).primaryColor;
mainColorSelected = Theme.of(context).primaryColor;
selectedBorder = Theme.of(context).indicatorColor;
unSelectedBorder = Theme.of(context).primaryColor;
} else {
mainColor = LocalUtilities.brighten(Theme.of(context).primaryColor, 96);
mainColorSelected =
LocalUtilities.brighten(Theme.of(context).primaryColor, 90);
selectedBorder = Theme.of(context).indicatorColor;
unSelectedBorder =
LocalUtilities.brighten(Theme.of(context).primaryColor, 60);
}
return ordered
.map(
(String playerUid) => Padding(
padding: EdgeInsets.all(2.0),
child: PlayerTileBasketball(
playerUid: playerUid,
gameUid: game.uid,
showSummary: false,
color: isSelected(playerUid) ? mainColorSelected : mainColor,
shape: ContinuousRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
side: BorderSide(
color:
isSelected(playerUid) ? selectedBorder : unSelectedBorder,
width: 3.0,
),
),
onTap: (String playerUid) =>
selectPlayer(playerUid, isSelected(playerUid)),
),
),
)
.toList();
}
/// Create the player multiselect widget.
PlayerMultiselect(
{@required this.game,
@required this.season,
@required this.isSelected,
@required this.selectPlayer,
this.additionalPlayers,
this.fullPlayerDetails,
this.orientation = Orientation.portrait});
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, layout) {
var cols = layout.maxWidth ~/ 200;
if (cols < 2) {
cols = 2;
}
var aspectRatio = (layout.maxWidth / cols) / 80.0;
return GridView.count(
childAspectRatio: aspectRatio,
crossAxisCount: cols,
shrinkWrap: true,
children: _populateList(context, orientation),
);
});
}
}
|
//------------------------------------------------------------------------------
// <copyright file="XPathQueryIterator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/**************************************************************************\
*
* Copyright (c) 1998-2002, Microsoft Corp. All Rights Reserved.
*
* Module Name:
*
* XPathQueryIterator.cs
*
* Abstract:
*
* Revision History:
*
\**************************************************************************/
namespace System.Xml.XPath {
using System;
using System.Diagnostics;
internal class XPathQueryIterator: ResetableIterator {
XPathNavigator nav;
IQuery query;
int position;
public XPathQueryIterator(IQuery query, XPathNavigator nav) {
this.nav = nav;
this.query = query;
this.query.setContext(nav);
}
public override ResetableIterator MakeNewCopy() {
return new XPathQueryIterator(query.Clone(), nav.Clone());
}
public override XPathNavigator Current {
get { return nav; }
}
public override int CurrentPosition {
get { return position; }
}
public override bool MoveNext() {
nav = query.advance();
if(nav != null) {
position ++;
return true;
}else {
return false;
}
}
public override void Reset() {
query.reset();
}
public override XPathNodeIterator Clone() {
XPathQueryIterator clone = new XPathQueryIterator(query.Clone(), nav.Clone());
clone.MoveToPosition(this.CurrentPosition);
Debug.Assert(this.CurrentPosition == clone.CurrentPosition);
return clone;
}
}
}
|
<?php
$app->get('/session', function () {
$session = SessionHander::getInstance()->getSession();
$response["uid"] = $session['uid'];
$response["email"] = $session['email'];
$response["username"] = $session['username'];
echoResponse(200, $session);
});
$app->get('/logout', function () {
$session = SessionHander::getInstance()->destroySession();
$response["status"] = "info";
$response["message"] = "Wylogowany pomyślnie.";
echoResponse(200, $response);
});
$app->post('/login', function () use ($app) {
$r = json_decode($app->request->getBody());
verifyRequiredParams(array('username', 'password'), $r);
$response = array();
$password = $r->password;
$username = $r->username;
$user = Database::getInstance()->getAdminByUsernameOrEmail($username);
if ($user != NULL) {
if (sha1($password) == $user->getPassword()) {
$response['status'] = "success";
$response['message'] = "Poprawnie zalogowany. Witaj $username !";
$response['username'] = $user->getUsername();
$response['uid'] = $user->getId();
$response['email'] = $user->getEmail();
$response['createdAt'] = $user->getCreateTime();
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['uid'] = $user->getId();
$_SESSION['email'] = $user->getEmail();
$_SESSION['username'] = $user->getUsername();
} else {
$response['status'] = "error";
$response['message'] = 'Logowanie nie powiodło się. Niepoprawne dane.';
}
} else {
$response['status'] = "error";
$response['message'] = 'Taki użytkownik nie jest zarejestrowany.';
}
echoResponse(200, $response);
});
?>
|
import { ESLintUtils } from '@typescript-eslint/experimental-utils'
import rule from '../../src/rules/test-for-null-using-isNullObject';
const ruleTester = new ESLintUtils.RuleTester({
parser: '@typescript-eslint/parser',
});
const errors = [{ messageId: "useIsNullObject", data: { name: "dataSheet" } }];
ruleTester.run('test-for-null-using-isNullObject', rule, {
valid: [
{
code: `
await Excel.run(async (context) => {
var dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}`,
},
],
invalid: [
{
code: `
await Excel.run(async (context) => {
var dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (dataSheet) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});
});`,
errors,
output: `
await Excel.run(async (context) => {
var dataSheet = context.workbook.worksheets.getItemOrNullObject(\"Data\");
return context.sync().then(function () {
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add(\"Data\");
}
dataSheet.position = 1;
});
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (dataSheet) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
errors,
output: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
if (dataSheet) {
dataSheet = context.workbook.worksheets.add("Data");
}`,
errors,
output: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (!dataSheet) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
errors,
output: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (!dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (true && dataSheet) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
errors,
output: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (true && dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (null != dataSheet) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
errors,
output: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
dataSheet.position = 1;
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
for (var i = 0; i < 5; i++) {
if (dataSheet) {
dataSheet = context.workbook.worksheets.add("Data");
}
}
dataSheet.position = 1;
});`,
errors,
output: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
for (var i = 0; i < 5; i++) {
if (dataSheet.isNullObject) {
dataSheet = context.workbook.worksheets.add("Data");
}
}
dataSheet.position = 1;
});`,
},
{
code: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
do {
console.log("test case");
} while (dataSheet);
dataSheet.position = 1;
});`,
errors,
output: `
var dataSheet;
dataSheet = context.workbook.worksheets.getItemOrNullObject("Data");
return context.sync().then(function () {
do {
console.log("test case");
} while (dataSheet.isNullObject);
dataSheet.position = 1;
});`,
},
]
});
|
import Vue from "vue";
import Vuex from "vuex";
import people from "./modules/people";
import planets from "./modules/planets";
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
people: people, // 这种方式是可以重命名模块名称
planets,
},
});
export default store;
|
// ResizableState.h: interface for the CResizableState class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_RESIZABLESTATE_H__9B226426_F27A_4F1E_BA45_88CD8A5A1B9E__INCLUDED_)
#define AFX_RESIZABLESTATE_H__9B226426_F27A_4F1E_BA45_88CD8A5A1B9E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CResizableState
{
protected:
// non-zero if successful
BOOL LoadWindowRect(LPCTSTR pszSection, BOOL bRectOnly);
BOOL SaveWindowRect(LPCTSTR pszSection, BOOL bRectOnly);
virtual CWnd* GetResizableWnd() = 0;
public:
CResizableState();
virtual ~CResizableState();
};
#endif // !defined(AFX_RESIZABLESTATE_H__9B226426_F27A_4F1E_BA45_88CD8A5A1B9E__INCLUDED_)
|
#!/bin/bash
#Gerar números bases
./glp.py > lp.txt;
|
# Phone Number QRCode
_Replaces click action on phone number links to display the number as QR Code. Clicking on the code removes it._
## Features
* Replace click action of every a-element (links) which links to
a phone number (begins with "tel:") to display a QR-Code of this number instead.
* Clicking on the code removes it
* Is displayed above all else in the middle of the page
## Roadmap
* Display above all else for all pages; sometimes it is displayed "before"
the page.
* Move this action to the context menu by default.
* Convert this to a firefox addon.
* In this firefox addon, have an option to replace the click action or add to
the context menu.
* In this firefox addon, have an option to define the size of the code
* Select text in page, addon checks if it is a telephone number and on
right click proposes to generate a QR-Code
|
<?php
namespace App\Http\Livewire;
use App\Models\Post as ModelsPost;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Livewire\WithPagination;
class Post extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $isOther = false;
public function updatedIsOther(){
$this->resetPage();
}
public function render()
{
if($this->isOther)
$posts = ModelsPost::where('user_id', '!=', Auth::user()->id)->orderBy('id', 'DESC')->paginate(2);
else
$posts = ModelsPost::where('user_id', Auth::user()->id)->orderBy('id', 'DESC')->paginate(2);
return view('livewire.post', compact('posts'));
}
public function show($postId){
return redirect()->route('posts.show', $postId);
}
}
|
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Windows.Forms;
using System.Xml.Serialization;
using MikuMikuLibrary.Materials;
using MikuMikuLibrary.Textures;
using MikuMikuModel.GUI.Controls;
using MikuMikuModel.GUI.Forms;
using MikuMikuModel.Mementos;
using MikuMikuModel.Nodes.Objects;
using MikuMikuModel.Nodes.TypeConverters;
using MikuMikuModel.Resources;
namespace MikuMikuModel.Nodes.Materials
{
public class MaterialTextureNode : Node<MaterialTexture>
{
private static readonly XmlSerializer sSerializer = new XmlSerializer( typeof( MaterialTexture ) );
public override NodeFlags Flags => NodeFlags.Rename;
public override Bitmap Image => ResourceStore.LoadBitmap( "Icons/MaterialTexture.png" );
public override Control Control
{
get
{
var textureSetNode = FindParent<ObjectSetNode>()?.FindNode<INode>( "Texture Set", true );
var texture = (( TextureSet ) textureSetNode?.Data)?.Textures.FirstOrDefault( x => x.Id == TextureId );
if ( texture == null )
return null;
TextureViewControl.Instance.SetTexture( texture );
return TextureViewControl.Instance;
}
}
[Category( "General" )]
[DisplayName( "Sampler flags" )]
[TypeConverter( typeof( UInt32HexTypeConverter ) )]
public uint SamplerFlags
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "General" )]
[DisplayName( "Texture id" )]
[TypeConverter( typeof( IdTypeConverter ) )]
public uint TextureId
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "General" )]
[DisplayName( "Texture flags" )]
[TypeConverter( typeof( UInt32HexTypeConverter ) )]
public uint TextureFlags
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "General" )]
[DisplayName( "Extra shader name" )]
public string ExtraShaderName
{
get => GetProperty<string>();
set => SetProperty( value );
}
[Category( "General" )]
public float Weight
{
get => GetProperty<float>();
set => SetProperty( value );
}
[Category( "General" )]
[DisplayName( "Texture coordinate matrix" )]
public Matrix4x4 TextureCoordinateMatrix
{
get => GetProperty<Matrix4x4>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Repeat U" )]
public bool RepeatU
{
get => GetProperty<bool>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Repeat V" )]
public bool RepeatV
{
get => GetProperty<bool>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Mirror U" )]
public bool MirrorU
{
get => GetProperty<bool>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Mirror V" )]
public bool MirrorV
{
get => GetProperty<bool>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Ignore alpha" )]
public bool IgnoreAlpha
{
get => GetProperty<bool>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
public uint Blend
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Alpha blend" )]
public uint AlphaBlend
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
public bool Border
{
get => GetProperty<bool>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Clamp to edge" )]
public bool ClampToEdge
{
get => GetProperty<bool>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
public uint Filter
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Mipmap" )]
public uint MipMap
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Mipmap bias" )]
public uint MipMapBias
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "Sampler flags" )]
[DisplayName( "Anisotropic filter" )]
public uint AnisotropicFilter
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "Texture flags" )]
public MaterialTextureType Type
{
get => GetProperty<MaterialTextureType>();
set
{
var previousType = Type;
MementoStack.BeginCompoundMemento();
SetProperty( value );
if ( previousType == Type || Type == MaterialTextureType.None )
{
MementoStack.EndCompoundMemento();
return;
}
Name = Enum.GetName( typeof( MaterialTextureType ), Type );
Blend = Blend == 0 ? Type == MaterialTextureType.Specular ? 1u : 7 : Blend;
Filter = Filter == 0 ? 2 : Filter;
MipMap = MipMap == 0 ? 2 : MipMap;
MementoStack.EndCompoundMemento();
}
}
[Category( "Texture flags" )]
[DisplayName( "Texture coordinate index" )]
public uint TextureCoordinateIndex
{
get => GetProperty<uint>();
set => SetProperty( value );
}
[Category( "Texture flags" )]
[DisplayName( "Texture coordinate translation type" )]
public MaterialTextureCoordinateTranslationType TextureCoordinateTranslationType
{
get => GetProperty<MaterialTextureCoordinateTranslationType>();
set => SetProperty( value );
}
public bool PromptTextureSelector( INode node )
{
var textureSetNode = node.FindParent<ObjectSetNode>().FindNode<INode>( "Texture Set", true );
if ( textureSetNode == null )
{
MessageBox.Show( "Could not find a suitable texture set.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Error );
return false;
}
using ( var textureSelectForm = new TextureSelectForm( textureSetNode, Type != MaterialTextureType.None ? Type : MaterialTextureType.Color ) )
{
if ( textureSelectForm.ShowDialog() != DialogResult.OK )
return false;
TextureId = textureSelectForm.SelectedTextureNode.Id;
Type = textureSelectForm.MaterialTextureType;
if ( textureSelectForm.SelectedTextureNode.Data.ArraySize == 6 )
{
TextureCoordinateTranslationType = MaterialTextureCoordinateTranslationType.Cube;
if ( Type == MaterialTextureType.Reflection )
Type = MaterialTextureType.EnvironmentCube;
}
else if ( Type == MaterialTextureType.EnvironmentSphere )
{
TextureCoordinateTranslationType = MaterialTextureCoordinateTranslationType.Sphere;
if ( Type == MaterialTextureType.Reflection )
Type = MaterialTextureType.EnvironmentSphere;
}
else
TextureCoordinateTranslationType = MaterialTextureCoordinateTranslationType.None;
}
return true;
}
protected override void Initialize()
{
AddCustomHandler( "Replace", () => PromptTextureSelector( this ) );
AddCustomHandlerSeparator();
AddCustomHandler( "Copy values", () =>
{
using ( var stringWriter = new StringWriter( CultureInfo.InvariantCulture ) )
{
sSerializer.Serialize( stringWriter, Data );
Clipboard.SetText( stringWriter.ToString() );
}
}, Keys.Control | Keys.C );
AddCustomHandler( "Paste values", () =>
{
try
{
using ( var stringReader = new StringReader( Clipboard.GetText() ) )
{
var materialTexture = ( MaterialTexture ) sSerializer.Deserialize( stringReader );
SetProperty( materialTexture.SamplerFlags, nameof( MaterialTexture.SamplerFlags ) );
SetProperty( materialTexture.TextureFlags, nameof( MaterialTexture.TextureFlags ) );
SetProperty( materialTexture.ExtraShaderName, nameof( MaterialTexture.ExtraShaderName ) );
SetProperty( materialTexture.Weight, nameof( MaterialTexture.Weight ) );
SetProperty( materialTexture.TextureCoordinateMatrix, nameof( MaterialTexture.TextureCoordinateMatrix ) );
}
}
catch
{
MessageBox.Show( "There is no valid data to paste.", Program.Name, MessageBoxButtons.OK,
MessageBoxIcon.Error );
}
}, Keys.Control | Keys.V );
}
protected override void PopulateCore()
{
}
protected override void SynchronizeCore()
{
}
public MaterialTextureNode( string name, MaterialTexture data ) : base( name, data )
{
}
}
}
|
##
# A Gem::Security::Policy object encapsulates the settings for verifying
# signed gem files. This is the base class. You can either declare an
# instance of this or use one of the preset security policies below.
class Gem::Security::Policy
attr_reader :name
attr_accessor :only_signed
attr_accessor :only_trusted
attr_accessor :verify_chain
attr_accessor :verify_data
attr_accessor :verify_root
attr_accessor :verify_signer
##
# Create a new Gem::Security::Policy object with the given mode and
# options.
def initialize(name, policy = {}, opt = {})
@name = name
# set options
@opt = opt
# build policy
policy.each_pair do |key, val|
case key
when :verify_data then @verify_data = val
when :verify_signer then @verify_signer = val
when :verify_chain then @verify_chain = val
when :verify_root then @verify_root = val
when :only_trusted then @only_trusted = val
when :only_signed then @only_signed = val
end
end
end
##
# Get the path to the file for this cert.
def self.trusted_cert_path(cert, opt = {})
opt = Gem::Security::OPT.merge(opt)
# get digest algorithm, calculate checksum of root.subject
algo = opt[:dgst_algo]
dgst = algo.hexdigest(cert.subject.to_s)
# build path to trusted cert file
name = "cert-#{dgst}.pem"
# join and return path components
File.join(opt[:trust_dir], name)
end
##
# Verify that the gem data with the given signature and signing chain
# matched this security policy at the specified time.
def verify_signature signature, data, chain, time = Time.now
Gem.ensure_ssl_available
cert_class = OpenSSL::X509::Certificate
exc = Gem::Security::Exception
chain ||= []
chain = chain.map{ |str| cert_class.new(str) }
signer, ch_len = chain[-1], chain.size
opt = Gem::Security::OPT.merge(@opt)
# make sure signature is valid
if @verify_data
# get digest algorithm (TODO: this should be configurable)
dgst = opt[:dgst_algo]
# verify the data signature (this is the most important part, so don't
# screw it up :D)
v = signer.public_key.verify(dgst.new, signature, data)
raise exc, "Invalid Gem Signature" unless v
# make sure the signer is valid
if @verify_signer
# make sure the signing cert is valid right now
v = signer.check_validity(nil, time)
raise exc, "Invalid Signature: #{v[:desc]}" unless v[:is_valid]
end
end
# make sure the certificate chain is valid
if @verify_chain
# iterate down over the chain and verify each certificate against it's
# issuer
(ch_len - 1).downto(1) do |i|
issuer, cert = chain[i - 1, 2]
v = cert.check_validity(issuer, time)
raise exc, "%s: cert = '%s', error = '%s'" % [
'Invalid Signing Chain', cert.subject, v[:desc]
] unless v[:is_valid]
end
# verify root of chain
if @verify_root
# make sure root is self-signed
root = chain[0]
raise exc, "%s: %s (subject = '%s', issuer = '%s')" % [
'Invalid Signing Chain Root',
'Subject does not match Issuer for Gem Signing Chain',
root.subject.to_s,
root.issuer.to_s,
] unless root.issuer.to_s == root.subject.to_s
# make sure root is valid
v = root.check_validity(root, time)
raise exc, "%s: cert = '%s', error = '%s'" % [
'Invalid Signing Chain Root', root.subject, v[:desc]
] unless v[:is_valid]
# verify that the chain root is trusted
if @only_trusted
# get digest algorithm, calculate checksum of root.subject
algo = opt[:dgst_algo]
path = Gem::Security::Policy.trusted_cert_path(root, opt)
# check to make sure trusted path exists
raise exc, "%s: cert = '%s', error = '%s'" % [
'Untrusted Signing Chain Root',
root.subject.to_s,
"path \"#{path}\" does not exist",
] unless File.exist?(path)
# load calculate digest from saved cert file
save_cert = OpenSSL::X509::Certificate.new(File.read(path))
save_dgst = algo.digest(save_cert.public_key.to_s)
# create digest of public key
pkey_str = root.public_key.to_s
cert_dgst = algo.digest(pkey_str)
# now compare the two digests, raise exception
# if they don't match
raise exc, "%s: %s (saved = '%s', root = '%s')" % [
'Invalid Signing Chain Root',
"Saved checksum doesn't match root checksum",
save_dgst, cert_dgst,
] unless save_dgst == cert_dgst
end
end
# return the signing chain
chain.map { |cert| cert.subject }
end
end
##
# Verifies +digests+ match +signatures+
def verify_signatures spec, digests, signatures
if only_signed and signatures.empty? then
raise Gem::Security::Exception,
"unsigned gems are not allowed by the #{name} policy"
end
digests.each do |file, digest|
signature = signatures[file]
raise Gem::Security::Exception, "missing signature for #{file}" unless
signature
verify_signature signature, digest.digest, spec.cert_chain
end
end
alias to_s name # :nodoc:
end
|
require 'sxp'
require 'pp'
class Top
def initialize(source)
@sxp = SXP::Reader::Scheme.read source
end
def compile()
@leg ||= LegC.new(@sxp)
end
# For debug
def leg() @leg end
def json()
compile.json
end
def text()
compile.text
end
end
# Abstract
class Compiler
def initialize(sxp)
raise "ERROR" unless sxp
@sxp = sxp
end
def json()
"json undef #{self}"
""
end
# def children()
# @children = ir()
# end
def error(kind = 'Error', expected = 'IDK', found = 'IDK')
raise "AccOunt: #{kind}\n Expected: #{expected}\n Found: #{found}"
end
def id?(obj)
obj.is_a?(Integer)
end
end
class LegC < Compiler
def initialize(sxp)
super
case @sxp
in [:leg, leg_id, plans, events] if id?(leg_id)
@plans = PlansC.new(plans)
@events = EventsC.new(events)
@id = leg_id
else error('syntax error', '[:leg, leg_id, plans, events]', @sxp)
end
end
# eventのフレームを軸に、プランを対応した構造
# [{e: [event-frame], p: [trace-frame]}]
def frame()
pf = @plans.frame
ef = @events.frame
plan_ids_arr = pf.map{ |p| p[1]}
ef.map{ |es|
related_plan_ids = es.map { |e| e[:rel2]}
plan_framei = plan_ids_arr.index { |pids| (not (pids & related_plan_ids).empty?)}
{e: es, p: pf[plan_framei]}
}
end
def contents() {p: @plans.contents, e: @events.contents} end
# frame はconstract_matrixのコメントで書かれた構造
def number_matrix(frame)
x, y, next_x = 0, 0, 0
connectors = []
matrix = frame.map{ |tiles|
executed = false
x = next_x
tmp = tiles.map{ |tile|
tmp = tile.append({x: x, y: y})
if executed && (not tile_executed?(tile)) then
next_x = x
connectors.append({x1: x-1, y1: y, x2:x, y2:y+1})
end
x += 1
executed = (not tile[1].empty?)
tmp
}
y += 1
tmp
}
[matrix, x, y, connectors]
end
# Frame = [{e:[{id: --, rel2: --} ...], p: [ID, [ID...]]}...]
def constract_matrix(frame)
frame.map{ |h| merge_plan_event(h) }
end
def fresh()
@fresh ||= 100000
@fresh += 1
end
# h: {e:[{id: --, rel2: --} ...], p: [ID, [ID...]]}
def merge_plan_event(h)
# [[pid, [e...]]...] それぞれの e rel2 pid
pairs = h[:p][1].map{ |i| [i, h[:e].filter{ |e| e[:rel2] == i }]}
# eの列の先頭部分に存在しうる、unplannedなeventたち
floated_es = h[:e] - pairs.map{ |pair| pair[1]}.flatten
# 対応するペアを持たないイベントに、プレイスホルダを対応させておく
# floated_es.map{ |e| [fresh(), [e]] }.concat(pairs)
floated_es.map{ |e| [nil, [e]] }.concat(pairs)
end
def tile_executed?(t)
not t[1].empty?
end
# Tile -> {id: , rel2: }
def tile_event(t)
t[1][0]
end
def tile_plan(t)
t[0]
end
def tile_place(t)
t[2]
end
def extract_eenv(ev_hash, eenv)
event = eenv.find {|e| e.id == ev_hash[:id]}
end
def extract_penv(p_id, penv)
penv.values.flatten.find{ |trace| trace.id == p_id }
end
def json()
layout = number_matrix(constract_matrix(frame))
matrix = layout[0]
x = layout[1]
y = layout[2]
connectors = layout[3]
env = contents()
penv = env[:p]
eenv = env[:e]
components = matrix.flatten(1).map do |t|
if tile_plan(t).nil?
then
type = "unplanned"
event = extract_eenv(tile_event(t), eenv)
j = event.json
target = j[:target]
path =j[:path]
# annotation =
else
type = tile_executed?(t) ? "executed" : "planned"
plan = extract_penv(tile_plan(t), penv)
j = plan.json
target = j[:target]
path =j[:path]
end
{x: tile_place(t)[:x], y: tile_place(t)[:y], data: {\
type: type, target: target, path: path}}
end
{xSize: x, ySize: y, components: components, connectors: connectors}
end
def text()
frame = frame()
contents = contents()
p_cont = contents[:p]
e_cont = contents[:e]
res = "レッグ#{@id}では"
res << frame.map{ |h|
plan_name, plan_ids = h[:p]
unplanned_ids, planned_ids = h[:e].partition{|ev| ev[:rel2].nil? }
traces = p_cont[plan_name]
tmp_msg = ""
unless unplanned_ids.empty?
tmp_msg << "ここでプランから外れて次のような行動をとった\n\n "
tmp_msg << unplanned_ids.map{ |ev|
ev[:id].to_s.to_s + ". " + e_cont.find{|e| e.id == ev[:id] }.text
}.join("\n ") << "\n\nそこで"
end
tmp_msg << plan_name.to_s
tmp_msg << "として以下を考えた\n\n "
tmp_msg << plan_ids.map{ |trace_id|
trace_id.to_s + ". " + traces.find{|t| t.id == trace_id }.text
}.join("\n ") << "\n\n"
tmp_msg << "このプランのもとで次のように実際の行動をとった\n\n "
tmp_msg << planned_ids.map{ |ev|
ev[:id].to_s.to_s + ". " + e_cont.find{|e| e.id == ev[:id] }.text
}.join("\n ") << "\n\n"
}.join("")
res << "レッグ#{@id}の説明は以上。\n"
end
end
class PlansC < Compiler
def initialize(sxp)
super
error('syntax error', '[:plans, ...]', @sxp) unless @sxp[0] == :plans
@id = @sxp[1]
@plan_arr = @sxp[1..].map { |plan| PlanC.new(plan) }
end
def frame() @plan_arr.map{ |p| p.frame } end
def contents()
hash = {}
@plan_arr.each{ |p| hash[p.id] = p.contents }
hash
end
# Return plans frame (array of array of plan-id)
def json()
tmp = @plan_ir.map {|plan| plan.json()}
@tiles = @plan_ir.empty? ? {} : @plan_ir[0].tiles.merge(*@plan_ir[1..].map{|ir|ir.tiles})
tmp
end
end
class PlanC < Compiler
def initialize(sxp)
super
error() unless @sxp[0] == :plan && @sxp[1].is_a?(Symbol)
@id = @sxp[1]
@trace_arr = @sxp[2..].map {|trace| TraceC.new(trace)}
end
attr_reader :id
def frame() [@id, @trace_arr.map{ |t| t.frame}] end
def contents() @trace_arr end
# Return plan frame (array)
def json()
@trace_arr.map{|trace|
tile = trace.json
@tiles[trace.id] = trace
trace.id
}
end
attr_reader :tiles
end
class TraceC < Compiler
def initialize(sxp)
super
case @sxp
in [trace_id, move, recognize] if id?(trace_id)
@move = MoveC.new(move)
raise @sxp unless recognize
@recognize = RecognizeC.new(recognize)
@id = trace_id
end
end
def id()
@id
end
def frame() @id end
# () -> Hash (like JSON)
def json()
{\
:type => "planned"\
, :target => @recognize.json\
, :path => @move.json\
}
end
def text()
@move.text + "。" + @recognize.text + "を確認する"
end
end
class MoveC < Compiler
def initialize(sxp)
super
case @sxp
in [:go, obj_sxp]
@obj = ObjC.new(obj_sxp)
@tag = :go
in :straight
@tag = :straight
else error('syntax error', "Move", @sxp)
end
end
def json()
case @tag
when :go
@obj.json << "に沿う"
when :straight
"直進する"
end
end
def text() json end
end
class RecognizeC < Compiler
def initialize(sxp)
super
case @sxp
in [:get, obj_sxp]
@finish = ObjC.new(obj_sxp)
@tag = :get
in [:for, n] if n >= 0
@tag = :for
@finish = n # TODO 外から扱いやすいように、構造を定義しなおす
in :straight
@tag = :straight
end
end
def json()
case @tag
when :get
@finish.json
when :for
n.to_s << "進む"
when :straight
"まっすぐ"
end
end
def text() json end
end
class ObjC < Compiler
def initialize(sxp)
super
case @sxp
in [e_sxp, obj_sxp1] if Es.related?(e_sxp)
# @tag = :e
@obj = Es.new(@sxp)
in [g_sxp, obj_sxp1] if Gs.related?(g_sxp)
# @tag = :g
@obj = Gs.new(@sxp)
in [g2_sxp, obj1, obj2] if G2s.related?(g2_sxp)
# @tag = :g2
@obj= G2s.new(@sxp)
in [:plan, n] if id?(n) # TODO implement
@tag = :plan
@obj = Ref.new(n)
in d_sxp
# @tag = :d
@obj = Ds.new(d_sxp)
# else error('syntax error', 'object', @sxp)
end
end
def json()
@obj.json
end
def text()
@obj.text
end
end
class EventsC < Compiler
def initialize(sxp)
super
error("Events") unless @sxp[0] == :events
@event_arr = @sxp[1..].map { |event| EventC.new(event) }
end
# [[event.frame]] : event が対応するプランが変わるところで分割した構造
# 変わり目とは planned -> unplanned の変わり目のこと
def frame()
badway = true
arr_arr_event_frame = []
arr_event_frame = []
@event_arr.each do |e|
case [badway, e.unplanned?]
when [false, true] # planned -> unplnned
arr_arr_event_frame.append(arr_event_frame)
arr_event_frame = [e.frame]
badway = true
else
arr_event_frame.append(e.frame)
badway = e.unplanned?
end
end
arr_arr_event_frame.append(arr_event_frame)
arr_arr_event_frame
end
def contents() @event_arr end
# Return event frame (array of plan-id)
def json()
@tiles = @ir.map{|e| e.json}
@event_frame = @tiles.map{|t| t.id }
end
attr_reader :tiles
end
class EventC < Compiler
def initialize(sxp)
super
case @sxp
in [id, action_sxp, recog_sxp, rel2plan_sxp] if id?(id)
@action = ActionC.new(action_sxp)
# raise sxp unless recog_sxp
@recog = RecognizeC.new(recog_sxp)
@rel2plan = Rel2PlanC.new(rel2plan_sxp)
@id = id
end
end
def id()
@id
end
def frame() {id: @id, rel2: @rel2plan.rel2 } end
def unplanned?() @rel2plan.unplanned? end
def json()
path, annotation = @action.json
{\
:type => @rel2plan.type\
, :target => @recog.json\
, :path => path\
, :annotation => annotation}
end
def text()
@action.text + "。" + @recog.text + "を確認。"
end
end
class ActionC < Compiler
def initialize(sxp)
super
case @sxp
in :'as-plan'
@tag = :'as-plan'
in [move_sxp, aware_sxp] unless move_sxp.is_a?(Symbol)
@move = MoveC.new(move_sxp)
@aware = AwareC.new(aware_sxp)
@tag = :move
in move_sxp
@move = MoveC.new(move_sxp)
@tag = :move
end
end
def json()
case @tag
when :'as-plan'
return "プラン通り", nil
when :move
return @move.json, (@aware ? @aware.json : nil)
end
end
def text()
case @tag
when :'as-plan'
"プラン通り"
when :move
@move.text
end
end
end
class AwareC < Compiler
def initialize(sxp)
super
case @sxp
in [:unconfirmed, obj_sxp]
@obj = ObjC.new(obj_sxp)
@tag = :unconfirmed
end
end
def json()
{message: "確認できない", obj: @obj}
end
end
class Rel2PlanC < Compiler
def initialize(sxp)
super
case @sxp
in [tag, trace_id, conf] if id?(trace_id) && conf.is_a?(Integer)
error("runtime error", "0-3", conf) unless 0 <= conf && conf <= 3
@tag = tag
@rel2_id = trace_id # ID で持つべき?対応するオブジェクトを持つべき? オブジェクトを持つなら、参照はどうやって計算する?
@conf = conf
@planned = true
in :unrelated
@tag = :unrelated
@planned = false
end
end
def rel2() @rel2_id end
def unplanned?() (not @planned) end
def type()
case @tag
when :unrelated
"unplanned"
when :related
"executed"
when :done
"executed"
end
end
end
# Abstract class
class ObjDescripter < Compiler
def self.Descripters()
[]
end
def self.related?(sxp)
Descripters().include?(sxp)
end
def initialize(sxp)
super
@descripter = ""
@sub_objs = []
end
def json
text()
end
def text()
@sub_objs.map {|obj| obj.text}.join("と") + (@sub_objs.empty? ? "" : "の") + @descripter.to_s
end
end
class Ds < ObjDescripter
def self.Descripters()
[:テラス, :尾根, :沢, :土がけ, :採石場, :土塁・堤防\
, :きれつ, :小さなきれつ, :こぶ, :小さなこぶ, :鞍部\
, :凹地, :小凹地, :穴, :凹凸地, :アリ塚, :岩がけ, :がけの間の通過部分\
, :湖, :池・沼 , :湧水点, :貯水槽・水桶, :開けた土地, :半ば開けた土地\
, :独立樹, :切り株・木の根, :道路, :道, :道・小道・小径, :パイプライン\
, :建物の通過できる部分, :階段, :川, :岩\
, :目的地]
end
def initialize(sxp)
super
@descripter = sxp
end
def text()
@sxp.to_s
end
end
class Es < ObjDescripter
def self.Descripters()
[:低い, :浅い, :深い, :植物の茂っている, :開けた, :岩の・岩状の, :湿地状の, :砂地状の, :針葉樹の, :広葉樹の, :倒れた・壊れた]
end
def initialize(e_sxp)
super
case e_sxp
in [descripter, sub_obj]
@descripter = descripter
@sub_objs = [ObjC.new(sub_obj)]
end
end
def text()
@descripter.to_s + @sub_objs[0].text
end
end
class Gs < ObjDescripter
def self.Descripters()
[:側, :ふち, :部分, :内側の角, :外側の角, :突端, :曲がり,\
:終わり, :上の部分, :下の部分, :上, :下, :根本, :傾斜の変わり目, :線]
end
def initialize(sxp)
super
case sxp
in [descripter, sub_obj]
@descripter = descripter
@sub_objs = [ObjC.new(sub_obj)]
end
end
end
class G2s < ObjDescripter
def self.Descripters()
[:交点, :分岐, :間, :変わり目]
end
def initialize(sxp)
super
case sxp
in [desc, obj1, obj2]
@descripter = desc
@sub_objs = [obj1, obj2].map{|sxp| ObjC.new(sxp)}
end
end
# def json()
# @sub_objs[0].json << @descripter.to_s << @sub_objs[1].json
# end
end
class Ref < ObjDescripter
def initialize(n)
super
@descripter = "プラン#{n}で記述したところ"
end
end
require './compiler'
# def t
# Top.new(Ex1)
# end
require './examples/loader'
def l
t = Top.new(Ex3)
t.compile
t.leg
end
|
#!/bin/bash -e
time=$(date +%Y-%m-%d)
DIR="$PWD"
ssh_user="buildbot@beagleboard.org"
rev=$(git rev-parse HEAD)
branch=$(git describe --contains --all HEAD)
server_dir="/var/lib/buildbot/masters/kernel-buildbot/public_html/images/${branch}/${rev}"
export apt_proxy=localhost:3142/
keep_net_alive () {
while : ; do
sleep 15
echo "log: [Running: ./publish/bb.org_4gb_stable.sh]"
done
}
build_and_upload_image () {
echo "***BUILDING***: ${config_name}: ${target_name}-${image_name}-${size}.img"
./RootStock-NG.sh -c ${config_name}
if [ -d ./deploy/${image_name} ] ; then
cd ./deploy/${image_name}/
echo "debug: [./setup_sdcard.sh ${options}]"
sudo ./setup_sdcard.sh ${options}
if [ -f ${target_name}-${image_name}-${size}.img ] ; then
sudo chown buildbot.buildbot ${target_name}-${image_name}-${size}.img
sync ; sync ; sleep 5
bmaptool create -o ${target_name}-${image_name}-${size}.bmap ${target_name}-${image_name}-${size}.img
xz -T0 -z -3 -v -v --verbose ${target_name}-${image_name}-${size}.img
sha256sum ${target_name}-${image_name}-${size}.img.xz > ${target_name}-${image_name}-${size}.img.xz.sha256sum
#upload:
ssh ${ssh_user} mkdir -p ${server_dir}
rsync -e ssh -av ./${target_name}-${image_name}-${size}.bmap ${ssh_user}:${server_dir}/
rsync -e ssh -av ./${target_name}-${image_name}-${size}.img.xz ${ssh_user}:${server_dir}/
rsync -e ssh -av ./${target_name}-${image_name}-${size}.img.xz.sha256sum ${ssh_user}:${server_dir}/
#cleanup:
cd ../../
sudo rm -rf ./deploy/ || true
else
echo "***ERROR***: Could not find ${target_name}-${image_name}-${size}.img"
fi
else
echo "***ERROR***: Could not find ./deploy/${image_name}"
fi
}
keep_net_alive & KEEP_NET_ALIVE_PID=$!
echo "pid: [${KEEP_NET_ALIVE_PID}]"
# IoT BeagleBone image
##Debian 9:
#image_name="${deb_distribution}-${release}-${image_type}-${deb_arch}-${time}"
image_name="debian-9.13-iot-armhf-${time}"
size="4gb"
target_name="bone"
options="--img-4gb ${target_name}-${image_name} --dtb beaglebone --distro-bootloader \
--hostname beaglebone --enable-cape-universal --enable-uboot-pru-rproc-414ti"
config_name="bb.org-debian-stretch-iot-v4.14"
build_and_upload_image
# LXQT BeagleBone image
##Debian 9:
#image_name="${deb_distribution}-${release}-${image_type}-${deb_arch}-${time}"
image_name="debian-9.13-lxqt-armhf-${time}"
size="4gb"
target_name="bone"
options="--img-4gb ${target_name}-${image_name} --dtb beaglebone --distro-bootloader \
--hostname beaglebone --enable-cape-universal --enable-uboot-pru-rproc-414ti"
config_name="bb.org-debian-stretch-lxqt-v4.14"
build_and_upload_image
# LXQT BeagleBoard-xM image
##Debian 9:
#image_name="${deb_distribution}-${release}-${image_type}-${deb_arch}-${time}"
image_name="debian-9.13-lxqt-xm-armhf-${time}"
size="4gb"
target_name="bbxm"
options="--img-4gb ${target_name}-${image_name} --dtb omap3-beagle-xm --rootfs_label rootfs --hostname beagleboard"
config_name="bb.org-debian-stretch-lxqt-xm"
build_and_upload_image
# LXQT BeagleBoard-X15/BeagleBone-AI image
##Debian 9:
#image_name="${deb_distribution}-${release}-${image_type}-${deb_arch}-${time}"
image_name="debian-9.13-lxqt-tidl-armhf-${time}"
size="6gb"
target_name="am57xx"
options="--img-6gb ${target_name}-${image_name} --dtb am57xx-beagle-x15 --hostname beaglebone"
config_name="bb.org-debian-stretch-lxqt-tidl-v4.14"
build_and_upload_image
[ -e /proc/$KEEP_NET_ALIVE_PID ] && sudo kill $KEEP_NET_ALIVE_PID
|
<?php
/**
* PHP CLient for Kubernetes API
*
* Copyright 2014 binarygoo Inc. All rights reserved.
*
* @author Faruk brbovic <fbrbovic@devstub.com>
* @link http://www.devstub.com/
* @copyright 2014 binarygoo / devstub.com
*
* 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.
*
*/
namespace DevStub\KubernetesAPIClient\Entity\v1beta1;
use DevStub\KubernetesAPIClient\Entity\BaseEntity;
class TypeMeta extends BaseEntity implements \JsonSerializable {
protected $kind;
protected $id;
protected $uid;
protected $creationTimestamp;
protected $selfLink;
protected $resourceVersion;
protected $apiVersion;
protected $namespace;
protected $annotations;
/**
* @return \DevStub\KubernetesAPIClient\Entity\v1beta1\StringArray[string]
*/
public function getAnnotations() {
return $this->annotations;
}
/**
* @param \DevStub\KubernetesAPIClient\Entity\v1beta1\StringArray[string] $annotations
*
* @return \DevStub\KubernetesAPIClient\Entity\v1beta1\StringArray[string]
*/
public function setAnnotations($annotations = self::UNIQUE_DEFAULT) {
if ($annotations === self::UNIQUE_DEFAULT) {
$annotations = new StringArray();
$annotations->_setEntityCallback([$this,__METHOD__]);
}
$this->annotations = $annotations;
return $this->annotations;
}
/**
* @return string
*/
public function getApiVersion() {
return $this->apiVersion;
}
/**
* @param string $apiVersion
*
* @return $this
*/
public function setApiVersion($apiVersion) {
$this->apiVersion = $apiVersion;
return $this;
}
/**
* @return string
*/
public function getCreationTimestamp() {
return $this->creationTimestamp;
}
/**
* @param string $creationTimestamp
*
* @return $this
*/
public function setCreationTimestamp($creationTimestamp) {
$this->creationTimestamp = $creationTimestamp;
return $this;
}
/**
* @return string
*/
public function getId() {
return $this->id;
}
/**
* @param string $id
*
* @return $this
*/
public function setId($id) {
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getKind() {
return $this->kind;
}
/**
* @param string $kind
*
* @return $this
*/
public function setKind($kind) {
$this->kind = $kind;
return $this;
}
/**
* @return string
*/
public function getNamespace() {
return $this->namespace;
}
/**
* @param string $namespace
*
* @return $this
*/
public function setNamespace($namespace) {
$this->namespace = $namespace;
return $this;
}
/**
* @return string
*/
public function getResourceVersion() {
return $this->resourceVersion;
}
/**
* @param string $resourceVersion
*
* @return $this
*/
public function setResourceVersion($resourceVersion) {
$this->resourceVersion = $resourceVersion;
return $this;
}
/**
* @return string
*/
public function getSelfLink() {
return $this->selfLink;
}
/**
* @param string $selfLink
*
* @return $this
*/
public function setSelfLink($selfLink) {
$this->selfLink = $selfLink;
return $this;
}
/**
* @return string
*/
public function getUid() {
return $this->uid;
}
/**
* @param string $uid
*
* @return $this
*/
public function setUid($uid) {
$this->uid = $uid;
return $this;
}
}
|
/*
* This script shows how to do some simple things with WAGI and WASI.
*
* We get access to HTTP headers from the `Environ` object.
* We get access to query parameters from the `CommandLine` object.
* We write data back to the client using `Console.log`, and we write data to the error
* log using `Console.error`.
*/
import "wasi";
import { Console, Environ, CommandLine } from "as-wasi";
// Sending to Console.log is essentially sending to STDOUT. In WAGI, as in CGI, the first
// section of the response MUST be a header. And in the header, it MUST contain either
// 'content-type' or 'location'. If neither of those is present, it will cause a
// 500 Internal Server Error.
Console.log("content-type: text/plain");
Console.log(""); // A blank line separates headers from body.
// This sends a message to the server's log.
Console.error("Module loaded.");
// Any call to Console.log after this will be written to the HTTP response body and sent
// to the client.
// Get a handle to the environment variables.
let env = new Environ();
// Get the 'Host' header from the HTTP request. Note that all HTTP headers are prefixed
// with 'HTTP_'
let host = env.get("HTTP_HOST");
// This is how we get information from the query string.
// If the query string contains `greet=NAME`, then we will replace 'world' with the name.
// For example, http://localhost/greet=matt will set `greet` to be "matt"
let vars = parseArgs();
let greet = "world";
if (vars.has("greet")) {
greet = vars.get("greet");
}
// Now we will send the message hello NAME from HOST.
// If name and host are not set, it will be "hello world from unknown host".
Console.log("hello " + greet + " from " + defstr(host, "unknown host"));
// Load the arguments and parse the query string values out of them.
//
// In WAGI (as in CGI), the query parameters from a query string are parsed into name/value
// pairs and appended to the args. The first arg is the URI's path component, and the rest
// are query params expressed as arguments.
//
// So http://example.com/as-env?greet=matt&foo=bar creates an arg list that looks like
// `["/as-env", "greet=matt", "foo=bar"]`. This function parses out the name/value pairs
// and returns a map like `{"greet": "matt", "foo": "nar"}`.
function parseArgs(): Map<string, string> {
let vars = new Map<string, string>();
let cl = new CommandLine();
let args = cl.all();
// Parse all of the args into name/value pairs.
// We skip the first arg b/c that is just the WASM path (as in POSIX args).
if (args.length > 1) {
for (let i = 1; i < args.length; i++) {
let pair = args[i].split("=");
if (pair.length == 2) {
vars.set(pair[0], pair[1]);
}
}
}
return vars;
}
// Utility function for getting a default string.
function defstr(input: string | null, defaultValue: string): string {
return input === null ? defaultValue : input;
}
|
package io.cloudstate.kotlinsupport.services
import io.cloudstate.kotlinsupport.Context
interface StatefulService {
fun setContext(context: Context)
infix fun fail(obj: Any)
infix fun emit(obj: Any)
infix fun forward(obj: Any)
}
|
DROP TABLE IF EXISTS t_employee;
CREATE TABLE t_employee (
id INT PRIMARY KEY AUTO_INCREMENT,
last_name VARCHAR(32) NOT NULL,
gender VARCHAR(1) DEFAULT '0' COMMENT '0: female, 1: male',
email VARCHAR(32),
dep_id INT NOT NULL COMMENT 'department_id'
);
|
using Krona.Network.P2P.Payloads;
using System.IO;
namespace Krona.Network.P2P
{
public static class Helper
{
public static byte[] GetHashData(this IVerifiable verifiable)
{
using (MemoryStream ms = new MemoryStream())
using (BinaryWriter writer = new BinaryWriter(ms))
{
verifiable.SerializeUnsigned(writer);
writer.Flush();
return ms.ToArray();
}
}
}
}
|
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace 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.
*/
package org.fcrepo.persistence.ocfl.impl;
import static org.fcrepo.kernel.api.FedoraTypes.FCR_ACL;
import static org.fcrepo.kernel.api.FedoraTypes.FCR_METADATA;
import static org.fcrepo.kernel.api.FedoraTypes.FEDORA_ID_PREFIX;
import static org.fcrepo.kernel.api.RdfLexicon.FEDORA_NON_RDF_SOURCE_DESCRIPTION_URI;
import static org.fcrepo.kernel.api.operations.ResourceOperationType.CREATE;
import static org.fcrepo.persistence.common.ResourceHeaderSerializationUtils.deserializeHeaders;
import static org.fcrepo.persistence.common.ResourceHeaderSerializationUtils.serializeHeaders;
import static org.fcrepo.persistence.ocfl.impl.OCFLPersistentStorageUtils.getSidecarSubpath;
import org.fcrepo.kernel.api.exception.RepositoryRuntimeException;
import org.fcrepo.kernel.api.models.ResourceHeaders;
import org.fcrepo.kernel.api.operations.CreateResourceOperation;
import org.fcrepo.kernel.api.operations.ResourceOperation;
import org.fcrepo.kernel.api.operations.ResourceOperationType;
import org.fcrepo.persistence.api.exceptions.PersistentItemNotFoundException;
import org.fcrepo.persistence.api.exceptions.PersistentStorageException;
import org.fcrepo.persistence.ocfl.api.FedoraOCFLMappingNotFoundException;
import org.fcrepo.persistence.ocfl.api.FedoraToOcflObjectIndex;
import org.fcrepo.persistence.ocfl.api.OCFLObjectSession;
import org.fcrepo.persistence.ocfl.api.Persister;
/**
* A base abstract persister class
*
* @author dbernstein
* @since 6.0.0
*/
abstract class AbstractPersister implements Persister {
/*
* The resourceOperationClass variable, in conjunction with the resourceOperationType, is used by the handle(...)
* method to determine whether or not the persister can perform the persistence routine on the operation passed in
* the persist(...) method.
*/
private final Class<? extends ResourceOperation> resourceOperationClass;
/*
* The resourceOperationType, in conjunction with the resourceOperationClass is used by the handle(...) method
* to determine which operations the persister knows how to handle.
*/
private final ResourceOperationType resourceOperationType;
protected final FedoraToOcflObjectIndex index;
protected AbstractPersister(final Class<? extends ResourceOperation> resourceOperationClass,
final ResourceOperationType resourceOperationType,
final FedoraToOcflObjectIndex index) {
this.resourceOperationClass = resourceOperationClass;
this.resourceOperationType = resourceOperationType;
this.index = index;
}
/**
* Writes the resource headers to the sidecar file.
* @param session The OCFL object session
* @param headers The resource headers
* @param subpath The subpath of the resource whose headers you are writing
* @throws PersistentStorageException
*/
protected static void writeHeaders(final OCFLObjectSession session, final ResourceHeaders headers,
final String subpath) throws PersistentStorageException {
final var headerStream = serializeHeaders(headers);
session.write(getSidecarSubpath(subpath), headerStream);
}
/**
* Reads the headers associated with the resource at specified subpath.
* @param objSession The OCFL object session
* @param subpath The subpath of the resource whose headers you are reading
* @return The resource's headers object
* @throws PersistentStorageException
*/
protected static ResourceHeaders readHeaders(final OCFLObjectSession objSession, final String subpath)
throws PersistentStorageException {
final var headerStream = objSession.read(getSidecarSubpath(subpath));
return deserializeHeaders(headerStream);
}
@Override
public boolean handle(final ResourceOperation operation) {
return resourceOperationClass.isInstance(operation) && resourceOperationType.equals(operation.getType());
}
/**
*
* @param resourceId The fedora resource identifier
* @return The associated mapping
* @throws PersistentStorageException When no mapping is found.
*/
protected FedoraOCFLMapping getMapping(final String resourceId) throws PersistentStorageException {
try {
return this.index.getMapping(resourceId);
} catch (FedoraOCFLMappingNotFoundException e){
throw new PersistentStorageException(e.getMessage());
}
}
/**
* Resolves the fedora root object identifier associated with the operation's resource identifier.
* @param operation The operation
* @param session The OCFL persistent storage session.
* @return The fedora root object identifier associated with the resource described by the operation.
*/
protected String resolveRootObjectId(final CreateResourceOperation operation,
final OCFLPersistentStorageSession session) {
final var resourceId = operation.getResourceId();
//is resource or any parent an archival group?
final String startingResourceId;
if (operation.getType().equals(CREATE)) {
final var parentId = operation.getParentId();
if (parentId != null) {
startingResourceId = parentId;
} else if (FEDORA_NON_RDF_SOURCE_DESCRIPTION_URI.equals(operation.getInteractionModel())) {
startingResourceId = resourceId.replace("/" + FCR_METADATA, "");
} else {
startingResourceId = null;
}
} else {
startingResourceId = resourceId;
}
final var archivalGroupId = startingResourceId == null ? null : findArchivalGroupInAncestry(startingResourceId,
session);
if (archivalGroupId != null) {
return archivalGroupId;
} else if (resourceId.endsWith("/" + FCR_METADATA) || resourceId.endsWith("/" + FCR_ACL)) {
return resourceId.substring(0, resourceId.lastIndexOf("/"));
} else {
return resourceId;
}
}
protected String findArchivalGroupInAncestry(final String resourceId, final OCFLPersistentStorageSession session) {
if (resourceId.endsWith(FEDORA_ID_PREFIX)) {
return null;
}
//strip off trailing slash if exists
String cleanedResourceId = resourceId;
if (resourceId.endsWith("/")) {
cleanedResourceId = resourceId.substring(0, resourceId.length() - 1);
}
try {
final var headers = session.getHeaders(cleanedResourceId, null);
if (headers.isArchivalGroup()) {
return cleanedResourceId;
}
} catch (final PersistentItemNotFoundException ex) {
//do nothing since there are cases where the resourceId will be the resource
//that is about to be created and thus will not yet exist in peristent storage.
} catch (final PersistentStorageException ex) {
throw new RepositoryRuntimeException(ex);
}
//get the previous path segment not including the trailing slash
final String parentId = cleanedResourceId.substring(0, cleanedResourceId.lastIndexOf('/'));
return findArchivalGroupInAncestry(parentId, session);
}
}
|
<?php
namespace PHPSQLParser\Test\Parser;
use PHPSQLParser\PHPSQLParser;
class CommentsTest extends \PHPUnit_Framework_TestCase {
protected $parser;
/**
* @before
* Executed before each test
*/
protected function setup() {
$this->parser = new PHPSQLParser(false, true);
}
public function testComments1() {
$sql = 'SELECT a, -- inline comment in SELECT section
b
FROM test';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment1.serialized');
$this->assertEquals($expected, $p, 'inline comment in SELECT section');
}
public function testComments2() {
$sql = 'SELECT a, /*
multi line
comment
*/
b
FROM test';
$p = $this->parser->parse($sql);
$expectedEncoded = getExpectedValue(dirname(__FILE__), 'comment2.serialized', false);
$expectedSerialized = base64_decode($expectedEncoded);
$expected = unserialize($expectedSerialized);
$this->assertEquals($expected, $p, 'multi line comment');
}
public function testComments3() {
$sql = 'SELECT a
FROM test -- inline comment in FROM section';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment3.serialized');
$this->assertEquals($expected, $p, 'inline comment in FROM section');
}
public function testComments4() {
$sql = 'SELECT a
FROM test
WHERE id = 3 -- inline comment in WHERE section
AND b > 4';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment4.serialized');
$this->assertEquals($expected, $p, 'inline comment in WHERE section');
}
public function testComments5() {
$sql = 'SELECT a
FROM test
LIMIT -- inline comment in LIMIT section
10';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment5.serialized');
$this->assertEquals($expected, $p, 'inline comment in LIMIT section');
}
public function testComments6() {
$sql = 'SELECT a
FROM test
ORDER BY -- inline comment in ORDER BY section
a DESC';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment6.serialized');
$this->assertEquals($expected, $p, 'inline comment in ORDER BY section');
}
public function testComments7() {
$sql = 'INSERT INTO a (id) -- inline comment in INSERT section
VALUES (1)';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment7.serialized');
$this->assertEquals($expected, $p, 'inline comment in INSERT section');
}
public function testComments8() {
$sql = 'INSERT INTO a (id)
VALUES (1) -- inline comment in VALUES section';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment8.serialized');
$this->assertEquals($expected, $p, 'inline comment in VALUES section');
}
public function testComments9() {
$sql = 'INSERT INTO a (id) -- inline comment in INSERT section;
SELECT id -- inline comment in SELECT section
FROM x';
$p = $this->parser->parse($sql);
$expected = getExpectedValue(dirname(__FILE__), 'comment9.serialized');
$this->assertEquals($expected, $p, 'inline comment in SELECT section');
}
}
?>
|
package ru.modulkassa.findgoods.di
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.HttpLoggingInterceptor.Level
import ru.modulkassa.findgoods.BuildConfig
import ru.modulkassa.findgoods.domain.network.AuthorizationInterceptor
import ru.modulkassa.findgoods.domain.repository.RetailPointRepository
import javax.inject.Inject
import javax.inject.Provider
class ModulKassaOkHttpClientProvider @Inject constructor(
private val retailPointRepository: RetailPointRepository
) : Provider<OkHttpClient> {
override fun get(): OkHttpClient {
val httpClientBuilder = OkHttpClient.Builder()
.addInterceptor(AuthorizationInterceptor(retailPointRepository))
if (BuildConfig.DEBUG) {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = Level.BODY
httpClientBuilder.addNetworkInterceptor(httpLoggingInterceptor)
}
return httpClientBuilder.build()
}
}
|
<?php
namespace App\Http\Livewire\Authboard;
use Livewire\Component;
use App\Models\User;
use App\Models\UserPost;
use App\Models\OfferService;
use App\Models\UserPostServiceType;
use App\Models\UserBookingDetail;
use Illuminate\Support\Facades\Auth;
class HostelDetail extends Component
{
public $postId;
public $service;
public $bookingAvailable;
public $bookingStatus;
public function mount($postId)
{
$this->postId=$postId;
}
public function render()
{
$this->service=UserPost::where('id' , $this->postId)->orderBy('id', 'desc')->first();
return view('livewire.authboard.hostel-detail')->layout('layouts.authboard');
}
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Unidade;
class UnidadeController extends Controller
{
function telaCadastro(){
if (session()->has("login")){
return view('telas_cadastro.cadastro_unidades');
}
return view('tela_login');
}
function telaAlteracao($id){
if (session()->has("login")){
$unidade = Unidade::find($id);
return view("telas_updates.alterar_unidade", [ "und" => $unidade ]);
}
return view('tela_login');
}
function adicionar(Request $req){
if (session()->has("login")){
$nome = $req->input('nome');
$unidade = new Unidade();
$unidade->nome = $nome;
if ($unidade->save()){
echo "<script>alert('Unidade $nome adicionada com Sucesso!');</script>";
} else {
echo "<script>alert('Unidade $nome nao foi adicionada!!!');</script>";
}
return UnidadeController::telaCadastro();
}
return view('tela_login');
}
function alterar(Request $req, $id){
if (session()->has("login")){
$unidade = Unidade::find($id);
$nome = $req->input('nome');
$unidade->nome = $nome;
if ($unidade->save()){
echo "<script>alert('Unidade $nome alterada com Sucesso!');</script>";
} else {
echo "<script>alert('Unidade $nome nao foi alterada!!!');</script>";
}
return UnidadeController::listar();
}
return view('tela_login');
}
function listar(){
if (session()->has("login")){
$unidade = Unidade::all();
return view("listas.lista_unidades", [ "und" => $unidade ]);
}else{
return view('tela_login');
}
}
function excluir($id){
if (session()->has("login")){
$unidade = Unidade::find($id);
$var = DB::table('produtos')->where('id_unidade','=',$id)->first();
if($var){
echo "<script>alert('A unidade nao pode ser excluida pois existem produtos associados');</script>";
}else{
if ($unidade->delete()){
echo "<script>alert('Unidade $id excluída com sucesso');</script>";
} else {
echo "<script>alert('Undade $id nao foi excluída!!!');</script>";
}
}
return UnidadeController::listar();
}else{
return view('tela_login');
}
}
}
|
// import original module declarations
import "styled-components";
// and extend them!
declare module "styled-components" {
export interface DefaultTheme {
insideBorder: string;
white: string;
black: string;
gray: { [key in ColorScale]: string };
main: string;
topbar: {
height: string;
};
transparent: string;
}
}
export type ColorScale = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
|
export class Expresspay {
/**
* Call this before 'checkoutPayment' to generate valid token from the server
*/
getToken(): Promise<Object>;
/**
* Present the expresspay payment UI.
* The result will be an an object with paymentStatus && errorMessage.
*/
checkoutPayment(): Promise<Object>;
/**
* Confirms the payment status
* The result will be an an object with paymentCompleteStatus && errorMessage.
*/
checkPaymentStatus(): Promise<Object>;
}
export declare const enum RequestType {
Submit = "submit",
CreateInvoice = "create_invoice",
Query = "query"
}
interface PayLoad {
/**
* Set server request type
* You can ignore this value if your server thats not rely on this.
*/
request?: RequestType
/**
* Set the developnment env
* Please ensure you set this value to false in your production code
* This helps to log server response
*/
enable_debug?: boolean
/**
* the full path url to the location on your servers where you implement our server side sdk
* if null it defaults to https://sandbox.expresspaygh.com/api/sdk/php/server.php
*/
server_url?: string
/**
* Currency of the transaction
*/
currency: string
/**
* Amount the customer is paying for the order
*/
amount: any
/**
* Unique order identification number
*/
order_id: string
/**
* Description of the order
*/
order_desc: string
/**
* Customer account number at Merchant
*/
account_number: any
/**
* URL that customer should be redirected at the completion of the payment process [ optional ]
*/
redirect_url?: string
/**
* Image that customer should be shown at Checkout [ optional ]
*/
order_img_url?: string
/**
* Customer First name [ optional ]
*/
first_name?: string
/**
* Customer Last name [ optional ]
*/
last_name?: string
/**
* Customer Phone Number [ optional ]
*/
phone_number?: string
/**
* Customer email address
*/
email?: string
}
/**
* @param {PayLoad} [options] - options for the express pay request.
*/
export function initialize(payload?: PayLoad): Expresspay;
|
module Modulus
module Import
module WeightTable
RANGE_START = 0
RANGE_END = 1
CHECK_ALGORITHM = 2
FIRST_CHECK_DIGIT = 3
CHECK_DIGIT_ENTRIES = 14
EXCEPTION_CASE = 17
def self.purge!
keys = Modulus.weight_table_keys
Modulus.redis.del( keys ) unless keys.empty?
end
def self.import_file(file)
CSV.foreach(file) do |row|
cells = row.first.split("\s")
start_range = cells[RANGE_START]
end_range = cells[RANGE_END]
weighting = Modulus::Weighting.new( parse_cells(cells) )
(start_range..end_range).each do |sort_code|
key = "#{Modulus.namespace}:#{sort_code}"
Modulus.redis.sadd( key, weighting.to_json )
end
end
end
private
def self.parse_cells(cells)
{
:digit_weights => cells.slice(FIRST_CHECK_DIGIT, CHECK_DIGIT_ENTRIES).map{ |d| d.to_i },
:check_method => parse_check_method( cells[CHECK_ALGORITHM] ),
:exception_case => cells[EXCEPTION_CASE].to_i
}
end
def self.parse_check_method(cell_value)
cell_value == 'DBLAL' ? 'DoubleAlternate' : (cell_value == 'MOD10' ? 'ModulusTen' : 'ModulusEleven')
end
end
end
end
|
using HotChocolate.Types;
namespace Metabase.GraphQl.References
{
public class ReferenceType
: InterfaceType<Data.IReference>
{
protected override void Configure(IInterfaceTypeDescriptor<Data.IReference> descriptor)
{
descriptor.Name(nameof(Data.IReference)[1..]);
}
}
}
|
package com.github.plume.oss.drivers
import com.github.plume.oss.PlumeStatistics
import org.slf4j.{Logger, LoggerFactory}
import java.io.File
import scala.util.Using
/** The driver used to connect to an in-memory TinkerGraph instance.
*/
final class TinkerGraphDriver extends GremlinDriver {
override protected val logger: Logger = LoggerFactory.getLogger(classOf[TinkerGraphDriver])
/** Add or update a org.apache.commons.configuration.BaseConfiguration key-value pair.
*
* @param key the key of the property.
* @param value the value of the property.
*/
def addConfig(key: String, value: String): TinkerGraphDriver = {
this.config.setProperty(key, value); this
}
/** Export the currently connected graph to the given path. The extension of the file should be included and may only
* be .xml, .json, or .kryo. If a graph file already exists it will be overwritten.
*
* @param filePath the file path to export to.
*/
def exportGraph(filePath: String): Unit = {
if (!isConnected) {
throw new RuntimeException(
"The driver is not connected to any graph and therefore cannot export anything!"
)
}
if (!isSupportedExtension(filePath)) {
throw new RuntimeException(
"Unsupported graph extension! Supported types are GraphML, GraphSON, and Gryo."
)
}
PlumeStatistics.time(
PlumeStatistics.TIME_CLOSE_DRIVER, {
Using.resource(this.graph.traversal()) { g =>
g.io[Any](filePath).write().iterate()
}
}
)
}
/** Imports a .xml, .json, or .kryo TinkerGraph file into the currently connected graph.
*
* @param filePath the file path to import from.
*/
def importGraph(filePath: String): Unit = {
if (!isConnected) {
throw new RuntimeException(
"The driver is not connected to any graph and therefore cannot import anything!"
)
}
if (!isSupportedExtension(filePath)) {
throw new RuntimeException(
"Unsupported graph extension! Supported types are GraphML, GraphSON, and Gryo."
)
}
if (!new File(filePath).exists) {
throw new RuntimeException(s"No existing serialized graph file was found at $filePath")
}
PlumeStatistics.time(
PlumeStatistics.TIME_OPEN_DRIVER, {
Using.resource(this.graph.traversal()) { g =>
g.io[Any](filePath).read().iterate()
}
}
)
}
/** Determines if the extension of the given file path is supported by TinkerGraph I/O.
*
* @param filePath the file path to check.
*/
private def isSupportedExtension(filePath: String): Boolean = {
val ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase()
"xml" == ext || "json" == ext || "kryo" == ext
}
}
|
class Module
private
# Aliases a method and undefines the original.
#
# class RenameExample
# def foo; "foo"; end
# rename_method(:bar, :foo)
# end
#
# example = RenameExample.new
# example.bar #=> 'foo'
#
# expect NoMethodError do
# example.foo
# end
#
# CREDIT: Trans
def rename_method( to_sym, from_sym )
raise ArgumentError, "method #{from_sym} does not exist" unless method_defined?( from_sym )
alias_method( to_sym, from_sym )
undef_method( from_sym )
end
alias_method :rename, :rename_method
end
|
#pylint: disable=too-many-arguments, too-many-locals
from typing import cast
from qcodes import Instrument, Parameter
from sim.data_provider import IDataProvider
from sim.mock_device import IMockDevice
from sim.mock_devices import MockQuantumDot
from sim.mock_pin import IMockPin
class SimulationParameter(Parameter):
""" Qcodes Parameter that wraps an IMockPin, which in turn
uses an IDataProvider as the backing data for the value
of the pin.
"""
def __init__(
self,
sim_pin : IMockPin,
**kwargs
):
super().__init__(**kwargs)
self._pin = sim_pin
def get_raw(self) -> float:
return self._pin.get_value()
def set_raw(self, value : float) -> None:
if self._pin.settable:
self._pin.set_value(value)
else:
raise RuntimeError(
f"Cannot set a value on pin '{self._pin.name}', "
f"which is using a non-settable data provider")
@property
def pin(self) -> IMockPin:
""" Retrieve the simulation pin that this QCoDeS parameter is wrapping """
return self._pin
def set_data_provider(self, data_provider : IDataProvider) -> None:
""" Convenience method to set the data provider on the pin backing this parameter """
self._pin.set_data_provider(data_provider)
class MockDeviceInstrument(Instrument):
""" Base class for all qcodes mock instruments that wrap an IMockDevice """
def __init__(self, name : str, mock_device : IMockDevice):
super().__init__(name)
self._mock_device = mock_device
@property
def mock_device(self) -> IMockDevice:
""" The mock device that this instrument is wrapping """
return self._mock_device
class QuantumDotMockInstrument(MockDeviceInstrument):
""" QCoDeS Mock Instrument that wraps a QuantumDotSim device """
def __init__(self, name: str = "QuantumDotMockInstrument"):
super().__init__(name, MockQuantumDot(name))
mock = self.mock_device
self.add_parameter(
"src",
parameter_class=SimulationParameter,
unit="V",
sim_pin=mock.src,
)
self.add_parameter(
"left_barrier",
parameter_class=SimulationParameter,
unit="V",
sim_pin=mock.l_barrier,
)
self.add_parameter(
"right_barrier",
parameter_class=SimulationParameter,
unit="V",
sim_pin=mock.r_barrier
)
self.add_parameter(
"central_barrier",
parameter_class=SimulationParameter,
unit="V",
sim_pin=mock.c_barrier,
)
self.add_parameter(
"left_plunger",
parameter_class=SimulationParameter,
unit="V",
sim_pin=mock.l_plunger,
)
self.add_parameter(
"right_plunger",
parameter_class=SimulationParameter,
unit="V",
sim_pin=mock.r_plunger,
)
self.add_parameter(
"drain",
parameter_class=SimulationParameter,
unit="I",
sim_pin=mock.drain
)
@property
def mock_device(self) -> MockQuantumDot:
""" The mock device that this instrument is wrapping """
return cast(MockQuantumDot, super().mock_device)
|
package eu.bunburya.apogee.utils
import java.util.regex.Pattern
/**
* Take a map where the keys are strings representing regex patters, and return a map where the keys are compiled
* Pattern objects.
*/
fun <valType> compileKeys(inMap: Map<String, valType>): Map<Pattern, valType> =
inMap.map { (k, v) -> Pattern.compile(k) to v }.toMap()
|
{-|
Module : Grammar
Description : Export the most useful functions to manipulate context-free grammars.
Copyright : (c) Davide Mancusi, 2017
License : BSD3
Maintainer : arekfu@gmail.com
Stability : experimental
Portability : POSIX
This module exports the most important datatypes and functions that can be used
to represent and manipulate context-free grammars.
-}
module Grammar
(
-- * Context-free grammars
-- ** The 'Grammar' typeclass
Grammar(..)
, Repr(..)
-- ** Context-free grammars over alphabets of integers
, IntCFG
, productionsToIntCFG
-- ** Context free grammars over alphabets of arbitrary types
, CFG
, productionsToCFG
-- ** Context-free grammars over alphabets of specific types
, CharCFG
, productionsToCharCFG
, parseCharCFG
, StringCFG
, productionsToStringCFG
-- ** Pretty-printing parts of a grammar
-- $examplegrammar
, showSymbol
, showWord
, showProductions
, showGrammar
, showGrammarUnquoted
, showGrammarQuoted
, showGrammarChevrons
, QuotingPolicy(..)
, quote
-- * Regular expressions
, Regex
, showRegex
, showRegexUnquoted
, showRegexQuoted
, showRegexChevrons
-- * Random grammar derivation
, MC
, evalMC
, randomGrammarDerive
, randomGrammarDeriveScan
) where
-- local imports
import Grammar.CFG
import Grammar.CFG.Parse
import Grammar.CFG.Random
import Grammar.Regex
import Grammar.MC
{- $examplegrammar #examplegrammar#
We illustrate the pretty-printing functionality with the following example grammar:
> exampleKeyValue :: [(Char, [String])]
> exampleKeyValue = let initialChars = map (:[]) ['a'..'c']
> chars = ['a'..'c'] ++ ['0'..'3']
> expansions = map (\c -> ['I', c]) chars
> in [ ('E', ["E+E", "E*E", "(E)", "I"])
> , ('I', initialChars ++ expansions)
> ]
>
> exampleGrammar :: CharCFG
> exampleGrammar = productionsToCharCFG exampleKeyValue
-}
|
# frozen-string-literal: true
require_dependency 'active_support/core_ext/module/delegation'
# Domain model object encapsulating a particular data view in the UI, based
# around a particular theme group of indicators in the cube. For example,
# a view of the `averagePrice` indicator, together with the relevant dates,
# location and other options, and access to the underlying data, to enable
# the renderer to draw the display
class DataView # rubocop:disable Metrics/ClassLength
include Rails.application.routes.url_helpers
attr_reader :user_selections, :query_result, :indicator, :theme
attr_accessor :first
def initialize(user_selections:, query_result:, indicator:, theme:)
@user_selections = user_selections
@query_result = query_result
@indicator = indicator
@theme = theme
end
delegate :from_date, to: :user_selections
delegate :to_date, to: :user_selections
delegate :selected_location, to: :user_selections
# @return The title for this view, taking into account the indicator and
# the theme name
def title
indicator ? title_with_indicator : title_without_indicator
end
# @return The label for the currently selected location
def selected_location_label
@selected_location_label ||=
Locations.lookup_location(selected_location)
.label
end
# @return True if a data view should be visible, given the indicator and theme
def visible?
user_selections.selected_themes.include?(theme.slug) &&
(!indicator || user_selections.selected_indicators.include?(indicator.slug))
end
# @return The link location for showing or hiding a data view by adding or
# removing the theme from the selected themes
def add_remove_theme_link(add)
add_remove_param(add, 'thm', theme.slug)
end
# Invoke a block for each of this theme's statisics
def each_statistic(&block)
theme.statistics.each(&block)
end
# @return True if a given statistic is selected for this theme
def statistic_selected?(statistic)
user_selections.selected_statistics.include?(statistic.slug)
end
# @return The link location for adding or removing a statistic from a theme
def add_remove_statistic(add, statistic)
add_remove_param(add, 'st', statistic.slug)
end
# @return The data from the query, formatted in way that's suitable for
# rendering in a table
def as_table_data
columns = as_table_columns
data = project_data(query_result, columns)
{ columns: columns, data: data }
end
# @return A Hash of the attributes needed to convey the key parameters of
# this data view to JavaScript code
def as_js_attributes # rubocop:disable Metrics/AbcSize
{
indicator: indicator.to_h(user_selections).to_json,
theme: theme.to_h(user_selections).to_json,
location: Locations.lookup_location(selected_location).to_json,
from_date: { date: user_selections.from_date }.to_json,
to_date: { date: user_selections.to_date }.to_json,
first: first ? 'true' : nil
}
end
# @return A node ID for this data view, identifying the indicator and theme
def node_id
"#{indicator ? "#{indicator.slug}-" : ''}#{theme.slug}".tr('_', '-')
end
private
def title_with_indicator
change_path = edit_browse_path(user_selections.params)
title_location_translated = title_location
<<~TITLE
#{indicator.label}
#{I18n.t('preposition.by')}
#{theme.label.downcase}
<span class='o-data-view__location-preposition'>#{title_location_translated[:preposition]}</span>
<a href='#{change_path}' class='o-data-view__location'>#{title_location_translated[:html]}</a>
TITLE
.html_safe # rubocop:disable Rails/OutputSafety
end
def title_without_indicator
change_path = edit_browse_path(user_selections.params)
title_location_translated = title_location
<<~TITLE
#{indicator.label}
<span class='o-data-view__location-preposition'>#{title_location_translated[:preposition]}</span>
<a href='#{change_path}' class='o-data-view__location'>#{title_location_translated[:html]}</a>
TITLE
.html_safe # rubocop:disable Rails/OutputSafety
end
def title_location
icon = "<i class='fa fa-pencil-square-o'></i>"
llabel = if location.welsh_name?
WelshGrammar.apply(source: location.label, assuming_prefix: I18n.t('preposition.in'))
else
OpenStruct.new(result: location.label, prefix: I18n.t('preposition.in'))
end
{
html: "<span class='o-data-view__location-name'>#{llabel.result}</span> #{icon}",
preposition: llabel.prefix
}
end
def title_key
theme.slug
end
def ukhpi
@ukhpi ||= UkhpiDataCube.new
end
def add_remove_param(add, param, value)
adjacent_selections = user_selections.send(add ? :with : :without, param, value)
"?#{UserSelectionsPresenter.new(adjacent_selections).as_url_search_string}"
end
def as_table_columns
[{ label: I18n.t('label.date'), pred: 'ukhpi:refMonth' }] +
theme.statistics.map do |statistic|
if statistic_selected?(statistic)
{ label: I18n.t("statistic.#{statistic.label_key}"), pred: pred_name(statistic) }
end
end.compact
end
def pred_name(statistic)
"ukhpi:#{indicator_name(indicator)}#{statistic_name(statistic)}"
end
def indicator_name(indicator)
indicator&.root_name
end
def statistic_name(statistic)
statistic.root_name
end
def project_data(query_result, columns)
query_result.map do |row_data|
columns.map do |column|
datum = row_data[column[:pred]]
datum = datum.is_a?(Hash) ? datum['@value'] : datum
datum.is_a?(Array) && datum.length == 1 ? datum.first : datum
end
end
end
def location
Locations.lookup_location(user_selections.selected_location)
end
end
|
import sys
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findSecondMinimumValue(self, root: TreeNode) -> int:
if not root or (not root.left and not root.right):
return -1
if root.left.val < root.right.val:
secondMinInLeft = self.findSecondMinimumValue(root.left)
return root.right.val if secondMinInLeft == -1 else min(root.right.val, secondMinInLeft)
elif root.left.val > root.right.val:
secondMinInRight = self.findSecondMinimumValue(root.right)
return root.left.val if secondMinInRight == -1 else min(root.left.val, secondMinInRight)
else:
secondMinInLeft = self.findSecondMinimumValue(root.left)
secondMinInRight = self.findSecondMinimumValue(root.right)
if secondMinInLeft == -1 and secondMinInRight == -1:
return -1
elif secondMinInLeft == -1:
return secondMinInRight
elif secondMinInRight == -1:
return secondMinInLeft
return min(secondMinInLeft, secondMinInRight)
root = TreeNode(10)
root.left = TreeNode(3)
root.left.left = TreeNode(2)
root.left.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(9)
root.right = TreeNode(15)
root.right.left = TreeNode(13)
root.right.right = TreeNode(17)
root.right.right.right = TreeNode(19)
ob = Solution()
print(ob.findSecondMinimumValue(root))
|
package io.suggest.log.buffered
import io.suggest.log.{ILogAction, MLogMsg}
import scala.scalajs.js.timers.SetTimeoutHandle
import scala.util.Try
/**
* Suggest.io
* User: Konstantin Nikiforov <konstantin.nikiforov@cbca.ru>
* Created: 30.04.2020 13:49
* Description: Экшены буферизатора логов.
*/
sealed trait IBufLogAppendAction extends ILogAction
/** Закидывание лог-сообщений в буфер. */
case class LogAppend( logMsgs: Seq[MLogMsg] ) extends IBufLogAppendAction
/** Результат обновления таймера. */
case class ExpTimerUpdate( timerId: Try[Option[SetTimeoutHandle]] ) extends IBufLogAppendAction
/** Срабатывание таймера. */
case object ExpTimerAlarm extends IBufLogAppendAction
|
#!/bin/bash
# Copyright (C) The Arvados Authors. All rights reserved.
#
# SPDX-License-Identifier: AGPL-3.0
set -e -o pipefail
if test -z "$1" ; then
echo "$0: Copies Arvados tutorial resources from public data cluster (jutro)"
echo "Usage: copy-tutorial.sh <tutorial>"
echo "<tutorial> is which tutorial to copy, one of:"
echo " bwa-mem Tutorial from https://doc.arvados.org/user/tutorials/tutorial-workflow-workbench.html"
echo " whole-genome Whole genome variant calling tutorial workflow (large)"
exit
fi
if test -z "ARVADOS_API_HOST" ; then
echo "Please set ARVADOS_API_HOST to the destination cluster"
exit
fi
src=jutro
tutorial=$1
if ! test -f $HOME/.config/arvados/jutro.conf ; then
# Set it up with the anonymous user token.
echo "ARVADOS_API_HOST=jutro.arvadosapi.com" > $HOME/.config/arvados/jutro.conf
echo "ARVADOS_API_TOKEN=v2/jutro-gj3su-e2o9x84aeg7q005/22idg1m3zna4qe4id3n0b9aw86t72jdw8qu1zj45aboh1mm4ej" >> $HOME/.config/arvados/jutro.conf
exit 1
fi
echo
echo "Copying from public data cluster (jutro) to $ARVADOS_API_HOST"
echo
make_project() {
name="$1"
owner="$2"
if test -z "$owner" ; then
owner=$(arv --format=uuid user current)
fi
project_uuid=$(arv --format=uuid group list --filters '[["name", "=", "'"$name"'"], ["owner_uuid", "=", "'$owner'"]]')
if test -z "$project_uuid" ; then
project_uuid=$(arv --format=uuid group create --group '{"name":"'"$name"'", "group_class": "project", "owner_uuid": "'$owner'"}')
fi
echo $project_uuid
}
copy_jobs_image() {
if ! arv-keepdocker | grep "arvados/jobs *latest" ; then
arv-copy --project-uuid=$parent_project jutro-4zz18-sxmit0qs6i9n2s4
fi
}
parent_project=$(make_project "Tutorial projects")
copy_jobs_image
if test "$tutorial" = "bwa-mem" ; then
echo
echo "Copying bwa mem tutorial"
echo
arv-copy --project-uuid=$parent_project jutro-j7d0g-rehmt1w5v2p2drp
echo
echo "Finished, data copied to \"User guide resources\" at $parent_project"
echo "You can now go to Workbench and choose 'Run a process' and then select 'bwa-mem.cwl'"
echo
fi
if test "$tutorial" = "whole-genome" ; then
echo
echo "Copying whole genome variant calling tutorial"
echo
arv-copy --project-uuid=$parent_project jutro-j7d0g-n2g87m02rsl4cx2
echo
echo "Finished, data copied to \"WGS Processing Tutorial\" at $parent_project"
echo "You can now go to Workbench and choose 'Run a process' and then select 'WGS Processing Tutorial'"
echo
fi
|
package CloudForest
// ScikitNode
// cdef struct Node:
// # Base storage structure for the nodes in a Tree object
// SIZE_t left_child # id of the left child of the node
// SIZE_t right_child # id of the right child of the node
// SIZE_t feature # Feature used for splitting the node
// DOUBLE_t threshold # Threshold value at the node
// DOUBLE_t impurity # Impurity of the node (i.e., the value of the criterion)
// SIZE_t n_node_samples # Number of samples at the node
// DOUBLE_t weighted_n_node_samples # Weighted number of samples at the node
type ScikitNode struct {
LeftChild int `json:"left_child"`
RightChild int `json:"right_child"`
Feature int `json:"feature"`
Threshold float64 `json:"threshold"`
Impurity float64 `json:"impurity"` //TODO(ryan): support this?
NNodeSamples int `json:"n_node_samples"` //TODO(ryan): support this?
WeightedNNodeSamples float64 `json:"weighted_n_node_samples"` //TODO(ryan): support this?
}
// AnnotatedTree represents a decision tree in the memory format used by scikit learn.
// cdef class Tree:
// # The Tree object is a binary tree structure constructed by the
// # TreeBuilder. The tree structure is used for predictions and
// # feature importances.
// # Input/Output layout
// cdef public SIZE_t n_features # Number of features in X
// cdef SIZE_t* n_classes # Number of classes in y[:, k]
// cdef public SIZE_t n_outputs # Number of outputs in y
// cdef public SIZE_t max_n_classes # max(n_classes)
// # Inner structures: values are stored separately from node structure,
// # since size is determined at runtime.
// cdef public SIZE_t max_depth # Max depth of the tree
// cdef public SIZE_t node_count # Counter for node IDs
// cdef public SIZE_t capacity # Capacity of tree, in terms of nodes
// cdef Node* nodes # Array of nodes
// cdef double* value # (capacity, n_outputs, max_n_classes) array of values
// cdef SIZE_t value_stride # = n_outputs * max_n_classes
type ScikitTree struct {
NFeatures int `json:"n_features"`
NClasses []int `json:"n_classes"`
NOutputs int `json:"n_outputs"` //TODO(ryan): support other values
MaxNClasses int `json:"max_n_classes"` //TODO(ryan): support other values
MaxDepth int `json:"max_depth"`
NodeCount int `json:"node_count"`
Capacity int `json:"capacity"`
Nodes []ScikitNode `json:"nodes"`
Value [][][]float64 `json:"value"` //TODO(ryan): support actual values
ValueStride int `json:"value_stride"`
}
func NewScikitTree(nFeatures int) *ScikitTree {
tree := &ScikitTree{
NFeatures: nFeatures,
NClasses: []int{2},
NOutputs: 1,
MaxNClasses: 2,
MaxDepth: 0,
NodeCount: 0,
Capacity: 0,
Nodes: make([]ScikitNode, 0),
Value: make([][][]float64, 0),
ValueStride: 0}
return tree
}
// BuildScikkitTree currentelly only builds the split threshold and node structure of a sickit tree from a
// Cloudforest tree specified by root node
func BuildScikitTree(depth int, n *Node, sktree *ScikitTree) {
if depth > sktree.MaxDepth {
sktree.MaxDepth = depth
}
depth++
sktree.NodeCount++
sktree.Capacity++
skn := ScikitNode{}
pos := len(sktree.Nodes)
// We can't use a pointer here because the array will move and we're building this as an array
// of structs for sklearn memory compatibility later so we use a pos.
sktree.Nodes = append(sktree.Nodes, skn)
if n.Splitter != nil {
sktree.Nodes[pos].Feature = n.Featurei
sktree.Nodes[pos].Threshold = n.Splitter.Value
sktree.Nodes[pos].LeftChild = sktree.NodeCount
BuildScikitTree(depth, n.Left, sktree)
sktree.Nodes[pos].RightChild = sktree.NodeCount
BuildScikitTree(depth, n.Right, sktree)
} else {
// Leaf node
sktree.Nodes[pos].LeftChild = -1
sktree.Nodes[pos].RightChild = -1
}
}
|
package models
import (
"github.com/jinzhu/gorm"
"github.com/wenxian2012/go-rbac-admin/dto"
)
type AuthSwag struct {
Username string `json:"username"`
Password string `json:"password"`
}
type User struct {
Model
Username *string `gorm:"column:username"`
Password *string `gorm:"column:password"`
Nickname *string `gorm:"column:nickname"`
Disabled *int `gorm:"column:disabled"`
Phone *string `gorm:"column:phone"`
Email *string `gorm:"column:email"`
Roles []*Role `gorm:"many2many:user_role;"`
}
func (a User) TableName() string {
return a.Model.TableName("user")
}
func (a *User) ToDtoUser() *dto.User {
user := dto.User{
ID: a.ID,
Username: *a.Username,
Password: *a.Password,
Nickname: *a.Nickname,
Roles: ToDtoRoles(a.Roles),
UpdatedAt: a.UpdatedAt,
}
if a.Phone != nil {
user.Phone = *a.Phone
}
if a.Email != nil {
user.Email = *a.Email
}
if a.Disabled != nil {
user.Disabled = *a.Disabled
}
return &user
}
type UserRole struct {
Model
UserID int `gorm:"column:user_id"`
RoleID int `gorm:"column:role_id"`
}
func (a UserRole) TableName() string {
return a.Model.TableName("user_role")
}
func CheckUser(username, password string) (*User, error) {
var user User
err := db.Model(&User{}).Where(User{Username: &username, Password: &password}).First(&user).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
if user.ID > 0 {
return &user, nil
}
return nil, nil
}
func CheckUsername(username string) (bool, error) {
var user User
err := db.Where("username = ?", username).First(&user).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if user.ID > 0 {
return true, nil
}
return false, nil
}
func GetUsersAll() ([]*User, error) {
var user []*User
err := db.Preload("Roles").Find(&user).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return user, nil
}
func (a *User) Query(params *dto.UserQueryParams) ([]*User, int, error) {
var list = []*User{}
var count int
db := db.Model(&User{})
if v := params.Username; v != "" {
db = db.Where("username LIKE ?", "%"+v+"%")
}
if v := params.Nickname; v != "" {
db = db.Where("nickname LIKE ?", "%"+v+"%")
}
if v := params.Phone; v != "" {
db = db.Where("phone LIKE ?", "%"+v+"%")
}
if v := params.Email; v != "" {
db = db.Where("email LIKE ?", "%"+v+"%")
}
if v := params.Disabled; v != nil {
db = db.Where("disabled = ?", v)
}
if v := params.RoleId; v != 0 {
subQuery := db.Model(&UserRole{}).Select("user_id").Where("role_id = ?", v).SubQuery()
db = db.Where("id IN (?)", subQuery)
}
db.Count(&count)
err := db.Preload("Roles").Offset(params.PageNum).Limit(params.PageSize).Find(&list).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, count, err
}
return list, count, nil
}
func (a *User) Find(id int) (*User, error) {
var user User
err := db.Preload("Roles").Where("id = ? ", id).First(&user).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return &user, nil
}
func (a *User) Update(roleIds []int) error {
var role []Role
db.Where("id in (?)", roleIds).Find(&role)
if err := db.Model(&User{}).Updates(a).Association("Roles").Replace(role).Error; err != nil {
return err
}
return nil
}
func (a *User) Create(roleIds []int) error {
var role []Role
db.Where("id in (?)", roleIds).Find(&role)
if err := db.Create(a).Error; err != nil {
return err
}
if err := db.Model(a).Association("Roles").Append(role).Error; err != nil {
return err
}
return nil
}
func (a *User) Delete(id int) error {
if err := db.Delete(User{Model: Model{ID: id}}).Association("Roles").Clear().Error; err != nil {
return err
}
return nil
}
|
-- @testpoint: 创建角色
drop ROLE if exists sys_role;
CREATE ROLE sys_role with createdb IDENTIFIED BY 'Bigdata@123' ;
drop ROLE if exists sys_role;
|
SELECT * FROM `t1`;
DELIMITER $
SELECT * FROM `t2`$
DELIMITER !!
SELECT * FROM `t3`!!
|
//CONTROLS =====================================================================
#define grad_moneymenu_DIALOG 40000
#define grad_moneymenu_title 40001
#define grad_moneymenu_myfunds 40010
#define grad_moneymenu_myfundsDesc 40011
#define grad_moneymenu_input 40020
#define grad_moneymenu_okbutton 40030
#define grad_moneymenu_recipient 40040
//DIMENSIONS AND POSITIONS =====================================================
#define grad_moneymenu_BG_W (0.4 * X_SCALE)
#define grad_moneymenu_Item_H (0.025 * Y_SCALE)
#define grad_moneymenu_Item_W (0.025 * X_SCALE)
#define grad_moneymenu_ItemSpace_Y (0.0025 * SZ_SCALE)
#define grad_moneymenu_Padding_Y (0.5 * grad_moneymenu_Item_H)
#define grad_moneymenu_Padding_X (0.5 * grad_moneymenu_Item_W)
#define grad_moneymenu_Info_W (grad_moneymenu_BG_W - 2*grad_moneymenu_Padding_X)
#define grad_moneymenu_Input_W (0.45 * grad_moneymenu_Info_W)
#define grad_moneymenu_Recipient_W (0.5 * grad_moneymenu_Info_W)
#define grad_moneymenu_Button_W (0.15 * X_SCALE)
#define grad_moneymenu_CloseButton_W (grad_moneymenu_Item_H - (2 * grad_moneymenu_ItemSpace_Y))
#define grad_moneymenu_TopBar_Y (grad_moneymenu_BG_Y - grad_moneymenu_Item_H - grad_moneymenu_ItemSpace_Y)
#define grad_moneymenu_BG_H (2*grad_moneymenu_Item_H + 3*grad_moneymenu_Padding_Y)
#define grad_moneymenu_BG_X CENTER(1, grad_moneymenu_BG_W)
#define grad_moneymenu_BG_Y CENTER(1, grad_moneymenu_BG_H)
|
package divyansh.tech.animeclassroom.home
import android.util.Log
import divyansh.tech.animeclassroom.ResultWrapper
import divyansh.tech.animeclassroom.models.home.AnimeModel
import divyansh.tech.animeclassroom.models.home.OfflineAnimeModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
import divyansh.tech.animeclassroom.utils.HomeTypes
/*
* Main default repo, to fetch data both from remote and locally
* */
class HomeDefaultRepo @Inject constructor(
private val remoteRepo: HomeRemoteRepo,
private val localRepo: HomeLocalRepo
) {
/*
* Call the function to fetch popular animes
* @returns: Flow<ResultWrapper<*>>
* */
suspend fun parsePopularAnimes(): Flow<ResultWrapper<*>> {
return flow {
val localData=localRepo.getAllPopularAnime()
val responseLocal= arrayListOf<AnimeModel>()
if(localData.isNotEmpty()){
for (data in localData) responseLocal.add(convertToAnimeModel(data))
}
val response = remoteRepo.getPopularAnimes()
for(anime in (response.data as ArrayList<AnimeModel>))
localRepo.saveAnimeDataOffline(anime, HomeTypes.POPULAR_ANIME.name)
emit(ResultWrapper.Success(responseLocal))
}
}
/*
* Call the function to fetch recent releases
* @returns Flow<ResultWrapper<*>>
* */
suspend fun parseRecentReleases(): Flow<ResultWrapper<*>> {
return flow {
val localData=localRepo.getAllRecentReleases()
val responseLocal= arrayListOf<AnimeModel>()
if(localData.isNotEmpty()){
for (data in localData) responseLocal.add(convertToAnimeModel(data))
}
val response = remoteRepo.getRecentReleases()
for(anime in (response.data as ArrayList<AnimeModel>))
localRepo.saveAnimeDataOffline(anime, HomeTypes.RECENT_RELEASE.name)
emit(ResultWrapper.Success(responseLocal))
}
}
/*
* Call the function to fetch popular movies
* @returns: Flow<ResultWrapper<*>>
* */
suspend fun parsePopularMovies(): Flow<ResultWrapper<*>> {
return flow {
val localData=localRepo.getAllPopularMovies()
val responseLocal= arrayListOf<AnimeModel>()
if(localData.isNotEmpty()){
for (data in localData) responseLocal.add(convertToAnimeModel(data))
}
val response = remoteRepo.getPopularMovies()
for(anime in (response.data as ArrayList<AnimeModel>))
localRepo.saveAnimeDataOffline(anime, HomeTypes.POPULAR_MOVIES.name)
emit(ResultWrapper.Success(responseLocal))
}
}
/*
* Call the function to fetch new seasons
* @returns: Flow<ResultWrapper<*>>
* */
suspend fun parseNewSeasons(): Flow<ResultWrapper<*>> {
return flow {
val localData=localRepo.getAllNewSeasons()
val responseLocal= arrayListOf<AnimeModel>()
if(localData.isNotEmpty()){
for (data in localData) responseLocal.add(convertToAnimeModel(data))
}
val response = remoteRepo.getNewSeasons()
for(anime in (response.data as ArrayList<AnimeModel>))
localRepo.saveAnimeDataOffline(anime, HomeTypes.NEW_SEASON.name)
emit(ResultWrapper.Success(responseLocal))
}
}
/*
* Call the function to fetch new seasons
* @returns: Flow<ResultWrapper<*>>
* */
suspend fun parseGenres(): Flow<ResultWrapper<*>> {
//TODO: Add local data first. (caching purpose)
return flow {
val response = remoteRepo.getGenres()
emit(response)
}
}
fun convertToAnimeModel(offlineAnimeModel: OfflineAnimeModel):AnimeModel{
return AnimeModel(
name = offlineAnimeModel.name,
imageUrl = offlineAnimeModel.imageUrl,
releaseDate = offlineAnimeModel.releaseDate,
animeUrl = offlineAnimeModel.animeUrl,
episodeNumber = offlineAnimeModel.episodeNumber,
episodeUrl = offlineAnimeModel.episodeUrl,
genre = offlineAnimeModel.genre)
}
}
|
#!/bin/bash
set -euo pipefail
CONFIG_FILE="`dirname \"$0\"`"/../config.sh
source ${CONFIG_FILE}
docker volume create \
--label "${PROJECT_LABEL}" \
"$JENKINS_VOLUME"
|
{
> I am trying to issue an SCSI START/StoP Unit via Adaptec's ASPI SCSI
> manager and an 1542B host adaptor. This is For an application I am
> writing in BP. Adaptec is of no help. if anyone here has any
> comments
> or suggestions please respond in this Forum.
}
Unit Aspi;
{ I/O Error reporting:
AspiSenseKey is the primary source of error inFormation.
0: I/O Complete.
Warnings (Filemark, Short block, etc) may be posted in Sense.
1-E: Error occured.
Examine SRBStat, HostStat, TargStat, Sense For details.
F: Severe error detected, no SCSI info available.
-------------------------------------------------------------------- }
Interface
Const
SrbIn = $08;
SRBOut = $10;
SRBNone = $18;
AspiPtr: Pointer = Nil;
Type
AspiSrb = Record
SrbCmd: Byte;
SrbStat: Byte;
SrbHost: Byte;
SrbReqFlags: Byte;
SrbHdrFill: LongInt;
Case Integer of
2: (Srb2TargetID: Byte;
Srb2LUN: Byte;
Srb2DataLen: LongInt;
Srb2SenseLen: Byte;
Srb2DataPtr: Pointer;
Srb2LinkPtr: Pointer;
Srb2CDBLen: Byte;
Srb2HAStat: Byte;
Srb2TargStat: Byte;
Srb2PostAddr: Pointer;
Srb2Filler: Array [1..34] of Byte;
{ Sense data follows CDB }
Srb2CDB: Array [0..50] of Byte);
1: (Srb1TargetID: Byte;
Srb1LUN: Byte;
Srb1DevType: Byte);
0: (Srb0Cnt: Byte;
Srb0TargetID: Byte;
Srb0MgrID: Array [1..16] of Char;
Srb0HostID: Array [1..16] of Char;
Srb0HostParm: Array [1..16] of Char);
end;
Var
AspiSRBStat: Byte;
AspiHostStat: Byte;
AspiTargStat: Byte;
AspiSenseKey: Byte;
AspiSense: Array [0..17] of Byte;
AspiSenseCode: Word;
Function AspiOpen: Integer;
Procedure AspiCall (Var SRB: AspiSrb);
{ Call ASPI Handler With SRB }
Inline ($FF/$1E/>AspiPtr/
$58/$58);
Procedure AspiWait (Var SRB: AspiSrb);
Function AspiClose: Integer;
Implementation
Uses Dos;
Procedure AspiWait (Var SRB: AspiSRB);
{ Call ASPI Handler With SRB and wait For Completion }
begin
if AspiPtr = Nil
then begin
AspiSenseKey := $0F;
Exit;
end;
With Srb do begin
SrbStat := 0;
AspiCall (Srb);
While SrbStat = 0 do ;
AspiSrbStat := SrbStat;
AspiHostStat := Srb2HAStat;
AspiTargStat := Srb2TargStat;
AspiSenseKey := 0;
FillChar (AspiSense, Sizeof (AspiSense), #0);
Move (Srb2CDB [Srb2CDBLen], AspiSense, Sizeof (AspiSense));
AspiSenseKey := AspiSense[2] and $0F;
AspiSenseCode := (AspiSense [12] SHL 8) or AspiSense [13];
end;
end;
Function AspiOpen: Integer;
Const
AspiName: Array [1..9] of Char = 'SCSIMGR$'#0;
Var
R: Registers;
AspiHan: Word;
begin
With R do begin
{ Assume failure }
AspiOpen := -1;
AspiPtr := Nil;
{ Open ASPI device driver }
AX := $3D00;
DS := Seg (AspiName[1]);
DX := ofs (AspiName[1]);
MSDos (R);
if odd (Flags)
then Exit;
AspiHan := AX;
{ Do IOCtl Read to get Pointer to ASPI handler }
AX := $4402;
BX := AspiHan;
CX := 4;
DS := Seg (AspiPtr);
DX := ofs (AspiPtr);
MSDos (R);
if Odd (flags)
then Exit;
{ Close device driver }
AX := $3E00;
BX := AspiHan;
MsDos (R);
if Odd (Flags)
then Exit;
end;
{ Indicate success and Exit }
AspiOpen := 0;
end { AspiOpen };
Function AspiClose: Integer;
begin
AspiClose := 0;
end { AspiClose };
end.
|
using System;
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using JsBind.Net.Tests.Infrastructure;
using TestBindings.WebAssembly;
namespace JsBind.Net.Tests.Tests
{
[TestClass(Description = "Dynamic Object Synchronous (WebAssembly)")]
public class DynamicObjectTestSynchronous
{
private readonly Window window;
private readonly Document document;
public DynamicObjectTestSynchronous(Window window, Document document)
{
this.window = window;
this.document = document;
}
[Fact(Description = "Primitive property get value")]
public void PrimitivePropertyGetValue()
{
// Arrange
var originProperty = Any.From(window)["origin"];
// Act
var origin = originProperty.GetValue<string>();
// Assert
origin.Should().NotBeNullOrEmpty();
}
[Fact(Description = "Reference property get value")]
public void ReferencePropertyGetValue()
{
// Arrange
var innerWindowProperty = Any.From(window)["window"];
// Act
var innerWindow = innerWindowProperty.GetValue<Window>();
// Assert
innerWindow.Should().NotBeNull();
innerWindow.Origin.Should().NotBeNullOrEmpty();
}
[Fact(Description = "Get primitive property value")]
public void GetPrimitivePropertyValue()
{
// Arrange
var dynamicTypeWindow = Any.From(window);
// Act
var origin = dynamicTypeWindow.GetPropertyValue<string>("origin");
// Assert
origin.Should().NotBeNullOrEmpty();
}
[Fact(Description = "Get reference property value")]
public void GetReferencePropertyValue()
{
// Arrange
var dynamicTypeWindow = Any.From(window);
// Act
var innerWindow = dynamicTypeWindow.GetPropertyValue<Window>("window");
// Assert
innerWindow.Should().NotBeNull();
innerWindow.Origin.Should().NotBeNullOrEmpty();
}
[Fact(Description = "Set property value")]
public void SetPropertyValue()
{
// Arrange
var dynamicTypeWindow = Any.From(window);
var testValue = Guid.NewGuid().ToString();
// Act
dynamicTypeWindow.SetPropertyValue("testProperty", testValue);
var actualValue = dynamicTypeWindow.GetPropertyValue<string>("testProperty");
// Assert
actualValue.Should().Be(testValue);
}
[Fact(Description = "Invoke function with primitive return value")]
public void InvokeFunctionWithPrimitiveReturnValue()
{
// Arrange
var dynamicTypeWindow = Any.From(window);
// Act
var result = dynamicTypeWindow.InvokeFunction<int>("parseInt", "30");
// Assert
result.Should().Be(30);
}
[Fact(Description = "Invoke function with reference return value")]
public void InvokeFunctionWithReferenceReturnValue()
{
// Arrange
var dynamicTypeDocument = Any.From(document);
// Act
var result = dynamicTypeDocument.InvokeFunction<Element>("getElementById", "app");
// Assert
result.Should().NotBeNull();
result.Id.Should().Be("app");
}
[Fact(Description = "Invoke function with array like return value")]
public void InvokeFunctionWithArrayLikeReturnValue()
{
// Arrange
var dynamicTypeDocument = Any.From(document);
// Act
var results = dynamicTypeDocument.InvokeFunction<IEnumerable<Element>>("querySelectorAll", "#app");
// Assert
results.Should().NotBeNull().And.HaveCount(1);
results.Single().Should().NotBeNull();
results.Single().Id.Should().Be("app");
}
}
}
|
@extends('layout')
@section('content')
@if (!Auth::guest())
<!-- List all the companies added by logged in user in a tabular format -->
<h6 style="color:#3366FF">
Contract '#{{$contract_info[0]->id}}' details
</h6>
<div class="contract_info">
<div>Client: {{$contract_info[0]->client_name}}</div>
<div>Client Manager: {{$contract_info[0]->client_manager_name}}</div>
<div>Supplier: {{$contract_info[0]->supplier_name}}</div>
<div>Bridge Account Manager: {{$contract_info[0]->supplier_manager_name}}</div>
<div>Supplier Company Manager: {{$contract_info[0]->supplier_manager_name}}</div>
<div>Client Price: {{$contract_info[0]->client_price}}</div>
<div>Supplier Price: {{$contract_info[0]->supplier_price}}</div>
<div>Fixed Price: @if($contract_info[0]->fixed_price==1) Yes @else NO @endif</div>
<div>Remarks: {{$contract_info[0]->remarks}}</div>
</div>
@endif
@stop
|
# vue-bulma-slider
Slider component for Vue Bulma.
Fork of [vue-bulma/slider](https://github.com/vue-bulma/slider)
## Installation
```
$ yarn add https://github.com/Andersbiha/vue-bulma-slider
```
## Examples
```vue
<template>
<div>
<slider type="success" size="large" :value="value" :max="100" :step="1" is-fullwidth @change="update"></slider>
<input class="input" type="number" v-model="value" min="0" max="100" number>
</div>
</template>
<script>
import Slider from 'vue-bulma-slider'
export default {
components: {
Slider
},
data () {
return {
value: 23
}
},
computed: {
per () {
return this.value + '%'
}
},
methods: {
update (val) {
this.value = Number(val)
}
}
}
</script>
```
|
package com.charlezz.opencvtutorial
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Parcelable
import androidx.annotation.DrawableRes
import org.opencv.android.Utils
import org.opencv.core.Mat
import org.opencv.imgproc.Imgproc
open abstract class Image constructor(
val title: String = "",
@DrawableRes val resId: Int
) : Parcelable {
var bitmap: Bitmap? = null
var result:String? = null
fun createBitmap(context: Context) {
if (resId != -1) {
bitmap = BitmapFactory.decodeResource(context.resources, resId)
val src = Mat()
Utils.bitmapToMat(bitmap, src)
Imgproc.cvtColor(src, src, Imgproc.COLOR_RGB2BGR)
bitmap = process(context, src)
}
}
open fun process(context: Context, src: Mat): Bitmap? {
return bitmap
}
}
|
package main
import (
"fmt"
"os"
"regexp"
"unicode"
)
const parse = `
getServoStatus = "getServoStatus" # 1.1 获取机械臂伺服状态
getMotorStatus = "getMotorStatus" # 1.2 获取机械臂上下电状态
setServoStatus = "set_servo_status" # 1.3 设置机械臂伺服状态
syncMotorStatus = "syncMotorStatus" # 1.4 同步伺服编码器数据
clearAlarm = "clearAlarm" # 1.5 清除报警
getMotorStatus = "getMotorStatus" # 1.6 获取同步状态
getRobotState = "getRobotState" # 2.1 获取机器人状态
getRobotMode = "getRobotMode" # 2.2 获取机器人模式
getRobotPos = "getRobotPos" # 2.3 获取机器人当前位置信息
getRobotPose = "getRobotPose" # 2.4 获取机器人当前位姿信息
getMotorSpeed = "getMotorSpeed" # 2.5 获取机器人马达速度
getCurrentCoord = "getCurrentCoord" # 2.6 获取机器人当前坐标
getCycleMode = "getServoStatus" # 2.7 获取机器人循环模式
getCurrentJobLine = "getCurrentJobLine" # 2.8 获取机器人当前作业运行行号
getCurrentEncode = "getCurrentEncode" # 2.9 获取机器人当前编码器值列表
getToolNumber = "getToolNumber" # 2.10 获取机器人当前工具号
getUserNumber = "getUserNumber" # 2.11 获取机器人当前用户工具号
getRobotTorques = "getRobotTorques" # 2.12 获取机器人当前力矩信息
getAnalogInput = "getAnalogInput" # 2.13 获取模拟量输入
setAnalogOutput = "setAnalogOutput" # 2.14 设置模拟量输出
dragTeachSwitch = "drag_teach_switch" # 2.15 拖动示教开关
setPayload = "cmd_set_payload" # 2.16 设置机械臂负载和重心
setToolCenterPoint = "cmd_set_tcp" # 2.17 设置机械臂工具中心
setToolNumber = "setToolNumber" # 2.18 切换机器人当前工具号
setUserNumber = "setUserNumber" # 2.19 切换机器人用户工具号
setCurrentCoord = "setCurrentCoord" # 2.20 指定坐标系
getCollisionState = "getCollisionState" # 2.21 获取碰撞状态
moveByJoint = "moveByJoint" # 3.1 关节运动
moveByLine = "moveByLine" # 3.2 直线运动
moveByArc = "moveByArc" # 3.3 圆弧运动
moveByRotate = "moveByRotate" # 3.4 旋转运动
stop = "stop" # 3.5 停止机器人运行
run = "run" # 3.6 机器人自动运行
pause = "pause" # 3.7 机器人暂停
addPathPoint = "addPathPoint" # 3.8 添加路点信息2.0
clearPathPoint = "clearPathPoint" # 3.9 清除路点信息2.0
moveByPath = "moveByPath" # 3.10 轨迹运动2.0
checkJbiExist = "checkJbiExist" # 3.11 检查jbi文件是否存在
runJbi = "runJbi" # 3.12 运行jbi文件
getJbiState = "getJbiState" # 3.13 获取jbi文件运行状态
getPathPointIndex = "getPathPointIndex" # 3.14 获取jbi文件运行状态
jog = "jog" # 3.15 jog运动
inverseKinematic = "inverseKinematic" # 4.1 逆解函数
positiveKinematic = "positiveKinematic" # 4.2 正解函数
convertPoseFromCartToUser = "convertPoseFromCartToUser" # 4.3 基坐标到用户坐标位姿转化
convertPoseFromUserToCart = "convertPoseFromUserToCart" # 4.4 用户坐标到基坐标位姿转化
inverseKinematicV2 = "inverseKinematic" # 4.5 逆解函数2.0 带参考点位置逆解
poseMul = "poseMul" # 4.6 位姿相乘
poseInv = "poseInv" # 4.7 位姿求逆
getInput = "getInput" # 5.1 获取输入IO状态
getOutput = "getOutput" # 5.2 获取输出IO状态
setOutput = "setOutput" # 5.3 设置输出IO状态
getVirtualInput = "getVirtualInput" # 5.4 获取虚拟输入IO状态
getVirtualOutput = "getVirtualOutput" # 5.5 获取虚拟输出IO状态
setVirtualOutput = "setVirtualOutput" # 5.6 设置虚拟输出IO状态
getSysVarB = "getSysVarB" # 6.1 获取系统B变量值
setSysVarB = "setSysVarB" # 6.2 设置系统B变量值
getSysVarI = "getSysVarI" # 6.3 获取系统I变量值
setSysVarI = "setSysVarI" # 6.4 设置系统I变量值
getSysVarD = "getSysVarD" # 6.5 获取系统D变量值
setSysVarD = "setSysVarD" # 6.6 设置系统D变量值
getSysVarPState = "getSysVarPState" # 6.7 获取系统P变量是否启用
getSysVarP = "getSysVarP" # 6.8 获取系统P变量值
getSysVarV = "getSysVarV" # 6.9 获取系统V变量值
ttInit = "transparent_transmission_init" # 7.1 初始化透传服务
ttSetCurrentServoJoint = "tt_set_current_servo_joint" # 7.2 设置当前透传伺服目标关节点
ttPutServoJointToBuf = "tt_put_servo_joint_to_buf" # 7.3 添加透传伺服目标关节点信息到缓存中
ttClearServoJointBuf = "tt_clear_servo_joint_buf" # 7.4 清空透传缓存
ttGetState = "get_transparent_transmission_state" # 7.5 获取当前机器人是否处于透传状态
getSoftVersion = "getSoftVersion" # 10.2 获取控制器软件版本号
`
var template = `
def %s(self) -> Any:
'''%s'''
# 注释
return self.send_cmd(Method.%s)
`
func main() {
dst := "dst.py"
fw, err := os.Create(dst)
if err != nil {
panic(err)
}
defer fw.Close()
reg := regexp.MustCompile(`(\w+) = ("\w+")\s*#\s*(.+)\n`)
for _, val := range reg.FindAllStringSubmatch(parse, -1) {
_, _ = fmt.Fprintf(fw, template, CamelCaseToUnderscore(val[1]), val[3], val[1])
}
}
func CamelCaseToUnderscore(s string) string {
var output []rune
var previous rune
for i, r := range s {
if i > 0 && unicode.IsUpper(r) && !unicode.IsUpper(previous) {
output = append(output, '_')
}
previous = r // 处理连续大写缩略词
output = append(output, unicode.ToLower(r))
}
return string(output)
}
|
package org.shirolang.base;
/**
*
* Defines a add of pre-defined multi-function types to
* be used to determine the
*/
public final class SType {
public static final String INTEGER = "Integer";
public static final String DOUBLE = "Double";
public static final String STRING = "String";
public static final String LIST = "List";
public static final String BOOLEAN = "Boolean";
public static final String GREATERTHAN = "GreaterThan";
public static final String GREATERTHAN_OR_EQUAL = "GreaterThanOrEqual";
public static final String LESSTHAN = "LessThan";
public static final String LESSTHAN_OR_EQUAL = "LessThanOrEqual";
public static final String EQUAL = "Equal";
public static final String NOT_EQUAL = "NotEqual";
public static final String AND = "And";
public static final String OR = "Or";
public static final String NOT = "Not";
public static final String ADD = "Add";
public static final String DIVIDE = "Divide";
public static final String MODULO = "Modulo";
public static final String MULTIPLY = "Multiply";
public static final String NEGATIVE = "Negative";
public static final String POWER = "Power";
public static final String SUBTRACT = "Subtract";
public static final String IDENT = "Ident";
public static final String SELECTOR = "Selector";
public static final String REFERENCE = "Reference";
public static final String MAP = "Map";
public static final String CONDITIONAL_RETURN = "ConditionalReturn";
public static final String CONDITIONAL_RETURN_NODE = "ConditionalReturnNode";
public static final String SUM = "Sum";
}
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import ProductsList from '../../components/ProductsList';
function action() {
const listaProdotti = [
{
_id: '5a61b31e009c0bef5d724a47',
name: 'PROSCIUTTO COTTO LENTI 80G',
EANCode: '',
price: 12.0,
},
{
_id: '5a61b31e009c0bef5d724a48',
name: 'GRANA PADANO DOP COOP 100g',
EANCode: '',
price: 2.05,
},
{
_id: '5a61b31e009c0bef5d724a49',
name: 'PETTO DI POLLO BIO COOP',
EANCode: '',
price: 7.21,
},
{
_id: '5a61b31e009c0bef5d724a4a',
name: 'PESTO SENZA AGLIO NOVELLA 120g',
EANCode: '',
price: 14.33,
},
];
return {
title: 'Elenco prodotti',
component: (
<Layout>
<ProductsList products={listaProdotti} />
</Layout>
),
};
}
export default action;
|
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
from collections import defaultdict
import torch
import numpy as np
from omegaconf import OmegaConf
def read_yaml(config_path):
conf = OmegaConf.load(config_path)
return conf
def write_yaml(conf, yaml_path):
OmegaConf.save(config=conf, f=yaml_path)
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = defaultdict(int)
self.avg = defaultdict(float)
self.sum = defaultdict(int)
self.count = defaultdict(int)
def update(self, n=1, **val):
for k in val:
self.val[k] = val[k]
self.sum[k] += val[k] * n
self.count[k] += n
self.avg[k] = self.sum[k] / self.count[k]
def set_batchnorm_mode(model, train=True):
"""Allows to set batch_norm layer mode to train or eval, independendtly on the mode of the model."""
def _set_batchnorm_mode(module):
if isinstance(module, torch.nn.BatchNorm1d) or isinstance(module, torch.nn.BatchNorm2d):
if train:
module.train()
else:
module.eval()
model.apply(_set_batchnorm_mode)
def get_error(output, target):
pred = output.argmax(dim=1)
correct = pred.eq(target).float().sum()
return float((1. - correct / output.size(0)) * 100.)
def adjust_learning_rate(optimizer, epoch, optimizer_cfg):
lr = optimizer_cfg.lr * (0.1 ** np.less(optimizer_cfg.schedule, epoch).sum())
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def get_device(model: torch.nn.Module):
return next(model.parameters()).device
|
.byte $01 ; Unknown purpose
.byte OBJ_GREENCHEEP, $0D, $16
.byte OBJ_BLOOPERCHILDSHOOT, $17, $14
.byte OBJ_WATERCURRENTDOWNARD, $1C, $14
.byte OBJ_GREENPIRANHA_FLIPPED, $23, $04
.byte OBJ_BIGBERTHABIRTHER, $24, $16
.byte OBJ_WATERCURRENTUPWARD, $28, $17
.byte OBJ_WATERCURRENTDOWNARD, $31, $16
.byte OBJ_REDPIRANHA_FLIPPED, $33, $08
.byte OBJ_GREENCHEEP, $44, $14
.byte OBJ_BLOOPERCHILDSHOOT, $4E, $14
.byte OBJ_WATERCURRENTUPWARD, $57, $18
.byte OBJ_GREENCHEEP, $58, $14
.byte OBJ_GREENPIRANHA, $65, $09
.byte OBJ_WATERCURRENTDOWNARD, $65, $16
.byte OBJ_GREENPIRANHA_FIRE, $6C, $08
.byte OBJ_BIGBERTHABIRTHER, $6C, $13
.byte $FF ; Terminator
|
FactoryBot.define do
factory :translation, aliases: [:project_translation] do
strings { {
title: "A test Project",
description: "Some Lorem Ipsum",
introduction: "Good times intro",
workflow_description: "Go outside",
researcher_quote: "This is my favorite project",
"urls.0.label" => "Blog",
"urls.1.label" => "Twitter"
} }
string_versions { {} }
association :translated, factory: :project
language { "en" }
factory :workflow_translation do
strings { {
"display_name" => "A translated Workflow name",
"interest.question" => "Draw a circle",
"interest.help" => "Duh?",
"interest.tools.0.label" => "Red",
"interest.tools.1.label" => "Green",
"interest.tools.2.label" => "Blue",
"interest.tools.3.label" => "Purple",
"interest.tools.3.details.0.answers.0.label"=>"Painfully wow",
"interest.tools.3.details.0.answers.1.label"=>"Just wow",
"interest.tools.3.details.0.question"=>"Wow rating:",
"shape.question" => "What shape is this galaxy",
"shape.help" => "Duh?",
"shape.answers.0.label" => "Smooth",
"shape.answers.1.label" => "Features",
"shape.answers.2.label" => "Star or artifact"
} }
association :translated, factory: :workflow
end
end
end
|
use same_file::Handle;
use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::path::Path;
fn main() -> Result<(), Error> {
let path_to_read = Path::new("content.txt");
let stdout_handle = Handle::stdout()?;
let handle = Handle::from_path(path_to_read)?;
if stdout_handle == handle {
return Err(Error::new(
ErrorKind::Other,
"You are reading and writing to the same file",
));
} else {
let file = File::open(&path_to_read)?;
let file = BufReader::new(file);
for (num, line) in file.lines().enumerate() {
println!("{} : {}", num, line?.to_uppercase());
}
}
Ok(())
}
|
//
// HistogramComputation.hpp
// EchoErrorCorrection
//
// Created by Miloš Šimek on 18/2/14.
//
#ifndef __EchoErrorCorrection__HistogramComputation__
#define __EchoErrorCorrection__HistogramComputation__
#include <vector>
#include <map>
#include <tuple>
#include <set>
#include <algorithm>
#include "RandomisedAccess.hpp"
#include "NeighbourTable.hpp"
#include "Tools.hpp"
using namespace std;
class HistogramComputation {
const RandomisedAccess& access;
const ConstNeighbTablePtr neighbTable;
//these 2 variables are altered by algorithm
//put a locks around them if you want to paralelize this part of algorithm
vector<unsigned> histogram;
set<ULL> histReadset;
public:
HistogramComputation(const RandomisedAccess& access, const ConstNeighbTablePtr neighbTable)
: access(access), neighbTable(neighbTable) {}
vector<unsigned> compute(unsigned minOverlap, double maxErrTolerance, ULL sampleSize);
private:
unsigned countNeighbours(ULL seqId, unsigned overlap, double errTolerance);
};
#endif /* defined(__EchoErrorCorrection__HistogramComputation__) */
|
package user.message
import document.annotation.AnnotationResult
import project.userroles.UserIdentifier
/**
* A message is a text between two users, optionally relating to an [AnnotationResult]
*/
data class Message(
val recipient: UserIdentifier,
val sender: UserIdentifier,
val message: String,
val annotatedDocument: AnnotationResult?,
val timestamp: Long = System.currentTimeMillis(),
var read: Boolean = false,
val _id: String? = null
)
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TemplateHaskell #-}
module Evaluator where
import Control.Arrow
import Control.Lens hiding (Lazy)
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.State
import Data.Char
import Data.List as List hiding (union)
import Data.Map as Map hiding (foldl, map)
import System.IO.Unsafe
import Data.Char
import qualified Lexer
import Location
import qualified Parser as P
import Pretty
import Token
{-
Evaluation Types
-}
data Program
= Value Value
deriving (Show)
data Value
= Integer Int
| Boolean Bool
| Closure Name P.Expression EvaluationContext
| Lazy P.Expression EvaluationContext
deriving (Show)
type Name = String
{-
## Pretty
-}
instance Pretty Program where
pretty (Value v) = pretty v
instance Pretty Value where
pretty (Integer i) = show i
pretty (Boolean b) = show b
pretty (Closure n e ctx) = "("++n++" => "++pretty e++")"
pretty (Lazy e ctx) = error "pretty (Lazy e ctx)"
{-
# EvaluatorState
-}
data EvaluatorState = EvaluatorState
{ _program :: P.Program
, _context :: EvaluationContext }
deriving (Show)
type EvaluationContext = Map Name Value
makeLenses ''EvaluatorState
showEvaluationContext :: EvaluationContext -> String
showEvaluationContext = unwords . map (\(n,v) -> "("++n++" => "++pretty v++")") . assocs
{-
# EvaluationStatus
-}
data EvaluatorStatus a = Ok a | Error (P.Expression, String)
instance Functor EvaluatorStatus where
f `fmap` Ok a = Ok (f a)
f `fmap` Error e = Error e
instance Applicative EvaluatorStatus where
pure = Ok
Ok f <*> Ok a = Ok (f a)
Ok _ <*> Error e = Error e
Error e <*> _ = Error e
instance Monad EvaluatorStatus where
Ok a >>= f = f a
Error e >>= _ = Error e
instance Show a => Show (EvaluatorStatus a) where
show (Ok a) = show a
show (Error (e, msg)) = "[!] Error in "++show e++", "++msg
{-
# Evaluator
-}
type Evaluator = StateT EvaluatorState EvaluatorStatus
{-
# Evaluation
-}
evaluate :: P.Program -> EvaluatorStatus Program
evaluate prgm = evalStateT evaluateProgram initEvaluatorState where
initEvaluatorState = EvaluatorState prgm empty
{-
## Evaluation Program
-}
evaluateProgram :: Evaluator Program
evaluateProgram = use program >>= \case
P.Expression expr -> Value <$> evaluateExpression expr
subEvaluate :: Evaluator a -> Evaluator a
subEvaluate evtr = do
st <- get
lift $ evalStateT evtr st
evaluateExpression :: P.Expression -> Evaluator Value
evaluateExpression expr = case expr of
P.Binding n e f -> do
eV <- evaluateExpression e
context . at n .= Just eV
evaluateExpression f
P.Application e f -> do
fV <- evaluateExpression f
(n, e, ctx) <- evaluateClosure e
evaluateApplication n fV e ctx
P.Lambda n e -> Closure n e <$> use context
P.Branching c e f -> evaluateBoolean e >>= \case
True -> evaluateExpression e
False -> evaluateExpression f
P.BinaryOperation o e f -> evaluateBinaryOperation o e f
P.UnaryOperation o e -> evaluateUnaryOperation o e
P.Literal t -> evaluateLiteral t
P.Associated e -> evaluateExpression e
evaluateClosure :: P.Expression -> Evaluator (P.Name, P.Expression, EvaluationContext)
evaluateClosure e = evaluateExpression e >>= \case
Closure n e ctx -> return (n, e, ctx)
eV -> errorUnexpected e "<Closure>" eV
-- [n => v](e with ctx)
evaluateApplication :: P.Name -> Value -> P.Expression -> EvaluationContext -> Evaluator Value
evaluateApplication n v e ctx = subEvaluate $ do
context %= union ctx
subEvaluate $ do
context . at n .= Just v
evaluateExpression e
integerBinaryOperators :: Map P.BinaryOperator (Int -> Int -> Int)
integerBinaryOperators = fromList
[ (P.Plus, (+))
, (P.Minus, (-))
, (P.Times, (*))
, (P.Divide, (div))
, (P.Modulus, (mod)) ]
-- , (P.Exponential, (**)) ]
booleanBinaryOperators :: Map P.BinaryOperator (Bool -> Bool -> Bool)
booleanBinaryOperators = fromList
[ (P.And, (&&))
, (P.Or, (||)) ]
evaluateBinaryOperation :: P.BinaryOperator -> P.Expression -> P.Expression -> Evaluator Value
evaluateBinaryOperation o e f =
if o `elem` keys integerBinaryOperators then do
x <- evaluateInteger e
y <- evaluateInteger f
return . Integer . uncurry (integerBinaryOperators!o) $ (x, y)
else if o `elem` keys booleanBinaryOperators then do
a <- evaluateBoolean e
b <- evaluateBoolean f
return . Boolean . uncurry (booleanBinaryOperators!o) $ (a, b)
else
fail "TODO"
evaluateUnaryOperation :: P.UnaryOperator -> P.Expression -> Evaluator Value
evaluateUnaryOperation o e = fail "TODO"
evaluateInteger :: P.Expression -> Evaluator Int
evaluateInteger e = evaluateExpression e >>= \case
Integer i -> return i
v -> errorUnexpected e "<Integer>" v
evaluateBoolean :: P.Expression -> Evaluator Bool
evaluateBoolean e = evaluateExpression e >>= \case
Boolean b -> return b
v -> errorUnexpected e "<Boolean>" v
evaluateLiteral :: Token -> Evaluator Value
evaluateLiteral t = do
mbV <- use $ context . at t
case mbV of
Just v -> return v
Nothing -> case t of
"true" -> return $ Boolean True
"false" -> return $ Boolean False
_ -> if all isDigit t
then return $ Integer (read t :: Int)
else errorUndefined t
{-
## Evaluation Utilities
-}
coerceValue :: Value -> Evaluator Value
coerceValue = \case
Lazy e ctx -> coerceValue =<< evaluateLazy e ctx
v -> return v
evaluateLazy :: P.Expression -> EvaluationContext -> Evaluator Value
evaluateLazy e ctx = subEvaluate $ do
context %= union ctx
evaluateExpression e
{-
# Errors
-}
errorUnexpected :: (Show b, Show a) => P.Expression -> a -> b -> Evaluator c
errorUnexpected expr exp unexp = lift $ Error (expr, "Expected "++show exp++", but found "++show unexp++".")
errorUndefined :: Token -> Evaluator a
errorUndefined t = lift $ Error (P.Literal t, "Undefined "++show t++".")
|
./gradlew codeCoverageReport -DincludeTags=unit
./gradlew codeCoverageReport -DincludeTags=producerOnly
./gradlew codeCoverageReport -DincludeTags=integration -DexcludeTags=redisCluster,producerOnly,local
./gradlew codeCoverageReport -DincludeTags=redisCluster
./gradlew codeCoverageReport -DincludeTags=local
export RQUEUE_REACTIVE_ENABLED=true
./gradlew codeCoverageReport -DincludeTags=unit
./gradlew codeCoverageReport -DincludeTags=producerOnly
./gradlew codeCoverageReport -DincludeTags=integration -DexcludeTags=redisCluster,producerOnly,local
./gradlew codeCoverageReport -DincludeTags=redisCluster
./gradlew codeCoverageReport -DincludeTags=local
|
package blended.streams.jms
import blended.jms.utils.JmsSession
import blended.util.RichTry._
import javax.jms._
import scala.util.{Failure, Success, Try}
class JmsConnector(
id : String,
jmsSettings : JmsSettings
)(
onSessionOpened : JmsSession => Try[Unit]
)(
beforeSessionCloseCallback : JmsSession => Try[Unit]
)(
afterSessionCloseCallback : JmsSession => Try[Unit]
)(
handleError : Throwable => Unit
) {
/**
* Initialize the connection to be used for this stage. If the connection can't be established,
* the stage will fail with an exception. For recovery, the stage should be wrapped within a
* [[blended.streams.StreamControllerSupport]].
*/
private val connection : Option[Connection] = Try {
jmsSettings.log.underlying.debug(s"Trying to create JMS connection for stream [$id]")
jmsSettings.connectionFactory.createConnection()
} match {
case Success(c) =>
Some(c)
case Failure(e) =>
handleError(e)
None
}
private val sessionMgr : Try[JmsSessionManager] = Try {
connection match {
case Some(c) =>
new JmsSessionManager(
name = id,
conn = c,
maxSessions = jmsSettings.sessionCount
) {
override def onSessionOpen: JmsSession => Try[Unit] = onSessionOpened
override def beforeSessionClose: JmsSession => Try[Unit] = beforeSessionCloseCallback
override def afterSessionClose: JmsSession => Try[Unit] = afterSessionCloseCallback
override def onError: Throwable => Unit = handleError
}
case None =>
throw new IllegalStateException(s"No connection available ... no session manager created")
}
}
private def withSessionMgr[T](f : JmsSessionManager => T) : Try[T] = Try {
sessionMgr match {
case Success(mgr) => f(mgr)
case Failure(t) => throw t
}
}
def getSession(id : String) : Option[JmsSession] = withSessionMgr[Option[JmsSession]]{ mgr =>
mgr.getSession(id).unwrap
} match {
case Success(v) => v
case Failure(t) =>
handleError(t)
None
}
def closeSession(id : String) : Unit = withSessionMgr[Unit]{ mgr =>
mgr.closeSession(id).unwrap
} match {
case Success(_) => ()
case Failure(t) =>
handleError(t)
()
}
def closeAll() : Unit = withSessionMgr[Unit]{ mgr =>
mgr.closeAll()
} match {
case Success(_) => ()
case Failure(t) =>
handleError(t)
()
}
def isOpen(id : String) : Boolean = withSessionMgr[Boolean] { mgr =>
mgr.isOpen(id)
} match {
case Success(b) => b
case Failure(t) =>
handleError(t)
false
}
}
|
name := "SlackCont"
version := "0.1"
organization := "com.github.yyu"
scalaVersion := "2.12.4"
scalacOptions := Seq("-unchecked", "-deprecation", "-feature", "-language:postfixOps")
scalapropsWithScalazlaws
scalapropsVersion := "0.5.5"
coverageExcludedPackages := ".*di;.*provider;.*main"
libraryDependencies ++= Seq(
"com.github.gilbertw1" %% "slack-scala-client" % "0.2.3",
"org.scalaz" %% "scalaz-core" % "7.2.24",
"com.google.inject" % "guice" % "4.2.0",
"com.typesafe" % "config" % "1.3.2",
"org.scalatest" %% "scalatest" % "3.0.5" % "test",
"org.mockito" % "mockito-core" % "2.18.3" % "test"
)
|
package com.jeroenreijn.examples.view;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
public final class UjormResolver extends AbstractTemplateViewResolver {
public UjormResolver() {
this.setViewClass(this.requiredViewClass());
}
@Override
protected Class<?> requiredViewClass() {
return UjormView.class;
}
}
|
<?php
/**
* 版权声明 : 地老天荒科技有限公司
* 文件名称 : couponlist_route_v1_api.php
* 创 建 者 : Shi Guang Yu
* 创建日期 : 2018/09/26 14:36
* 文件描述 : 景区优惠券管理路由文件
* 历史记录 : -----------------------
*/
/**
* 传值方式 : POST
* 路由功能 : 添加优惠券数据
*/
Route::post(
':v/couponlist_module/couponlist_route',
'couponlist_module/:v.controller.CouponlistController/couponlistPost'
)->middleware('Right_v1_IsAdmin');
/**
* 传值方式 : GET
* 路由功能 : 获取景区所有优惠券信息
*/
Route::get(
':v/couponlist_module/couponlist_route',
'couponlist_module/:v.controller.CouponlistController/couponlistGet'
)->middleware('Right_v1_IsAdmin');
/**
* 传值方式 : DELETE
* 路由功能 : 删除优惠券
*/
Route::delete(
':v/couponlist_module/couponlist_route',
'couponlist_module/:v.controller.CouponlistController/couponlistDelete'
)->middleware('Right_v1_IsAdmin');
|
<?php
namespace HashmatWaziri\LaravelMultiAuthImpersonate\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class LeaveImpersonation
{
use Dispatchable;
use InteractsWithSockets;
use SerializesModels;
/** @var Authenticatable */
public $impersonator;
/** @var Authenticatable */
public $impersonated;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Authenticatable $impersonator, Authenticatable $impersonated)
{
$this->impersonator = $impersonator;
$this->impersonated = $impersonated;
}
}
|
/*!
* client metatype registration.
*/
#include "client.h"
#include "types.h"
/*!
* \ingroup mptClient
* \brief client type
*
* Get or register client metatype.
*
* \return id for client metatype
*/
extern int mpt_client_typeid(void)
{
static int id = 0;
if (!id) {
id = mpt_type_meta_new("client");
}
return id;
}
|
module Data.JSON.LinkedData.Graph where
import Data.Aeson
import Data.Text as T
import Iri.Data
import Protolude
data Node =
IriNode !Iri
| BlankNode !BlankObject
| JsonLDValueNode !ValueObject
deriving (Eq, Generic, Show)
data BlankObject =
BlankObject
{ blankObjectId :: Text
, blankObjectValue :: Text
}
deriving (Eq, Generic, Show)
instance ToJSON BlankObject
instance FromJSON BlankObject
data ValueObject =
JsValue Value
| TypedValue Text
| LanguageTaggedString Text
deriving (Eq, Generic, Show)
mkBlankObject :: Text -> Text -> Either Text BlankObject
mkBlankObject "" _ = Left "blankObjectId must start with \"_\""
mkBlankObject id v =
if validBlankId id
then Right $ BlankObject id v
else Left $ id <> " is an invalid BlankObject id"
where
validBlankId x = T.head x == '_'
|
// Copyright (c) 2021, the MarchDev Toolkit project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/// Extensions for comparable `Iterable`
extension IterableComparableExtension<T extends Comparable> on Iterable<T> {
Iterable<T> get _sorted => this.toList()..sort();
/// Returns the element with minimum value.
///
/// If `this` is empty, [StateError] will be thrown.
T get min {
if (this.isEmpty) {
throw StateError('No element');
}
return _sorted.first;
}
/// Returns the element with maximum value.
///
/// If `this` is empty, [StateError] will be thrown.
T get max {
if (this.isEmpty) {
throw StateError('No element');
}
return _sorted.last;
}
/// Returns the element with minimum value.
///
/// If `this` is empty, the result of invoking is [null].
T? get minOrNull {
if (this.isEmpty) {
return null;
}
return _sorted.first;
}
/// Returns the element with maximum value.
///
/// If `this` is empty, the result of invoking is [null].
T? get maxOrNull {
if (this.isEmpty) {
return null;
}
return _sorted.last;
}
/// Returns the element with minimum value of filtered
/// collection by `test` predicate.
///
/// If `this` is empty, [StateError] will be thrown.
///
/// For more info about filtering refer to [Iterable.where].
T minWhere(bool test(T element)) => this.where(test).min;
/// Returns the element with maximum value of filtered
/// collection by `test` predicate.
///
/// If `this` is empty, [StateError] will be thrown.
///
/// For more info about filtering refer to [Iterable.where].
T maxWhere(bool test(T element)) => this.where(test).max;
/// Returns the element with minimum value of filtered
/// collection by `test` predicate.
///
/// If `this` is empty, the result of invoking is [null].
///
/// For more info about filtering refer to [Iterable.where].
T? minOrNullWhere(bool test(T element)) => this.where(test).minOrNull;
/// Returns the element with maximum value of filtered
/// collection by `test` predicate.
///
/// If `this` is empty, the result of invoking is [null].
///
/// For more info about filtering refer to [Iterable.where].
T? maxOrNullWhere(bool test(T element)) => this.where(test).maxOrNull;
}
|
import React, { forwardRef } from 'react';
import ScrollableContentWrapper from '../../components/ScrollableContentWrapper';
const ScrollerWithCustomProps = forwardRef(function ScrollerWithCustomProps(props, ref) {
return (
<ScrollableContentWrapper
{...props}
ref={ref}
renderView={({ style, ...props }) => <div {...props} style={{ ...style }} />}
renderTrackHorizontal={(props) => <div {...props} style={{ display: 'none' }} className='track-horizontal' />}
/>
);
});
export default ScrollerWithCustomProps;
|
namespace Clarity.App.Worlds.Interaction.Tools
{
public static class CommonChildPlaneSemantics
{
public const string Plane2D = "Plane2D";
public const string Plane3DVertical = "Plane3DVertical";
public const string Plane3DHorizontal = "Plane3DHorizontal";
}
}
|
// Copyright (c) 2015-2016, Tammo Beil - All rights reserved
#pragma once
#include "BRSSettingTypes.generated.h"
UENUM(BlueprintType)
namespace EBRSSoundClass
{
enum Type
{
Master,
Music,
SFX,
Voice,
UI,
VoIP,
//Should always be last (used for Size of array)
MAX UMETA(Hidden)
};
}
namespace FSoundClassHelpers
{
static FString SoundClassToString(EBRSSoundClass::Type SoundClass)
{
switch (SoundClass)
{
case EBRSSoundClass::Master:
return FString(TEXT("Master"));
case EBRSSoundClass::Music:
return FString(TEXT("Music"));
case EBRSSoundClass::SFX:
return FString(TEXT("SFX"));
case EBRSSoundClass::Voice:
return FString(TEXT("Voice"));
case EBRSSoundClass::UI:
return FString(TEXT("UI"));
case EBRSSoundClass::VoIP:
return FString(TEXT("VoIP"));
default:
break;
}
return FString("ERROR");
}
}
|
package com.cuneytayyildiz.android.consent.sdk.helper.callbacks
import com.google.ads.consent.ConsentInformation
import com.google.ads.consent.ConsentStatus
interface ConsentInformationCallback {
fun onResult(consentInformation: ConsentInformation, consentStatus: ConsentStatus?)
fun onFailed(consentInformation: ConsentInformation, reason: String?)
}
|
package de.pk.jblockchain.node.service;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.pk.jblockchain.common.SignatureUtils;
import de.pk.jblockchain.common.domain.Address;
import de.pk.jblockchain.common.domain.Node;
import de.pk.jblockchain.common.domain.Transaction;
import de.pk.jblockchain.node.service.smartContract.SmartContractService;
@Service
public class TransactionService {
@Value("${storage.path}")
private String storePath;
private final static Logger LOG = LoggerFactory.getLogger(TransactionService.class);
private final AddressService addressService;
@Autowired
SmartContractService smartContractService;
/**
* Pool of Transactions which are not included in a Block yet.
*/
private Set<Transaction> transactionPool = new HashSet<>();
@Autowired
public TransactionService(AddressService addressService) {
this.addressService = addressService;
}
public Set<Transaction> getTransactionPool() {
return transactionPool;
}
/**
* load initial values
*
* @param Set<Transaction>
*/
public void init(Set<Transaction> transactions) {
this.transactionPool = transactions;
}
/**
* save values
*
*/
public void save() throws IOException {
ObjectMapper mapper = new ObjectMapper();
FileOutputStream fStream = null;
GZIPOutputStream zStream = null;
try {
fStream = new FileOutputStream(System.getProperty("user.home") + this.storePath + "transaction.json.gz");
zStream = new GZIPOutputStream(new BufferedOutputStream(fStream));
mapper.writeValue(zStream, this.transactionPool);
} finally {
if (zStream != null) {
zStream.flush();
zStream.close();
}
if (fStream != null) {
fStream.flush();
fStream.close();
}
System.out.println("Transactions Saved!");
}
}
/**
* Add a new Transaction to the pool
*
* @param transaction
* Transaction to add
* @return true if verification succeeds and Transaction was added
*/
public synchronized boolean add(Transaction transaction) {
if (verify(transaction)) {
transactionPool.add(transaction);
try {
this.save();
} catch (IOException e) {
System.out.println("Unable to save transactions: " + e.getMessage());
}
return true;
}
return false;
}
/**
* Remove Transaction from pool
*
* @param transaction
* Transaction to remove
*/
public void remove(Transaction transaction) {
transactionPool.remove(transaction);
try {
this.save();
} catch (IOException e) {
System.out.println("Unable to save transactions: " + e.getMessage());
}
}
/**
* Does the pool contain all given Transactions?
*
* @param transactions
* Collection of Transactions to check
* @return true if all Transactions are member of the pool
*/
public boolean containsAll(Collection<Transaction> transactions) {
return transactionPool.containsAll(transactions);
}
private boolean verify(Transaction transaction) {
// correct signature
Address sender = addressService.getByHash(transaction.getSenderHash());
if (sender == null) {
LOG.warn("Unknown address " + Base64.encodeBase64String(transaction.getSenderHash()));
return false;
}
if (!smartContractService.validateContract(transaction.getText())) {
LOG.warn("Invalid message: no contract found for " + transaction.getText());
return false;
}
try {
if (!SignatureUtils.verify(transaction.getSignableData(), transaction.getSignature(),
sender.getPublicKey())) {
LOG.warn("Invalid signature");
return false;
}
} catch (Exception e) {
LOG.error("Error while verification", e);
return false;
}
// correct hash
if (!Arrays.equals(transaction.getHash(), transaction.calculateHash())) {
LOG.warn("Invalid hash");
return false;
}
return true;
}
/**
* Download Transactions from other Node and them to the pool
*
* @param node
* Node to query
* @param restTemplate
* RestTemplate to use
*/
public void retrieveTransactions(Node node, RestTemplate restTemplate) {
Transaction[] transactions = restTemplate.getForObject(node.getAddress() + "/transaction", Transaction[].class);
Collections.addAll(transactionPool, transactions);
LOG.info("Retrieved " + transactions.length + " transactions from node " + node.getAddress());
}
}
|
3.0.5 (unreleased)
------------------
- Nothing changed yet.
3.0.4 (2019-03-17)
------------------
- Fix : breaking change with dash 0.38.* and later. back to 0.37
3.0.3 (2019-03-06)
------------------
- DD-200 : display error message when exception occures in db.retrieve_table
3.0.2 (2019-02-19)
------------------
- fix twine upload
- LICENSE Apache 2
3.0.1 (2019-02-15)
------------------
- fix the missing link_ddui_to_airflow script in the package distribution
- add coverage and unit test reports to jenkins
- make testing with the webserver easier
- fix bug : update of the task's output not working at first, when there is no user action to force reload a dag
- serve dash js libs remotely
- fix Datadriver's UI CSS to remove != alignment
3.0.0 (2019-02-08)
------------------
- Support Python 3.6
- Support Airflow 1.10.*
- Integration of plotly.Dash
- New UI with rich visualisations of output tables
- Support of any datadriver's DB like object
2.3.4 (2018-09-05)
------------------
|
# README
Smooks mediator can be used to handle many conversion scenarios and this particular artifact converts a EDI file to XML. Then transforms the XML to match what is expected from the backend. Afterwards iterates and sends requests to the backend service.
> Note: This particular sample is tested with WSO2 ESB 5.0.0 M2 and WSO2 AS 530
### Contents
- Smooks configuration file : smooks-config.xml
- Proxy service: Smooks3.xml
- EDI file: edidata.edi
- EDI to xml mapping file: edimapping.xml
- XSLT transformation file: Transformation.xsl
- Axis2 service file
### Preconditions
- VFS transport should be enabled in ESB
- Local folder locations should be created as in, out and fail
- Upload the .aar file to WSO2 AS
### Steps
- Upload the given smooks configuration file to governance registry
- Upload the given XSLT transformation file to governance registry
- Place the EDI to XML mapping file inside <product_home>/repository/samples/resources/smooks folder
- Change the IP address of the given endpoints in the proxy service
- Deploy the given proxy service in ESB by appropriatly changing following vfs parameters to reflect the in, out and fail locations
```sh
parameter name="transport.vfs.FileURI
parameter name="transport.vfs.MoveAfterFailure
parameter name="transport.vfs.MoveAfterProcess
```
- Place the given edi file in the folder defined by "transport.vfs.FileURI" parameter
|
# -*- coding: utf-8 -*-
"""The LinkedIn subjects' subjects' searching module."""
import os
from linkedin_api import Linkedin as LinkedinAPI
class LinkedinSearch:
"""
The class to search for subjects and put them into `found` and `potential` categories.
"""
def __init__(self, user_input):
self.first_name = user_input["first_name"]
self.last_name = user_input["last_name"]
self.keyword_company = user_input["company"]
self.keyword_school = user_input["school"]
self.keyword_title = user_input["job_title"]
self._api = None
self._found_subjects = []
self._potential_subjects = []
def linkedin_search(self):
"""
Call other methods to search for subjects and put them into appropriate categories.
"""
self.__linkedin_authenticate()
self.__linkedin_search_for_subjects()
def __linkedin_authenticate(self):
"""Authenticate using LinkedIn login and password."""
self._api = LinkedinAPI(os.getenv("LINKEDIN_LOGIN"), os.getenv("LINKEDIN_PASSWORD"))
def __linkedin_search_for_subjects(self):
"""
Search for a subject in an ideal case or, if not found, find potential candidates.
"""
self.__linkedin_search_in_ideal_case()
if not self._found_subjects:
self.__linkedin_search_for_potential_candidate()
def __linkedin_search_in_ideal_case(self):
"""
Search for a subject in an ideal case if provided all necessary information.
"""
if self.keyword_company and self.keyword_school and self.keyword_title:
self._found_subjects = self._api.search_people(
keyword_first_name=self.first_name,
keyword_last_name=self.last_name,
keyword_company=self.keyword_company,
keyword_school=self.keyword_school,
keyword_title=self.keyword_title,
)
def __linkedin_search_for_potential_candidate(self):
"""
Search for potential candidates with any provided information.
"""
for i in range(3):
try:
results = self._api.search_people(
keyword_first_name=self.first_name,
keyword_last_name=self.last_name,
keyword_company=None
if i != 0
else self.keyword_company
if self.keyword_company
else 1 / 0,
keyword_school=None
if i != 1
else self.keyword_school
if self.keyword_school
else 1 / 0,
keyword_title=None
if i != 2
else self.keyword_title
if self.keyword_title
else 1 / 0,
)
except ZeroDivisionError:
continue
self._potential_subjects.extend(results)
|
package rere.sasl.gs2
sealed trait ChannelBindingFlag
object ChannelBindingFlag {
final case class SupportsAndUsed(channelBindingName: String) extends ChannelBindingFlag
case object NotSupports extends ChannelBindingFlag
case object SupportsButNotUsed extends ChannelBindingFlag
}
|
const DOT_RE = /\/\.\//g;
const DOUBLE_DOT_RE = /\/[^/]+\/\.\.\//;
const MULTI_SLASH_RE = /([^:/])\/+\//g;
function dirname(path) {
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) return '//';
return path.slice(0, end);
}
function resolve(from, to) {
if (to.indexOf('/') == 0) return to;
if (!from) return to;
let path = dirname(from) + '/' + to;
// https://github.com/seajs/seajs/blob/master/src/util-path.js
// /a/b/./c/./d ==> /a/b/c/d
path = path.replace(DOT_RE, '/');
/*
@author wh1100717
a//b/c ==> a/b/c
a///b/////c ==> a/b/c
DOUBLE_DOT_RE matches a/b/c//../d path correctly only if replace // with / first
*/
path = path.replace(MULTI_SLASH_RE, '$1/');
// a/b/c/../../d ==> a/b/../d ==> a/d
while (path.match(DOUBLE_DOT_RE)) {
path = path.replace(DOUBLE_DOT_RE, '/');
}
return path;
}
exports.resolve = resolve;
|
import * as React from "react";
import { Helmet } from "react-helmet";
import { useParams, Redirect } from "react-router-dom";
import { isValidAccountAddress } from "components/utils";
import Participants from "./Participants";
import type { PageParams } from "types/page";
const TreasureHunt: React.FC = () => {
const { account = "" } = useParams<PageParams>();
return account && !isValidAccountAddress(account) ? (
<Redirect to="/treasure-hunt" />
) : (
<>
<Helmet>
{isValidAccountAddress(account) ? (
<title>Treasure Hunt {account}</title>
) : (
<title>Nano Treasure Hunt Participants</title>
)}
</Helmet>
<Participants />
</>
);
};
export default TreasureHunt;
|
# Hello World
The purpose of this sample is for the client to send commands which contain a single message typed in the console.
If the user sends the same message twice a business exception is thrown.
|
#!/bin/bash
# Replace these three settings.
PROJDIR="/home/filemanager"
PIDFILE="$PROJDIR/filemanager.pid"
SOCKET="$PROJDIR/filemanager.sock"
cd $PROJDIR
if [ -f $PIDFILE ]; then
kill `cat -- $PIDFILE`
rm -f -- $PIDFILE
fi
/usr/bin/env - \
PYTHONPATH="../python:.." \
./manage.py runfcgi --settings=filemanager.settings socket=$SOCKET pidfile=$PIDFILE workdir=$PROJDIR
chmod a+w $SOCKET
|
# frozen_string_literal: true
shared_examples 'uses error_pages' do
context do
it do
controller_file_test
routes_file_test
end
def controller_file_test # rubocop:disable Metrics/AbcSize
application_controller_file = content('app/controllers/application_controller.rb')
expect(application_controller_file).to match('rescue_from Exception')
expect(application_controller_file).to match('rescue_from ActiveRecord::RecordNotFound')
expect(application_controller_file).to match('rescue_from ActionController::RoutingError')
expect(application_controller_file).to match('server_error')
expect(application_controller_file).to match('page_not_found')
end
def routes_file_test
route_file = content('config/routes.rb')
expect(route_file).to match('unmatched_route')
end
end
end
|
---
title: test
undefined: 'Description '
created_date: 2018-01-16 18:30:00 +0000
date: 2018-09-01 21:10:45 +0530
---
test
|
module Color where
data Color = Red |
Yellow |
Blue |
Green |
Purple |
Orange |
Brown deriving(Eq, Show)
instance Semigroup Color where
(<>) Red Blue = Purple
(<>) Blue Red = Purple
(<>) Yellow Blue = Green
(<>) Blue Yellow = Green
(<>) Yellow Red = Orange
(<>) Red Yellow = Orange
(<>) a b = if a == b
then a
else Brown
mix :: Color -> Color -> Color
mix color1 color2 =
color1 <> color2
--guard
{--
instance Semigroup Color where
(<>) a b | a == b = a
| all (`elem` [Red,Blue,Purple]) [a,b] = Purple
| all (`elem` [Blue,Yellow,Green]) [a,b] = Green
| all (`elem` [Red,Yellow,Orange]) [a,b] = Orange
| otherwise = Brown
--}
|
/*
@author Achmad Baihaqi / 01 / XII RPL-1
*/
---- Pratikum soal no 1
SELECT m.kode_dos, m.nama_mk
FROM matakuliah m
WHERE m.kode_dos
IN (
SELECT kode_dos
FROM jurusan
WHERE kode_dos = 10
);
----> Copyright © 2020. Achmad Baihaqi.
|
// Package svg provides common SVG elements and attributes.
// See https://developer.mozilla.org/en-US/docs/Web/SVG/Element for an overview.
package svg
import (
g "github.com/maragudk/gomponents"
)
func Path(children ...g.Node) g.Node {
return g.El("path", children...)
}
func SVG(children ...g.Node) g.Node {
return g.El("svg", g.Attr("xmlns", "http://www.w3.org/2000/svg"), g.Group(children))
}
|
import fs from 'fs';
import { buildClientSchema, graphqlSync, introspectionQuery } from 'graphql';
import { generate } from 'graphql-code-generator';
import { TypeScriptNamingConventionMap } from 'graphql-codegen-typescript-common';
import { mergeSchemas } from 'graphql-tools';
import path from 'path';
import { ADMIN_API_PATH, API_PORT, SHOP_API_PATH } from '../../packages/common/src/shared-constants';
import { downloadIntrospectionSchema } from './download-introspection-schema';
const CLIENT_QUERY_FILES = path.join(__dirname, '../../admin-ui/src/app/data/definitions/**/*.ts');
const ADMIN_SCHEMA_OUTPUT_FILE = path.join(__dirname, '../../schema-admin.json');
const SHOP_SCHEMA_OUTPUT_FILE = path.join(__dirname, '../../schema-shop.json');
// tslint:disable:no-console
Promise.all([
downloadIntrospectionSchema(ADMIN_API_PATH, ADMIN_SCHEMA_OUTPUT_FILE),
downloadIntrospectionSchema(SHOP_API_PATH, SHOP_SCHEMA_OUTPUT_FILE),
])
.then(([adminSchemaSuccess, shopSchemaSuccess]) => {
if (!adminSchemaSuccess || !shopSchemaSuccess) {
console.log('Attempting to generate types from existing schema json files...');
}
const adminSchemaJson = JSON.parse(fs.readFileSync(ADMIN_SCHEMA_OUTPUT_FILE, 'utf-8'));
const shopSchemaJson = JSON.parse(fs.readFileSync(SHOP_SCHEMA_OUTPUT_FILE, 'utf-8'));
const adminSchema = buildClientSchema(adminSchemaJson.data);
const shopSchema = buildClientSchema(shopSchemaJson.data);
const combinedSchemas = mergeSchemas({ schemas: [adminSchema, shopSchema]});
const combinedJson = graphqlSync(combinedSchemas, introspectionQuery).data;
fs.writeFileSync(path.join(__dirname, '../../schema.json'), JSON.stringify(combinedJson, null, 2));
const namingConventionConfig = {
namingConvention: {
enumValues: 'keep',
} as TypeScriptNamingConventionMap,
};
return generate({
overwrite: true,
generates: {
[path.join(__dirname, '../../packages/common/src/generated-types.ts')]: {
schema: [ADMIN_SCHEMA_OUTPUT_FILE, path.join(__dirname, 'client-schema.ts')],
documents: CLIENT_QUERY_FILES,
plugins: [
{ add: '// tslint:disable' },
'time',
'typescript-common',
'typescript-client',
'typescript-server'],
config: namingConventionConfig,
},
[path.join(__dirname, '../../packages/common/src/generated-shop-types.ts')]: {
schema: [SHOP_SCHEMA_OUTPUT_FILE],
plugins: [
{ add: '// tslint:disable' },
'time',
'typescript-common',
'typescript-server'],
config: namingConventionConfig,
},
},
});
})
.then(
result => {
process.exit(0);
},
err => {
console.error(err);
process.exit(1);
},
);
|
export type { IriTemplateEx } from './IriTemplateEx'
export { IriTemplateExMixin } from './IriTemplateEx'
|
class Render < ActiveRecord::Base
attr_accessible :filename, :output, :job_id, :console_log
belongs_to :job
belongs_to :user
mount_uploader :output, RenderFileUploader
end
|
using UnityEngine;
namespace Janovrom.Firesimulation.Runtime.Variables
{
[CreateAssetMenu(fileName ="NewFloat", menuName ="FireSimulation/New Float")]
public sealed class FloatVariable : Variable<float>
{
}
}
|
/**
* Données
*/
let photos = document.querySelectorAll('.photo-list li')
let counter = document.querySelector('em');
let btnValidate = document.querySelector('#btnValidate');
let affichage = document.querySelector('#affichage');
/**
* Fonctions
*/
function onClickSelectPhoto()
{
this.classList.toggle('selected');
// Tous les éléments séléctionnés
let selectedPhotos = document.querySelectorAll('.selected');
counter.innerHTML = selectedPhotos.length;
}
function onClickValidatePhotos()
{
affichage.innerHTML = '';
let selectedPhotos = document.querySelectorAll('.selected');
let newPhoto = "";
for (let i=0; i<selectedPhotos.length; i++) {
newPhoto = document.createElement('img');
newPhoto.src = selectedPhotos[i].firstChild.src;
affichage.appendChild(newPhoto);
}
}
/**
* Code Principal
*/
for (let i=0; i<photos.length; i++)
{
photos[i].addEventListener('click', onClickSelectPhoto)
}
btnValidate.addEventListener('click', onClickValidatePhotos)
|
# portfolio-template
SImple Portfolio Template. Completley buit with HTML,CSS and JAVASCRIPT
# Demo
codeezzi-portfolio.surge.sh
|
[CmdletBinding()]
param ()
$pesterTestPath = Join-Path (Join-Path $PSScriptRoot "..") "test"
$pesterTestPath = Join-Path $pesterTestPath "*"
$dtNow = [datetime]::UtcNow
$dateString = $dtNow.ToString("yyyy'-'MM'-'dd")
$timeString = $dtNow.ToString("HH'-'mm'-'ss")
$outputFileName = "TEST-date-$dateString-utc-$timeString.xml"
$outputDirectory = Join-Path (Join-Path $PSScriptRoot "..") "TestResult"
if (-not (Test-Path $outputDirectory)) {
New-Item -ItemType Directory $outputDirectory | Out-Null
}
$outputFilePath = Join-Path $outputDirectory $outputFileName
Import-Module Pester -Verbose:$false
$pesterModule = Get-Module Pester
if ($pesterModule.Version -lt [version]::Parse("4.0")) {
Install-Module -Name Pester -Force -SkipPublisherCheck -Scope CurrentUser
Import-Module Pester -Force -Verbose:$false
}
Invoke-Pester -Script $pesterTestPath -EnableExit -OutputFormat NUnitXml `
-OutputFile $outputFilePath
|
require 'logger'
require 'rack'
require 'rack/mount'
require 'rack/builder'
require 'rack/accept'
require 'rack/auth/basic'
require 'rack/auth/digest/md5'
require 'hashie'
require 'set'
require 'active_support/version'
require 'active_support/core_ext/hash/indifferent_access'
if ActiveSupport::VERSION::MAJOR >= 4
require 'active_support/core_ext/object/deep_dup'
else
require_relative 'backports/active_support/deep_dup'
end
require 'active_support/ordered_hash'
require 'active_support/core_ext/object/conversions'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/hash/deep_merge'
require 'grape/util/content_types'
require 'multi_json'
require 'multi_xml'
require 'virtus'
require 'i18n'
require 'thread'
I18n.load_path << File.expand_path('../grape/locale/en.yml', __FILE__)
module Grape
module Http
require 'grape/http/headers'
end
module Presenters
require 'grape/presenters/presenter'
end
module Exceptions
require 'grape/exceptions/base'
require 'grape/exceptions/validation'
require 'grape/exceptions/validation_errors'
require 'grape/exceptions/missing_vendor_option'
require 'grape/exceptions/missing_mime_type'
require 'grape/exceptions/missing_option'
require 'grape/exceptions/invalid_formatter'
require 'grape/exceptions/invalid_versioner_option'
require 'grape/exceptions/unknown_validator'
require 'grape/exceptions/unknown_options'
require 'grape/exceptions/invalid_with_option_for_represent'
require 'grape/exceptions/incompatible_option_values'
require 'grape/exceptions/missing_group_type'
require 'grape/exceptions/unsupported_group_type'
require 'grape/exceptions/invalid_message_body'
require 'grape/exceptions/invalid_accept_header'
end
module Formatter
require 'grape/formatter/json'
require 'grape/formatter/serializable_hash'
require 'grape/formatter/txt'
require 'grape/formatter/xml'
require 'grape/formatter/base'
end
module ErrorFormatter
require 'grape/error_formatter/json'
require 'grape/error_formatter/txt'
require 'grape/error_formatter/xml'
require 'grape/error_formatter/base'
end
module Parser
require 'grape/parser/json'
require 'grape/parser/xml'
require 'grape/parser/base'
end
module Middleware
require 'grape/middleware/base'
require 'grape/middleware/versioner'
require 'grape/middleware/formatter'
require 'grape/middleware/error'
module Auth
require 'grape/middleware/auth/base'
require 'grape/middleware/auth/dsl'
require 'grape/middleware/auth/strategy_info'
require 'grape/middleware/auth/strategies'
end
module Versioner
require 'grape/middleware/versioner/path'
require 'grape/middleware/versioner/header'
require 'grape/middleware/versioner/param'
require 'grape/middleware/versioner/accept_version_header'
end
end
module Util
require 'grape/util/inheritable_values'
require 'grape/util/stackable_values'
require 'grape/util/inheritable_setting'
require 'grape/util/strict_hash_configuration'
end
module DSL
require 'grape/dsl/settings'
require 'grape/dsl/configuration'
require 'grape/dsl/callbacks'
require 'grape/dsl/inside_route'
require 'grape/dsl/helpers'
require 'grape/dsl/middleware'
require 'grape/dsl/parameters'
require 'grape/dsl/request_response'
require 'grape/dsl/routing'
require 'grape/dsl/validations'
require 'grape/dsl/api'
end
class API
require 'grape/api/helpers'
end
require 'grape/api'
require 'grape/endpoint'
require 'grape/route'
require 'grape/namespace'
require 'grape/path'
require 'grape/cookies'
require 'grape/validations'
require 'grape/http/request'
end
require 'grape/validations/validators/base'
require 'grape/validations/attributes_iterator'
require 'grape/validations/validators/allow_blank'
require 'grape/validations/validators/at_least_one_of'
require 'grape/validations/validators/coerce'
require 'grape/validations/validators/default'
require 'grape/validations/validators/exactly_one_of'
require 'grape/validations/validators/mutual_exclusion'
require 'grape/validations/validators/presence'
require 'grape/validations/validators/regexp'
require 'grape/validations/validators/values'
require 'grape/validations/params_scope'
require 'grape/validations/validators/all_or_none'
require 'grape/version'
|
# Case conversion
This package contains a single function, copied from the
`github.com/golang/protobuf/protoc-gen-go/generator` package. That
modules LICENSE is referenced in its entirety in this package.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.