text
stringlengths 27
775k
|
|---|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using Azure.Analytics.Synapse.Spark.Models;
namespace Microsoft.Azure.Commands.Synapse.Models
{
public class PSSparkServicePluginInformation
{
public PSSparkServicePluginInformation(SparkServicePlugin pluginInfo)
{
this.PreparationStartedAt = pluginInfo?.PreparationStartedAt;
this.ResourceAcquisitionStartedAt = pluginInfo?.ResourceAcquisitionStartedAt;
this.SubmissionStartedAt = pluginInfo?.SubmissionStartedAt;
this.MonitoringStartedAt = pluginInfo?.MonitoringStartedAt;
this.CleanupStartedAt = pluginInfo?.CleanupStartedAt;
this.CurrentState = pluginInfo?.CurrentState;
}
/// <summary>
/// </summary>
public System.DateTimeOffset? PreparationStartedAt { get; set; }
/// <summary>
/// </summary>
public System.DateTimeOffset? ResourceAcquisitionStartedAt { get; set; }
/// <summary>
/// </summary>
public System.DateTimeOffset? SubmissionStartedAt { get; set; }
/// <summary>
/// </summary>
public System.DateTimeOffset? MonitoringStartedAt { get; set; }
/// <summary>
/// </summary>
public System.DateTimeOffset? CleanupStartedAt { get; set; }
/// <summary>
/// Gets or sets possible values include: 'Preparation',
/// 'ResourceAcquisition', 'Queued', 'Submission', 'Monitoring',
/// 'Cleanup', 'Ended'
/// </summary>
public PluginCurrentState? CurrentState { get; set; }
}
}
|
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:meteor_ui/src/components/color/color.dart';
@immutable
abstract class UIThemeDataInterface with Diagnosticable {
String get fontFamily;
double get baseFontSize;
UIColorScheme get colors;
const UIThemeDataInterface();
}
|
namespace ChampionsLeague
{
public class TeamScore
{
private string teamName;
private int teamOnSoilGoals;
private int teamAwaySoilGoals;
public TeamScore(string teamName)
{
this.teamName = teamName;
}
public string TeamName
{
get { return this.teamName; }
}
public int TeamOnSoilGoals
{
get { return this.teamOnSoilGoals; }
set { this.teamOnSoilGoals = value; }
}
public int TeamAwaySoilGoals
{
get { return this.teamAwaySoilGoals; }
set { this.teamAwaySoilGoals = value; }
}
public int TotalGoals
{
get { return (this.teamOnSoilGoals + this.teamAwaySoilGoals); }
}
}
}
|
import { Socket } from "socket.io"
import ErrorHandler from "@uno-game/error-handler"
import GameService from "@/Services/GameService"
import ChatService from "@/Services/ChatService"
import PlayerService from "@/Services/PlayerService"
import ClientService from "@/Services/ClientService"
import CryptUtil from "@/Utils/CryptUtil"
import { CardColors, Player, PlayerStatus } from "@uno-game/protocols"
/**
* Usually the class which handles events from client
*/
class ListenerService {
clients: Map<string, Socket> = new Map()
onConnection (client: Socket) {
try {
const playerData = {} as Player
client.emit("PlayerConnected", client.id)
client.on("SetPlayerData", (playerId: string, playerName: string) => {
playerData.id = playerId
playerData.name = playerName
ClientService.setClient(playerId, client)
this.onSetPlayerData(playerId, playerName)
client.emit("PlayerDataSet")
})
client.on("CreateGame", () => {
const gameId = CryptUtil.makeShortUUID()
const chatId = CryptUtil.makeShortUUID()
client.join(gameId)
client.join(chatId)
this.onCreateGame(gameId, playerData.id, chatId)
})
client.on("JoinGame", (gameId: string) => {
client.join(gameId)
const chatId = GameService.getChatIdByGameId(gameId)
if (chatId) {
client.join(chatId)
}
this.onJoinGame(gameId, playerData.id, chatId)
})
client.on("BuyCard", (gameId: string) => {
this.onBuyCard(gameId, playerData.id)
})
client.on(
"PutCard",
(gameId: string, cardIds: string[], selectedColor: CardColors) => {
this.onPutCard(gameId, playerData.id, cardIds, selectedColor)
},
)
client.on("SendChatMessage", (chatId: string, content: string) => {
this.onSendChatMessage(playerData.id, chatId, content)
})
client.on(
"ChangePlayerStatus",
(gameId: string, playerStatus: PlayerStatus) => {
this.onChangePlayerStatus(playerData.id, gameId, playerStatus)
},
)
client.on("ToggleReady", (gameId: string) => {
this.onToggleReady(gameId, playerData.id)
})
client.on("ForceSelfDisconnect", (gameId: string) => {
this.onPlayerDisconnect(playerData.id)
client.leave(gameId)
client.emit("SelfDisconnected")
})
client.on("disconnect", () => {
ClientService.destroyClient(playerData.id)
this.onPlayerDisconnect(playerData.id)
})
} catch (error) {
ErrorHandler.handle(error)
}
}
private onChangePlayerStatus (
playerId: string,
gameId: string,
playerStatus: PlayerStatus,
) {
const playerExists = PlayerService.playerExists(playerId)
const gameExists = GameService.gameExists(gameId)
if (playerExists && gameExists) {
GameService.changePlayerStatus(gameId, playerId, playerStatus)
}
}
private onSendChatMessage (playerId: string, chatId: string, content: string) {
const playerExists = PlayerService.playerExists(playerId)
const chatExists = ChatService.chatExists(chatId)
if (playerExists && chatExists) {
ChatService.pushMessage(playerId, chatId, content)
}
}
private onJoinGame (gameId: string, playerId: string, chatId: string) {
const gameExists = GameService.gameExists(gameId)
const chatExists = ChatService.chatExists(chatId)
if (gameExists) {
GameService.joinGame(gameId, playerId)
if (chatExists) {
ChatService.joinChat(chatId)
}
}
}
private onCreateGame (gameId: string, playerId: string, chatId: string) {
const playerExists = PlayerService.playerExists(playerId)
if (playerExists) {
GameService.setupGame(playerId, gameId, chatId)
ChatService.setupChat(playerId, chatId)
}
}
private onPlayerDisconnect (playerId: string) {
const playerExists = PlayerService.playerExists(playerId)
if (playerExists) {
GameService.purgePlayer(playerId)
}
}
private onBuyCard (gameId: string, playerId: string) {
const gameExists = GameService.gameExists(gameId)
const playerExists = PlayerService.playerExists(playerId)
if (gameExists && playerExists) {
GameService.buyCard(playerId, gameId)
}
}
private onPutCard (
gameId: string,
playerId: string,
cardIds: string[],
selectedColor: CardColors,
) {
const gameExists = GameService.gameExists(gameId)
const playerExists = PlayerService.playerExists(playerId)
if (gameExists && playerExists) {
GameService.putCard(playerId, cardIds, gameId, selectedColor)
}
}
private onToggleReady (gameId: string, playerId: string) {
const gameExists = GameService.gameExists(gameId)
const playerExists = PlayerService.playerExists(playerId)
if (gameExists && playerExists) {
GameService.toggleReady(playerId, gameId)
}
}
private onSetPlayerData (playerId: string, playerName: string) {
PlayerService.setPlayerData({
id: playerId,
name: playerName,
})
ClientService.dispatchGameHistoryConsolidated(playerId)
}
}
export default new ListenerService()
|
#!/bin/bash
# Run this script to auto-reload the documentation with changes to source files
# Requirements:
# The watchmedo utility must installed globally:
# Run `pipx install watchdog[watchmedo]` to install.
# The live-server utility must also be installed globally:
# Run `npm install -g live-server` to install.
# Ensure that the auto-build exits when the script exits
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
echo "Starting dev server"
# Watches package, docsrc, and README.md to build docs with Sphinx into a static HTML site
./autobuild.sh &
# Watches static site output and live reloads browser in response to it
live-server ../docs
|
require 'yaml'
require 'json'
require './constants'
gsi_style = JSON.parse($stdin.read)
style = <<-EOS
version: 8
center: #{CENTER}
zoom: #{ZOOM}
sprite: #{gsi_style['sprite']}
glyphs: #{gsi_style['glyphs']}
layers: []
EOS
style = YAML.load(style)
style['sources'] = gsi_style['sources']
gsi_style['layers'].each {|layer|
layer.delete('metadata')
style['layers'].insert(-1, layer)
}
print JSON.pretty_generate(style)
|
"""
Quadrotor{R}
A standard quadrotor model, with simple aerodynamic forces. The orientation is represent by
a general rotation `R`. The body z-axis point is vertical, so positive controls cause acceleration
in the positive z direction.
# Constructor
Quadrotor(; kwargs...)
Quadrotor{R}(; kwargs...)
where `R <: Rotation{3}` and defaults to `UnitQuaternion{Float64}` if omitted. The keyword arguments are
* `mass` - mass of the quadrotor, in kg (default = 0.5)
* `J` - inertia of the quadrotor, in kg⋅m² (default = `Diagonal([0.0023, 0.0023, 0.004])`)
* `gravity` - gravity vector, in kg/m² (default = [0,0,-9.81])
* `motor_dist` - distane between the motors, in m (default = 0.1750)
* `km` - motor torque constant (default = 0.0245)
* `kf` - motor force constant (default = 1.0)
"""
@autodiff struct Quadrotor{R} <: RigidBody{R}
mass::Float64
J::SMatrix{3,3,Float64,9}
Jinv::SMatrix{3,3,Float64,9}
gravity::SVector{3,Float64}
motor_dist::Float64
kf::Float64
km::Float64
bodyframe::Bool # velocity in body frame?
ned::Bool
end
control_dim(::Quadrotor) = 4
function Quadrotor{R}(;
mass=0.5,
J=Diagonal(@SVector [0.0023, 0.0023, 0.004]),
gravity=SVector(0,0,-9.81),
motor_dist=0.1750,
kf=1.0,
km=0.0245,
bodyframe=false,
ned=false,
) where R
@assert issymmetric(J)
Quadrotor{R}(mass,J,inv(J),gravity,motor_dist,kf,km,bodyframe,ned)
end
(::Type{Quadrotor})(;kwargs...) = Quadrotor{UnitQuaternion{Float64}}(;kwargs...)
@inline RobotDynamics.velocity_frame(model::Quadrotor) = model.bodyframe ? :body : :world
function trim_controls(model::Quadrotor)
@SVector fill(-model.gravity[3]*model.mass/4.0, size(model)[2])
end
function forces(model::Quadrotor, x, u)
q = orientation(model, x)
kf = model.kf
g = model.gravity
m = model.mass
w1 = u[1]
w2 = u[2]
w3 = u[3]
w4 = u[4]
F1 = max(0,kf*w1);
F2 = max(0,kf*w2);
F3 = max(0,kf*w3);
F4 = max(0,kf*w4);
F = @SVector [0., 0., F1+F2+F3+F4] #total rotor force in body frame
if model.ned
F = SA[0,0,-F[3]]
g = -g
end
f = m*g + q*F # forces in world frame
return f
end
function moments(model::Quadrotor, x, u)
kf, km = model.kf, model.km
L = model.motor_dist
w1 = u[1]
w2 = u[2]
w3 = u[3]
w4 = u[4]
F1 = max(0,kf*w1);
F2 = max(0,kf*w2);
F3 = max(0,kf*w3);
F4 = max(0,kf*w4);
M1 = km*w1;
M2 = km*w2;
M3 = km*w3;
M4 = km*w4;
tau = @SVector [L*(F2-F4), L*(F3-F1), (M1-M2+M3-M4)] #total rotor torque in body frame
if model.ned
tau = SA[tau[1], -tau[2], -tau[3]]
end
return tau
end
function wrenches(model::Quadrotor, x, u)
F = forces(model, x, u)
M = moments(model, x, u)
return [F; M]
q = orientation(model, x)
C = forceMatrix(model)
mass, g = model.mass, model.gravity
# Calculate force and moments
w = max.(u, 0) # keep forces positive
fM = forceMatrix(model)*w
f = fM[1]
M = @SVector [fM[2], fM[3], fM[4]]
e3 = @SVector [0,0,1]
F = mass*g - q*(f*e3)
return F,M
end
function forceMatrix(model::Quadrotor)
kf, km = model.kf, model.km
L = model.motor_dist
@SMatrix [
kf kf kf kf;
0 L*kf 0 -L*kf;
-L*kf 0 L*kf 0;
km -km km -km;
]
end
RobotDynamics.inertia(model::Quadrotor) = model.J
RobotDynamics.inertia_inv(model::Quadrotor) = model.Jinv
RobotDynamics.mass(model::Quadrotor) = model.mass
function Base.zeros(model::Quadrotor{R}) where R
x = RobotDynamics.build_state(model, zero(RBState))
u = @SVector fill(-model.mass*model.gravity[end]/4, 4)
return x,u
end
|
import { Injectable } from '@angular/core';
import { from, Observable, iif, of } from 'rxjs';
import localforage from 'localforage';
import AES from "crypto-js/aes";
import Utf8 from 'crypto-js/enc-utf8';
import { environment } from 'src/environments/environment';
import { map, mergeMap, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class CacheService {
// Init Cache
async init(): Promise<boolean> {
console.log('Configuring Cache', environment.cache);
// Configure local storage
return localforage.config(environment.cache);
}
// Store item
store(key: string, data: any, passphrase?: string): Observable<any> {
let ciphertext: string;
// If passphrase exists, encrypt data
if (passphrase) {
console.log('Store', JSON.stringify(data), '\nKey', passphrase);
ciphertext = AES.encrypt(JSON.stringify(data), passphrase).toString();
return from(localforage.setItem(key, ciphertext));
}
// If passphrase store encrypted text, else store JSON string
return from(localforage.setItem(key, data));
}
// Get item
get(key: string, passphrase?: string): Observable<any|void> {
console.log(`Retrieving ${key} from cache`);
return from(localforage.getItem(key)).pipe(
// Switch passphrase present
mergeMap((data: any) => !!passphrase
? of(null).pipe(
map(() => JSON.parse(
AES.decrypt(data, passphrase).toString(Utf8)
))
) : of(data)
),
catchError(err => {
console.warn(err);
return of(null);
})
);
}
// Delete item
delete(key: string): Observable<void> {
return from(localforage.removeItem(key));
}
// Clear cache
clear(): Observable<void> {
return from(localforage.clear());
}
}
|
# Peak Index in a Mountain Array
@ [Description](https://leetcode.com/problems/peak-index-in-a-mountain-array/)
@ Tags: Array, Binary Search
@ Easy
------------------
## Solution
改变二分法判断条件即可
```java
class Solution {
public int peakIndexInMountainArray(int[] A) {
int left = 0, right = A.length - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (A[mid] > A[mid - 1] && A[mid] > A[mid + 1])
return mid;
else {
if (A[mid] < A[mid + 1])
left = mid;
else
right = mid;
}
}
return (A[right] > A[left]) ? right : left;
}
}
```
|
package br.com.programadorthi.base.remote
import android.content.Context
import android.net.ConnectivityManager
import androidx.core.content.ContextCompat
class NetworkHandlerImpl(context: Context) : NetworkHandler {
private val service = ContextCompat.getSystemService(context, ConnectivityManager::class.java)
override fun hasInternetConnection(): Boolean =
service?.activeNetworkInfo?.isConnectedOrConnecting ?: false
}
|
import { Props as reactSelectProps } from 'react-select/lib/Select';
import React, { FC } from 'react';
import { FieldProps, Field } from 'formik';
import ReactSelect from 'react-select';
import { IFieldContainerProps, FieldContainer } from '../FieldContainer/FieldContainer';
type ISelectFieldProps = reactSelectProps<any> &
IFieldContainerProps & {
id?: string;
label?: string;
error?: any;
placeholder?: string;
tooltip?: string;
checked?: boolean;
hideErrorMessage?: boolean;
required?: boolean;
disabled?: boolean;
onChange?(params?: any): void;
onBlur?(params?: any): void;
onKeyUp?(params?: any): void;
};
export const SelectField: React.FC<ISelectFieldProps> = ({
name,
label,
tooltip,
required,
hideLabel,
options,
showMobileView,
...props
}) => (
<Field
name={name}
render={({
field,
form: { errors, touched, setFieldValue, setFieldTouched }
}: FieldProps) => (
<FieldContainer
label={label}
error={touched[field.name] && errors[field.name]}
id={`${field.name}_select_TID`}
tooltip={tooltip}
required={required}
showMobileView={showMobileView}
hideLabel={hideLabel}
>
<ReactSelect
inputId={`${field.name}_select_TID`}
error={touched[field.name] && errors[field.name]}
options={options}
name={field.name}
value={
options
? options.find((option: any) => option.value === field.value)
: ''
}
onBlur={() => setFieldTouched(field.name, true)}
onChange={(option) =>
setFieldValue(field.name, (option && option.value) || null)
}
classNamePrefix="react-select"
className="react-select"
{...props}
/>
</FieldContainer>
)}
/>
);
export const MultiSelectField: React.FC<ISelectFieldProps> = ({
name,
label,
tooltip,
required,
options,
hideLabel,
showMobileView,
...props
}) => (
<Field
name={name}
render={({
field,
form: { errors, touched, setFieldValue, setFieldTouched }
}: FieldProps) => (
<FieldContainer
label={label}
error={touched[field.name] && errors[field.name]}
id={`${field.name}_select_TID`}
tooltip={tooltip}
required={required}
showMobileView={showMobileView}
hideLabel={hideLabel}
>
<ReactSelect
inputId={`${field.name}_select_TID`}
error={touched[field.name] && errors[field.name]}
options={options}
name={field.name}
isMulti={true}
value={
options &&
options.filter((option) => field.value.includes(option.value))
}
onBlur={() => setFieldTouched(field.name, true)}
onChange={(option) => {
console.log(option);
setFieldValue(
field.name,
option.map((item: any) => item.value) || null
);
}}
classNamePrefix="react-select"
className="react-select"
{...props}
/>
</FieldContainer>
)}
/>
);
|
---
title: Create Folders
---
In the code view, folders can be created with the "Create folder" button.

To do so, a dialog will open where the new folder and a commit message have to be entered. It is possible, to create
multiple nested folders in one step.

In the new folder, a file named `.scmkeep` is created, because you cannot create empty folders in for example Git
or Mercurial. This file can be removed, as soon as there are other files in this folder.
|
<?php if (!defined('FW')) die('Forbidden');
class FW_Shortcode_Column extends FW_Shortcode
{
private $restricted_types = array( 'column' );
/**
* @internal
*/
public function _init()
{
add_action(
'fw_option_type_builder:page-builder:register_items',
array($this, '_action_register_builder_item_types')
);
add_filter( 'fw_ext:shortcodes:collect_shortcodes_data', array(
$this, '_filter_add_column_data'
) );
}
/**
* @internal
*/
public function _filter_add_column_data( $structure ) {
$data['column'] = $this->get_item_data();
return array_merge( $structure, $data );
}
private function get_shortcode_options() {
$shortcode_instance = fw()->extensions->get( 'shortcodes' )->get_shortcode( 'column' );
return $shortcode_instance->get_options();
}
private function get_shortcode_config() {
$shortcode_instance = fw_ext( 'shortcodes' )->get_shortcode( 'column' );
return $shortcode_instance->get_config( 'page_builder' );
}
/**
* Adds data about column to be pushed further to the frontend.
*
* @since 1.3.21
*/
public function get_item_data() {
$data = array(
'restrictedTypes' => $this->restricted_types,
);
$options = $this->get_shortcode_options();
if ( $options ) {
fw()->backend->enqueue_options_static( $options );
$data['options'] = $this->transform_options( $options );
}
$config = $this->get_shortcode_config();
if ( isset( $config['popup_size'] ) ) {
$data['popup_size'] = $config['popup_size'];
}
if (isset($config['popup_header_elements'])) {
$data['header_elements'] = $config['popup_header_elements'];
}
$data['item_widths'] = fw_ext_builder_get_item_widths_for_js('column');
$data['l10n'] = array(
'edit' => __( 'Edit', 'fw' ),
'duplicate' => __( 'Duplicate', 'fw' ),
'remove' => __( 'Remove', 'fw' ),
'collapse' => __( 'Collapse', 'fw' ),
'title' => __( 'Column', 'fw' ),
);
$data['tag'] = 'column';
if ($options) {
$data['default_values'] = fw_get_options_values_from_input(
$options, array()
);
}
return $data;
}
/*
* Puts each option into a separate array
* to keep it's order inside the modal dialog
*/
private function transform_options( $options ) {
$transformed_options = array();
foreach ( $options as $id => $option ) {
if ( is_int( $id ) ) {
/**
* this happens when in options array are loaded external options using fw()->theme->get_options()
* and the array looks like this
* array(
* 'hello' => array('type' => 'text'), // this has string key
* array('hi' => array('type' => 'text')) // this has int key
* )
*/
$transformed_options[] = $option;
} else {
$transformed_options[] = array( $id => $option );
}
}
return $transformed_options;
}
public function _action_register_builder_item_types() {
if (fw_ext('page-builder')) {
require $this->get_declared_path('/includes/page-builder-column-item/class-page-builder-column-item.php');
/**
* Note: A file is required from framework/extensions/shortcodes/includes/shortcode-template-components.php
* because the shortcodes don't have includes/ functionality
*/
}
}
}
|
fun JavaBaseClass.onJavaBaseClass() { }
fun JavaBaseClass?.onJavaBaseClassNullable() { }
fun JavaSubClass.onJavaSubClass() { }
fun JavaBaseInterface.onJavaBaseInterface() { }
fun JavaSubInterface.onJavaSubInterface() { }
fun JavaSubSubClass.onJavaSubSubClass() { }
fun JavaSubFromKotlin.onJavaSubFromKotlin() { }
fun KotlinBaseClass.onKotlinBaseClass() { }
fun KotlinBaseClass?.onKotlinBaseClassNullable() { }
fun KotlinSubClass.onKotlinSubClass() { }
fun KotlinBaseInterface.onKotlinBaseInterface() { }
fun KotlinSubInterface.onKotlinSubInterface() { }
fun KotlinSubSubClass.onKotlinSubSubClass() { }
fun KotlinSubFromJava.onKotlinSubFromJava() { }
internal fun JavaBaseClass.onJavaBaseClassInternal() { }
internal fun KotlinBaseClass.onKotlinBaseClassInternal() { }
private fun JavaBaseClass.onJavaBaseClassPrivate() { }
private fun KotlinBaseClass.onKotlinBaseClassPrivate() { }
fun JavaClass.onJavaClass() { }
fun KotlinClass.onKotlinClass() { }
fun Any.onAny() { }
fun Any?.onAnyNullable() { }
fun Turtles.onTurtles() { }
fun All.onAll() { }
fun The.onThe() { }
fun Way.onWay() { }
fun Down.onDown() { }
fun Ninja.onNinja() { }
fun Power.onPower() { }
fun <X: KotlinSubClass, T: X>T.onKotlinSubClassGenerics()
fun <X: JavaSubClass, T: X>T.onJavaSubClassGenerics()
fun JavaContainer<*>.onJavaContainerAll()
fun KotlinContainer<*>.onKotlinContainerAll()
|
extern crate test_generator;
use test_generator::test_resources;
use std::cell::RefCell;
use std::collections::HashSet;
use std::fs::{read_dir, File};
use std::io::prelude::*;
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::Command;
use preprocessor::PreprocessorOptions;
use purkka::core::{get_default_include_path, get_file_cb, get_file_content_cb};
use resolve::*;
fn parse(content: &str, filename: &str) -> ResolveResult {
let path = get_default_include_path();
let options = PreprocessorOptions {
include_path: path.iter().map(|x| x.as_ref()).collect(),
include_files: Vec::new(),
definitions: Vec::new(),
};
let cb = get_file_content_cb(&options);
let get_file_content = |req: &FileQuery| match req.requested_file.as_str() {
t if t == filename => (content.to_string(), req.requested_file.clone()),
_ => cb(req),
};
let options = PreprocessorOptions {
include_path: vec![],
include_files: vec![],
definitions: vec![],
};
let ctx = RefCell::new(None);
let res = get_file_cb(&options, &get_file_content, ctx)(FileQuery::new(
".",
filename,
true,
false,
HashSet::new(),
));
res
}
#[test_resources("src/purkka/tests/testcases/*.prk")]
fn run_test(filename: &str) {
let filename = filename.split("/").last().unwrap();
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push("tests/testcases");
let mut purkka_path = path.clone();
purkka_path.push(&filename);
let mut prk_contents = String::new();
let mut prk = File::open(&purkka_path).unwrap();
prk.read_to_string(&mut prk_contents).unwrap();
let prefix = filename.split(".prk").next().unwrap();
let mut c_path = path.clone();
c_path.push(&format!("{}.c", &prefix));
let mut c = File::open(&c_path).unwrap();
let mut c_contents = String::new();
c.read_to_string(&mut c_contents).unwrap();
let result = parse(&prk_contents, &purkka_path.to_str().unwrap());
assert_eq!(result.c_content, c_contents);
}
#[test]
fn check_result_files() {
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
d.push("tests/testcases");
let paths = read_dir(d).unwrap();
for path in paths {
let readable_path = path.unwrap().path().display().to_string();
if readable_path.ends_with(".c") {
let output = match Command::new("gcc")
.arg("-Wall")
.arg("-Wextra")
.arg("-Werror")
.arg("-Wno-unused-parameter")
.arg("-Wno-unused-variable")
.arg("-fopenmp")
.arg("-O2")
.arg("-o")
.arg("/dev/null")
.arg("-c")
.arg(readable_path)
.output()
{
Ok(ok) => ok,
Err(e) => {
if let io::ErrorKind::NotFound = e.kind() {
return;
}
panic!("Failed to compile a C test case: {:?}", e);
}
};
io::stdout().write_all(&output.stdout).unwrap();
io::stdout().write_all(&output.stderr).unwrap();
assert!(output.status.success());
}
}
}
|
'use strict';
const errors = {
200: 'Ok',
201: 'Created',
400: 'Bad request',
401: 'Unauthorised',
403: 'Forbidden',
404: 'Not found',
409: 'Conflict',
500: 'Server exception'
};
function response(res, status, message, data) {
message = message || (status in errors ? errors[status] : 'Undefined msg');
res.status(status).json({
error: (status < 200 || status > 299),
message: message,
data: data,
randomId: parseInt(Math.random() * 1000000000)
});
}
module.exports = response;
|
<?php
return [
'UserUnique' => 5000, //用户名已存在
'EmailUnique' => 5001, //用户邮箱已注册
'CreateFailure' => 5002, //创建失败
'VerificationCode' => 5003, //验证码错误
'GetUserFail' => 5004, //获取用户信息失败
'PasswordError' => 5005, //密码错误
'FrequentOperation' => 5006, //操作过于频繁,稍后再试
'SendFail' => 5007, //发送失败
'UpdateFailure' => 5008, //修改失败
'GetMsgFail' => 5009, //获取信息失败
'TokenFail' => 5010, //token验证失败 需重新登录
'authorization' => 5011, //授权失败
'LoginFailure' => 5012, //登录失败
'UpperLimit' => 5013, //已达上限
'DeleteFailure' => 5014, //删除失败
'Certified' => 5015, //已认证
'GetPinFail' => 5016, //未设置Pin码
'PinError' => 5017, //Pin错误
'GetFileFail' => 5018, //获取文件失败
'UploadFail' => 5019, //文件上传错误
'GetPromoFail' => 5020, //获取推广者信息失败
'Unbound' => 5021, //此手机号未绑定
'NotNull' => 5022, //不可为空
'NotBinDing' => 5023, //已绑定
'PhoneFail' => 5024, //手机验证失败
'RegisterClosed' => 5025, //注册窗口已关闭
'BindingFail' => 5026, //google 绑定失败
'GetVerify' => 5027, //获取验证码失败
'IllegalRegister' => 5028, //请填写邀请码
'Identical' => 5029, //请填写新手机号码
'Empty' => 5030, //账户不存在
'PayNameUnique' => 5031, //支付账号已存在
'CertificateFailure' => 5032, //身份证号已存在
'TwoVerification' => 6001, //需要验证
'ArticleEmpty' => 6002, //文章分类不存在
'ParamError' => 6003, //参数错误
'TicketFail' => 6004, //工单不存在
'PayFail' => 6005, //支付方式不存在
'PhoneNull' => 6006, //未绑定手机号
'IdentificationEmpty' => 6007, //未实名认证
'IdentificationStatus' => 6008, //实名认证未通过
'AccountNull' => 6009, //邮箱或手机号不能为空
'VerifyInvalid' => 6010, //验证码失效
'PhoneUnique' => 6011, //该手机号已注册
'EmailNull' => 6012, //请输入邮箱
'CountryNull' => 6013, //区号不能为空
'PhoneEmpty' => 6014, //请填写手机号
'UserNameUnique' => 6015, //用户名已存在
'SendVerify' => 6016, //请发送短信验证码
'SendEmailVerify' => 6017, //请发送邮箱验证码
'SmsValidate' => 6018, //请验证手机验证码
'NetworkAnomaly' => 6019, //网络异常
'UserNameError' => 6020, //用户名错误
'SafeValidate' => 6021, //请先进行安全验证
'Identification' => 6022, //请先进行高级认证
'IdentificationApply' => 6023, //高级认证审核中请耐心等待
'RealNameValidate' => 6024, //请先进行实名认证
'OtcAdvertiserUnique' => 6025, //您已是广告主
'OtcAdvertiserApply' => 6026, //您申请的广告主正在审核中,请耐心等待
'OtcAdvertiserFail' => 6027, //申请失败请重试
'OtcAdvertiserNull' => 6028, //请先申请成为广告主
'AddBlockFail' => 6029, //添加黑名单失败
'BlockUserUnique' => 6030, //黑名单中用户已存在
];
|
module Awspec::Helper
module Finder
module CloudwatchEvent
def find_cloudwatch_event(id)
cloudwatch_event_client.list_rules.rules.find do |rule|
rule.name == id || rule.arn == id
end
end
def select_all_cloudwatch_events
cloudwatch_event_client.list_rules.rules
end
end
end
end
|
from .augmenter import Augmenter
from .triplet_model import TripletModel
from .datagenerator import DataGenerator
from .triplet_loss import triplet_loss_metric
from .triplet_loss import triplet_loss_function
from .compute_fingerprint import compute_fingerprint
|
angular.module('mainMenuPrivacy').directive('mainMenuPrivacy', ['isyTranslateFactory',
function (isyTranslateFactory) {
return {
templateUrl: 'components/transclusions/mainMenuPanel/mainMenuPrivacy/mainMenuPrivacy.html',
restrict: 'A',
link: function (scope) {
scope.language = isyTranslateFactory.getCurrentLanguage();
}
};
}]);
|
using NeuralNetwork.Visualizer.Contracts.Drawing.Core.Primitives;
using System.Threading.Tasks;
namespace NeuralNetwork.Visualizer.Winform.Drawing.Controls
{
public interface IControlDrawing
{
Task RedrawAsync();
void Redraw();
Task<Image> GetImage();
}
}
|
import React, { createContext } from 'react';
export interface ConfirmData<T = string> {
title?: string;
body?: JSX.Element | string | false | null;
label?: string;
actionBody?: (close: () => void) => JSX.Element | false | null;
buttonText?: string;
buttonColor?: string;
isCentered?: boolean;
onlyAlert?: boolean;
onClick: (val: boolean) => Promise<void> | void;
doubleConfirm?: boolean;
textConfirm?: string;
// TODO: DO THIS PROPERLY
defaultState?: Partial<T>;
customBody?: React.FC<{
state: T;
setState: React.Dispatch<React.SetStateAction<T>>;
isFormValid: boolean;
setIsFormValid: React.Dispatch<React.SetStateAction<boolean>>;
}>;
}
export type PopupType = 'prompt' | 'confirm' | 'alert';
export interface ConfirmContextValue {
type: PopupType;
isOpen: boolean;
isLoading: boolean;
data?: ConfirmData;
}
export interface ConfirmContext {
setValue: React.Dispatch<React.SetStateAction<ConfirmContextValue>>;
value: ConfirmContextValue;
defaults: Partial<
Record<
'prompt' | 'confirm' | 'delete',
Pick<ConfirmData, 'title' | 'body' | 'buttonText' | 'buttonColor'>
>
> & { cancel: string };
}
export const defaultDefaults: ConfirmContext['defaults'] = {
prompt: {
title: 'Enter some data',
buttonText: 'Submit',
buttonColor: 'blue'
},
confirm: {
title: 'Are you sure?'
},
delete: {
title: 'Are you sure?',
body: 'Are you sure you want to delete this',
buttonText: 'Delete',
buttonColor: 'red'
},
cancel: 'Cancel'
};
export const confirmContext = createContext<ConfirmContext>({
value: { type: 'confirm', isOpen: false, isLoading: false },
setValue: () => {},
defaults: { ...defaultDefaults }
});
|
2020年11月08日01时数据
Status: 200
1.拜登
微博热度:3971975
2.特朗普
微博热度:2530942
3.胡杏儿辣目洋子OLAY S卡
微博热度:2344044
4.拜登率先获得270张选举人票
微博热度:1362828
5.马苏 这几年摊上一些乱七八糟的事
微博热度:821232
6.快乐大本营
微博热度:527021
7.郭敬明再给何昶希S卡
微博热度:504922
8.美国佛罗里达州发生枪击事件
微博热度:467731
9.微信视频号直播强行置顶朋友圈
微博热度:462577
10.王楚然好适合南湘
微博热度:460376
11.王俊凯易烊千玺卡点为王源庆生
微博热度:407482
12.演员请就位
微博热度:294250
13.演员请就位版小时代好像小品
微博热度:281622
14.脱毛后的猕猴桃
微博热度:251101
15.立冬的第一顿火锅
微博热度:188631
16.小虎我是一路被骂过来的
微博热度:157129
17.特朗普推特
微博热度:152486
18.杭州17岁女生获顶尖科学家大会颁奖
微博热度:144217
19.央视调查代餐市场
微博热度:143289
20.王鹤棣爆粗口愤怒离场
微博热度:142732
21.张大大对尔冬升说你要抱抱我
微博热度:140832
22.关灯看手机危害到底有多大
微博热度:140404
23.西游记的配音找到了
微博热度:138990
24.word是个神奇的东西
微博热度:138158
25.男子因错过站点殴打公交司机被刑拘
微博热度:137150
26.辣目洋子版顾里
微博热度:135811
27.黄奕刘雨昕微博互关
微博热度:135106
28.舞蹈风暴
微博热度:131038
29.抗美援朝烈士遗孀生前愿望
微博热度:130017
30.每天锻炼一小时的学生不足30%
微博热度:129709
31.李佳琦直播
微博热度:129687
32.顾耀东吃面吃哭了
微博热度:129368
33.刘诗诗蓝色星光纱裙
微博热度:119396
34.尖子生之间的恋爱
微博热度:100076
35.湖南师大自杀身亡女生家属发声
微博热度:81818
36.韩红 我身体很健康
微博热度:79732
37.美好的时光
微博热度:79237
38.叶璇说黄奕赢得不光荣
微博热度:74809
39.美国费城计票中心附近遭炸弹威胁
微博热度:71267
40.伦敦渣打银行永久实行弹性工作制
微博热度:71147
41.大熊猫为什么不能徒手摸
微博热度:67227
42.易烊千玺提名金鸡奖最佳男主角
微博热度:66533
43.黑龙江冬泳健儿冰上吃饺子
微博热度:66327
44.张雨绮是人间猕猴桃本人
微博热度:66223
45.广西崇左白头叶猴添新丁
微博热度:62482
46.原来柯基是这么下楼梯的
微博热度:61440
47.高中体育特长生训练间隙趴地学习
微博热度:59635
48.燕云台人名
微博热度:58907
49.张弛骨折
微博热度:49896
50.德州1份冷冻猪肉制品外包装核酸阳性
微博热度:49282
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'accommodation_unit_dto.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AccommodationUnitDto _$AccommodationUnitDtoFromJson(
Map<String, dynamic> json) =>
AccommodationUnitDto(
json['hostId'] as String,
json['city'] as String,
json['zip'] as String,
$enumDecodeNullable(_$VoivodeshipEnumMap, json['voivodeship']),
json['addressLine'] as String,
json['vacanciesTotal'] as int,
json['petsPresent'] as bool?,
json['petsAccepted'] as bool?,
json['disabledPeopleFriendly'] as bool?,
json['lgbtFriendly'] as bool?,
json['parkingPlaceAvailable'] as bool?,
json['ownerComments'] as String?,
json['easyAmbulanceAccess'] as bool?,
json['vacanciesFree'] as int?,
$enumDecodeNullable(_$VerificationStatusEnumMap, json['status']),
json['staffComments'] as String?,
json['guid'] as String?,
json['host'] == null
? null
: HostDto.fromJson(json['host'] as Map<String, dynamic>),
dateTimeFromString(json['createdAt'] as String?),
dateTimeFromString(json['updatedAt'] as String?),
json['systemComments'] as String?,
(json['guests'] as List<dynamic>?)?.map((e) => e as String).toList(),
);
Map<String, dynamic> _$AccommodationUnitDtoToJson(
AccommodationUnitDto instance) =>
<String, dynamic>{
'hostId': instance.hostId,
'city': instance.city,
'zip': instance.zip,
'voivodeship': _$VoivodeshipEnumMap[instance.voivodeship],
'addressLine': instance.addressLine,
'vacanciesTotal': instance.vacanciesTotal,
'petsPresent': instance.petsPresent,
'petsAccepted': instance.petsAccepted,
'disabledPeopleFriendly': instance.disabledPeopleFriendly,
'lgbtFriendly': instance.lgbtFriendly,
'parkingPlaceAvailable': instance.parkingPlaceAvailable,
'ownerComments': instance.ownerComments,
'easyAmbulanceAccess': instance.easyAmbulanceAccess,
'vacanciesFree': instance.vacanciesFree,
'status': _$VerificationStatusEnumMap[instance.status],
'staffComments': instance.staffComments,
'guid': instance.guid,
'host': instance.host,
'createdAt': nullableDateTimeToString(instance.createdAt),
'updatedAt': nullableDateTimeToString(instance.updatedAt),
'systemComments': instance.systemComments,
'guests': instance.guests,
};
const _$VoivodeshipEnumMap = {
Voivodeship.DOLNOSLASKIE: 'DOLNOŚLĄSKIE',
Voivodeship.KUJAWSKO_POMORSKIE: 'KUJAWSKO-POMORSKIE',
Voivodeship.LUBELSKIE: 'LUBELSKIE',
Voivodeship.LUBUSKIE: 'LUBUSKIE',
Voivodeship.LODZKIE: 'ŁÓDZKIE',
Voivodeship.MALOPOLSKIE: 'MAŁOPOLSKIE',
Voivodeship.MAZOWIECKIE: 'MAZOWIECKIE',
Voivodeship.OPOLSKIE: 'OPOLSKIE',
Voivodeship.PODKARPACKIE: 'PODKARPACKIE',
Voivodeship.PODLASKIE: 'PODLASKIE',
Voivodeship.POMORSKIE: 'POMORSKIE',
Voivodeship.SLASKIE: 'ŚLĄSKIE',
Voivodeship.SWIETOKRZYSKIE: 'ŚWIĘTOKRZYSKIE',
Voivodeship.WARMINSKO_MAZURSKIE: 'WARMIŃSKO-MAZURSKIE',
Voivodeship.WIELKOPOLSKIE: 'WIELKOPOLSKIE',
Voivodeship.ZACHODNIOPOMORSKIE: 'ZACHODNIOPOMORSKIE',
};
const _$VerificationStatusEnumMap = {
VerificationStatus.CREATED: 'CREATED',
VerificationStatus.VERIFIED: 'VERIFIED',
VerificationStatus.REJECTED: 'REJECTED',
};
|
<?php
//3dsfwefwef132131231sd.php
define("DIR", __DIR__);
$old_composer_md5 = ('composer.json');
exec("cd ../..",$out);
exec("git pull",$out);
if (!$out) {
$composer_md5 = md5_file('composer.json');
if ($old_composer_md5 !=$composer_md5) {
exec("composer update",$out);
}
}
|

---
⭐️ From [martins-rafael](https://github.com/martins-rafael)
|
package dev.prokop.crypto.bip32;
import dev.prokop.utils.HashUtils;
import dev.prokop.utils.HexUtils;
import java.util.Arrays;
public class Bip32MasterRawKey {
private static final byte[] BITCOIN_SEED = "Bitcoin seed".getBytes();
private final byte[] secretKey;
private final byte[] chainCode;
public static Bip32MasterRawKey fromSeed(byte[] seed) {
final byte[] i = HashUtils.hmacSha512(BITCOIN_SEED, seed);
final byte[] il = Arrays.copyOfRange(i, 0, 32);
final byte[] ir = Arrays.copyOfRange(i, 32, 64);
Arrays.fill(i, (byte) 0);
return new Bip32MasterRawKey(il, ir);
}
private Bip32MasterRawKey(byte[] secretKey, byte[] chainCode) {
this.secretKey = secretKey;
this.chainCode = chainCode;
}
public byte[] getChainCode() {
return chainCode;
}
public byte[] getSecretKey() {
return secretKey;
}
public void wipe() {
Arrays.fill(secretKey, (byte) 0);
Arrays.fill(chainCode, (byte) 0);
}
@Override
public String toString() {
return "Bip32MasterRawKey{" +
"secretKey=" + HexUtils.hex(secretKey) +
", chainCode=" + HexUtils.hex(chainCode) +
'}';
}
}
|
//
// BNJSUserDefaultsHelper.h
// CompSDK
//
// Created by Fakai Zhao on 15/9/21.
// Copyright (c) 2015年 Baidu. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef enum {
// 预留值
BNJSUserDefaultsKeyNone = 100,
/************************************************************
v5.0.0 Added.... DO NOT MODIFY IT !!!!!!!!!!!!!!!!!!
v5.0.0 正在使用...已经发布.... 请勿修改 !!!!!!!!!!!!!
************************************************************/
// 用户选择城市
BNJSUserDefaultsKeyCurrentCity,
// 选择城市历史记录
BNJSUserDefaultsKeySelectedCityHistory,
// 搜索历史记录
BNJSUserDefaultsKeyQueryKeywordHistory,
// 筛选配置更新时间
BNJSUserDefaultsKeySearchFilterConfigLastUpdateTime,
// 城市列表更新时间
// BNJSUserDefaultsKeyQueryKeywordHistory,
/************************************************************
v5.1.0 Added.... DO NOT MODIFY IT !!!!!!!!!!!!!!!!!!
v5.1.0 正在使用...已经发布.... 请勿修改 !!!!!!!!!!!!!
************************************************************/
// 用户定位信息 包含经纬度 城市id 地址
BNJSUserDefaultsKeyLastUserLocationInfo,
/************************************************************
v5.7.0 Added.... DO NOT MODIFY IT !!!!!!!!!!!!!!!!!!
v5.7.0 正在使用...已经发布.... 请勿修改 !!!!!!!!!!!!!
************************************************************/
// Banner取消关闭按钮点击时间
BNJSUserDefaultsKeyHomeBannerCloseTime,
/************************************************************
v5.8.0 Added.... DO NOT MODIFY IT !!!!!!!!!!!!!!!!!!
v5.8.0 正在使用...已经发布.... 请勿修改 !!!!!!!!!!!!!
************************************************************/
// 服务端返回Copid过期时间
BNJSUserDefaultsKeyCopidCookieExpires,
BNJSUserDefaultsKeySearchFilterVersionMD5,
/************************************************************
v5.12.0 Added.... DO NOT MODIFY IT !!!!!!!!!!!!!!!!!!
v5.12.0 正在使用...已经发布.... 请勿修改 !!!!!!!!!!!!!
************************************************************/
// 是否展示过“自动选择最优优惠和抵用券方案”
BNJSUserDefaultsKeyHasTipAutoChooseActivityAndVoucher,
/************************************************************
v5.13.2 Added.... DO NOT MODIFY IT !!!!!!!!!!!!!!!!!!
v5.13.2 正在使用...已经发布.... 请勿修改 !!!!!!!!!!!!!
************************************************************/
// 上次定位时间
BNJSUserDefaultsKeyLastLocatedSuccessTimeInterval,
} BNJSUserDefaultsKey;
/**
* 用于约束UserDefaults存储的Key
*/
@interface BNJSUserDefaultsHelper : NSObject
+ (id)valueForKey:(BNJSUserDefaultsKey)cusKey;
+ (BOOL)setValue:(id)value forKey:(BNJSUserDefaultsKey)cusKey;
+ (BOOL)boolForKey:(BNJSUserDefaultsKey)cusKey;
+ (BOOL)setBool:(BOOL)value forKey:(BNJSUserDefaultsKey)cusKey;
+ (NSInteger)integerForKey:(BNJSUserDefaultsKey)cusKey;
+ (BOOL)setInteger:(NSInteger)value forKey:(BNJSUserDefaultsKey)cusKey;
+ (double)doubleForKey:(BNJSUserDefaultsKey)cusKey;
+ (BOOL)setDouble:(double)value forKey:(BNJSUserDefaultsKey)cusKey;
@end
|
module React
module Rails
# A renderer class suitable for `ActionController::Renderers`.
# It is associated to `:component` in the Railtie.
#
# It is prerendered by default with {React::ServerRendering}.
# Set options[:prerender] to `false` to disable prerendering.
#
# @example Rendering a component from a controller
# class TodosController < ApplicationController
# def index
# @todos = Todo.all
# render component: 'TodoList', props: { todos: @todos }, tag: 'span', class: 'todo'
# end
# end
class ControllerRenderer
include React::Rails::ViewHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::TextHelper
attr_accessor :output_buffer
def initialize(options={})
controller = options[:controller]
@__react_component_helper = controller.__react_component_helper
end
# @return [String] HTML for `component_name` with `options[:props]`
def call(component_name, options, &block)
props = options.fetch(:props, {})
options = default_options.merge(options.slice(:data, :aria, :tag, :class, :id, :prerender))
react_component(component_name, props, options, &block)
end
private
def default_options
{ prerender: true }
end
end
end
end
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/rappor/test_rappor_service.h"
#include "components/rappor/byte_vector_utils.h"
#include "components/rappor/proto/rappor_metric.pb.h"
#include "components/rappor/rappor_parameters.h"
namespace rappor {
TestRapporService::TestRapporService()
: RapporService(&prefs_) {
Initialize(0,
HmacByteVectorGenerator::GenerateEntropyInput(),
FINE_LEVEL);
}
TestRapporService::~TestRapporService() {}
int TestRapporService::GetReportsCount() {
RapporReports reports;
ExportMetrics(&reports);
return reports.report_size();
}
} // namespace rappor
|
// Copyright (C) 2018 Fievus
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System;
namespace Charites.Windows.Mvc.Bindings
{
/// <summary>
/// Represents an edit content of an editable content.
/// </summary>
/// <typeparam name="T">The type of the content.</typeparam>
public class EditableEditContent<T> : IEditableEditContent<T>
{
/// <summary>
/// Occurs when an edit is completed.
/// </summary>
public event EventHandler EditCompleted;
/// <summary>
/// Occurs when an edit is canceled.
/// </summary>
public event EventHandler EditCanceled;
/// <summary>
/// Gets the <see cref="ObservableProperty{T}"/> of the value of the content.
/// </summary>
public ObservableProperty<T> Value { get; } = new ObservableProperty<T>();
/// <summary>
/// Initializes a new instance of the <see cref="EditableEditContent{T}"/> class.
/// </summary>
public EditableEditContent()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EditableEditContent{T}"/> class
/// with the specified content value.
/// </summary>
/// <param name="value">The value of the edit content.</param>
public EditableEditContent(T value)
{
Value.Value = value;
}
/// <summary>
/// Completes an edit of the content.
/// </summary>
public void CompleteEdit() => OnEditCompleted(EventArgs.Empty);
/// <summary>
/// Cancels an edit of the content.
/// </summary>
public void CancelEdit() => OnEditCanceled(EventArgs.Empty);
/// <summary>
/// Raises the <see cref="EditCompleted"/> event with the specified event data.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnEditCompleted(EventArgs e) => EditCompleted?.Invoke(this, e);
/// <summary>
/// Raises the <see cref="EditCanceled"/> event with the specified event data.
/// </summary>
/// <param name="e">The event data.</param>
protected virtual void OnEditCanceled(EventArgs e) => EditCanceled?.Invoke(this, e);
}
}
|
package org.monospark.remix;
/**
* A {@code RecordRemixer} is a factory for a {@link RecordRemix}
* that can be linked to a record class using either the {@link Remix} annotation or
* {@link Records#remix(Class, RecordRemixer)}.
* <p>
* Any subclass must have a default constructor to instantiate it via reflection.
**/
@FunctionalInterface
public interface RecordRemixer<R extends Record> {
/**
* Creates the {@link RecordRemix} that specifies the record behaviour.
* <p>
* This method is only called once.
**/
void create(RecordRemix<R> r);
}
|
package gazette
import java.sql.Date
import scodec.{Attempt, Codec, Err}
import scodec.codecs.{uint16, utf8, variableSizeBits}
import scalaz.Disjunction
object Util {
def parseDate(s: String): Option[Date] = Disjunction.fromTryCatchNonFatal(Date.valueOf(s)).toOption
def parseCsv(s: String): List[String] =
s.split(",").toList.map(_.trim).filter(_.nonEmpty)
implicit val stringCodec = variableSizeBits(uint16, utf8)
private def stringToDate(s: String): Attempt[Date] =
Attempt.fromOption(Util.parseDate(s), Err(s"Could not parse yyyy-MM-dd from ${s}."))
private def dateToString(d: Date): Attempt[String] =
Attempt.fromOption(Some(d.toString), Err("Strange error, encoding a Date should always work."))
implicit val dateCodec: Codec[Date] = variableSizeBits(uint16, utf8).exmap(stringToDate, dateToString)
}
|
{-# LANGUAGE DeriveGeneric #-}
module Tunebank.Model.NewUser where
import GHC.Generics
import Data.Text (Text)
import Database.PostgreSQL.Simple
-- import Database.PostgreSQL.Simple.FromField (FromField(..), fromField)
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
-- | a data type that represents a new user to be presented to the database
-- | which will generate default values for id, creation_ts and role (Normal)
data NewUser = NewUser
{ name :: Text
, email :: Text
, password :: Text
} deriving (Eq, Show, Generic)
instance ToRow NewUser where
toRow u = [ toField (name u), toField (email u), toField (password u) ]
data EmailConfirmation = EmailConfirmation
{ address :: Text
, slug :: Text
}
-- | the returned type of a successful new user registration
instance FromRow EmailConfirmation where
fromRow = EmailConfirmation <$> field <*> field
|
use std::{fs, io, path::Path};
// stackoverflow.com/questions/26958489/how-to-copy-a-folder-recursively-in-rust
pub(crate) fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
fs::create_dir_all(&dst)?;
for entry in fs::read_dir(src)? {
let entry = entry?;
let ty = entry.file_type()?;
if ty.is_dir() {
copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?;
} else {
fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?;
}
}
Ok(())
}
|
{-|
This implements the 'basic conversion routine' given in Section 2 of Adams' original paper,
without using lookup tables to speed up the loops.
-}
module Text.Format.Floating.Simple where
import Text.Format.Floating.Constants
import Text.Format.Floating.Decimal
import Text.Format.Floating.Rounding
import Data.Text (Text)
formatDec :: (RealFloat a) => a -> Text
formatDec = formatDec' RoundEven
formatDec' :: (RealFloat a) => RoundingMode -> a -> Text
formatDec' rm x = renderDecimal (convertToDecimal x rm)
formatSci :: (RealFloat a) => a -> Text
formatSci = formatSci' RoundEven
formatSci' :: (RealFloat a) => RoundingMode -> a -> Text
formatSci' rm x = renderDecimalSci (convertToDecimal x rm)
-- | Convert a given float to the form (m10, e10) where m10 is the smallest valid integer,
-- such that a = m10 * 10 ^ e10.
convertToDecimal :: (RealFloat a) => a -> RoundingMode -> DecimalFloat
convertToDecimal x rm
| isNaN x = DecimalNaN mf
| isInfinite x = DecimalInfinity s
| x == 0.0 = DecimalFloat False 0 0
| isNegativeZero x = DecimalFloat True 0 0
| otherwise = DecimalFloat s (e0 + e10) (abs d0)
where
(mf, ef) = decodeFloat x
s = signum x < 0
e2 = toInteger ef - 2
uvw = addIntervals
(intervalOf $ 4 * mf)
(if x == smallestNormalizedFloat then -1 else -2, 0, 2)
(e10, (a, b, c)) = if e2 >= 0
then (0, scaleInterval uvw (2 ^ e2))
else (e2, scaleInterval uvw (5 ^ abs e2))
(d0, e0) = shortestDecimalRep a b c (acceptLowerBound rm mf s) (acceptUpperBound rm mf s) True
shortestDecimalRep :: Integer -> Integer -> Integer -> Bool -> Bool -> Bool -> (Integer, Integer)
shortestDecimalRep a0 b0 c0 acceptSmaller acceptLarger breakTieDown
= loop True True a0 b0 (if acceptLarger then c0 else c0 - 1) 0 0 where
loop az bz a b c digit i =
let a' = a `div` 10
b' = b `div` 10
c' = c `div` 10
digit' = b `mod` 10
adz = a `mod` 10 == 0
az' = az && adz
bz' = bz && (digit == 0)
isTie = digit == 5 && bz
wantRoundDown = digit < 5 || (isTie && breakTieDown)
roundDown = (wantRoundDown && (a /= b || az)) || b + 1 > c
in if a' < c' || (acceptSmaller && az')
then loop az' bz' a' b' c' digit' (i + 1)
else (if roundDown then b else b + 1, i)
|
/*
* Copyright (c) 2012, Thingsquare, http://www.thingsquare.com/.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include "contiki-net.h"
#include "websocket.h"
/* Log configuration */
#include "sys/log.h"
#define LOG_MODULE "Websocket"
#define LOG_LEVEL LOG_LEVEL_IPV6
PROCESS(websocket_process, "Websockets process");
#define MAX_HOSTLEN 64
#define MAX_PATHLEN 100
LIST(websocketlist);
#define WEBSOCKET_FIN_BIT 0x80
#define WEBSOCKET_OPCODE_MASK 0x0f
#define WEBSOCKET_OPCODE_CONT 0x00
#define WEBSOCKET_OPCODE_TEXT 0x01
#define WEBSOCKET_OPCODE_BIN 0x02
#define WEBSOCKET_OPCODE_CLOSE 0x08
#define WEBSOCKET_OPCODE_PING 0x09
#define WEBSOCKET_OPCODE_PONG 0x0a
#define WEBSOCKET_MASK_BIT 0x80
#define WEBSOCKET_LEN_MASK 0x7f
struct websocket_frame_hdr {
uint8_t opcode;
uint8_t len;
uint8_t extlen[4];
};
struct websocket_frame_mask {
uint8_t mask[4];
};
/*---------------------------------------------------------------------------*/
static int
parse_url(const char *url, char *host, uint16_t *portptr, char *path)
{
const char *urlptr;
int i;
const char *file;
uint16_t port;
if(url == NULL) {
return 0;
}
/* Don't even try to go further if the URL is empty. */
if(strlen(url) == 0) {
return 0;
}
/* See if the URL starts with http:// or ws:// and remove it. */
if(strncmp(url, "http://", strlen("http://")) == 0) {
urlptr = url + strlen("http://");
} else if(strncmp(url, "ws://", strlen("ws://")) == 0) {
urlptr = url + strlen("ws://");
} else {
urlptr = url;
}
/* Find host part of the URL. */
for(i = 0; i < MAX_HOSTLEN; ++i) {
if(*urlptr == 0 ||
*urlptr == '/' ||
*urlptr == ' ' ||
*urlptr == ':') {
if(host != NULL) {
host[i] = 0;
}
break;
}
if(host != NULL) {
host[i] = *urlptr;
}
++urlptr;
}
/* Find the port. Default is 0, which lets the underlying transport
select its default port. */
port = 0;
if(*urlptr == ':') {
port = 0;
do {
++urlptr;
if(*urlptr >= '0' && *urlptr <= '9') {
port = (10 * port) + (*urlptr - '0');
}
} while(*urlptr >= '0' &&
*urlptr <= '9');
}
if(portptr != NULL) {
*portptr = port;
}
/* Find file part of the URL. */
while(*urlptr != '/' && *urlptr != 0) {
++urlptr;
}
if(*urlptr == '/') {
file = urlptr;
} else {
file = "/";
}
if(path != NULL) {
strncpy(path, file, MAX_PATHLEN);
}
return 1;
}
/*---------------------------------------------------------------------------*/
static int
start_get(struct websocket *s)
{
if(websocket_http_client_get(&(s->s)) == 0) {
LOG_ERR("Out of memory error\n");
s->state = WEBSOCKET_STATE_CLOSED;
return WEBSOCKET_ERR;
} else {
LOG_INFO("Connecting...\n");
s->state = WEBSOCKET_STATE_HTTP_REQUEST_SENT;
return WEBSOCKET_OK;
}
return WEBSOCKET_ERR;
}
/*---------------------------------------------------------------------------*/
void
call(struct websocket *s, websocket_result_t r,
const uint8_t *data, uint16_t datalen)
{
if(s != NULL && s->callback != NULL) {
s->callback(s, r, data, datalen);
}
}
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(websocket_process, ev, data)
{
PROCESS_BEGIN();
while(1) {
PROCESS_WAIT_EVENT();
if(ev == resolv_event_found && data != NULL) {
int ret;
struct websocket *s;
const char *name = data;
/* Either found a hostname, or not. We need to go through the
list of websocketsand figure out to which connection this
reply corresponds, then either restart the HTTP get, or kill
it (if no hostname was found). */
for(s = list_head(websocketlist);
s != NULL;
s = list_item_next(s)) {
if(strcmp(name, websocket_http_client_hostname(&s->s)) == 0) {
ret = resolv_lookup(name, NULL);
if(ret == RESOLV_STATUS_CACHED) {
/* Hostname found, restart get. */
if(s->state == WEBSOCKET_STATE_DNS_REQUEST_SENT) {
LOG_INFO("Restarting get\n");
start_get(s);
}
} else {
if(s->state == WEBSOCKET_STATE_DNS_REQUEST_SENT) {
/* Hostname not found, kill connection. */
LOG_ERR("killing connection\n");
call(s, WEBSOCKET_HOSTNAME_NOT_FOUND, NULL, 0);
}
}
}
}
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
/* Callback function. Called from the webclient when the HTTP
* connection was abruptly aborted.
*/
void
websocket_http_client_aborted(struct websocket_http_client_state *client_state)
{
if(client_state != NULL) {
struct websocket *s = (struct websocket *)
((char *)client_state - offsetof(struct websocket, s));
LOG_WARN("Websocket reset\n");
s->state = WEBSOCKET_STATE_CLOSED;
call(s, WEBSOCKET_RESET, NULL, 0);
}
}
/*---------------------------------------------------------------------------*/
/* Callback function. Called from the webclient when the HTTP
* connection timed out.
*/
void
websocket_http_client_timedout(struct websocket_http_client_state *client_state)
{
if(client_state != NULL) {
struct websocket *s = (struct websocket *)
((char *)client_state - offsetof(struct websocket, s));
LOG_WARN("Websocket timed out\n");
s->state = WEBSOCKET_STATE_CLOSED;
call(s, WEBSOCKET_TIMEDOUT, NULL, 0);
}
}
/*---------------------------------------------------------------------------*/
/* Callback function. Called from the webclient when the HTTP
* connection was closed after a request from the "websocket_http_client_close()"
* function. .
*/
void
websocket_http_client_closed(struct websocket_http_client_state *client_state)
{
if(client_state != NULL) {
struct websocket *s = (struct websocket *)
((char *)client_state - offsetof(struct websocket, s));
LOG_INFO("Websocket closed.\n");
s->state = WEBSOCKET_STATE_CLOSED;
call(s, WEBSOCKET_CLOSED, NULL, 0);
}
}
/*---------------------------------------------------------------------------*/
/* Callback function. Called from the webclient when the HTTP
* connection is connected.
*/
void
websocket_http_client_connected(struct websocket_http_client_state *client_state)
{
struct websocket *s = (struct websocket *)
((char *)client_state - offsetof(struct websocket, s));
LOG_INFO("Websocket connected\n");
s->state = WEBSOCKET_STATE_WAITING_FOR_HEADER;
call(s, WEBSOCKET_CONNECTED, NULL, 0);
}
/*---------------------------------------------------------------------------*/
/* The websocket header may potentially be split into multiple TCP
segments. This function eats one byte each, puts it into
s->headercache, and checks whether or not the full header has been
received. */
static int
receive_header_byte(struct websocket *s, uint8_t byte)
{
int len;
int expected_len;
struct websocket_frame_hdr *hdr;
/* Take the next byte of data and place it in the header cache. */
if(s->state == WEBSOCKET_STATE_RECEIVING_HEADER) {
s->headercache[s->headercacheptr] = byte;
s->headercacheptr++;
if(s->headercacheptr >= sizeof(s->headercache)) {
/* Something bad happened: we ad read 10 bytes and had not yet
found a reasonable header, so we close the socket. */
websocket_close(s);
}
}
len = s->headercacheptr;
hdr = (struct websocket_frame_hdr *)s->headercache;
/* Check the header that we have received to see if it is long
enough. */
/* We start with expecting a length of at least two bytes (opcode +
1 length byte). */
expected_len = 2;
if(len >= expected_len) {
/* We check how many more bytes we should expect to see. The
length byte determines how many length bytes are included in
the header. */
if((hdr->len & WEBSOCKET_LEN_MASK) == 126) {
expected_len += 2;
} else if((hdr->len & WEBSOCKET_LEN_MASK) == 127) {
expected_len += 4;
}
/* If the option has the mask bit set, we should expect to see 4
mask bytes at the end of the header. */
if((hdr->len & WEBSOCKET_MASK_BIT ) != 0) {
expected_len += 4;
}
/* Now we know how long our header if expected to be. If it is
this long, we are done and we set the state to reflect this. */
if(len == expected_len) {
s->state = WEBSOCKET_STATE_HEADER_RECEIVED;
return 1;
}
}
return 0;
}
/*---------------------------------------------------------------------------*/
/* Callback function. Called from the webclient module when HTTP data
* has arrived.
*/
void
websocket_http_client_datahandler(struct websocket_http_client_state *client_state,
const uint8_t *data, uint16_t datalen)
{
struct websocket *s = (struct websocket *)
((char *)client_state - offsetof(struct websocket, s));
struct websocket_frame_hdr *hdr;
struct websocket_frame_mask *maskptr;
if(data == NULL) {
call(s, WEBSOCKET_CLOSED, NULL, 0);
} else {
/* This function is a state machine that does different things
depending on the state. If we are waiting for header (the
default state), we change to the RECEIVING_HEADER state when we
get the first byte. If we are receiving header, we put all
bytes we have into a header buffer until the full header has
been received. If we have received the header, we parse it. If
we have received and parsed the header, we are ready to receive
data. Finally, if there is data left in the incoming packet, we
repeat the process. */
if(s->state == WEBSOCKET_STATE_WAITING_FOR_HEADER) {
s->state = WEBSOCKET_STATE_RECEIVING_HEADER;
s->headercacheptr = 0;
}
if(s->state == WEBSOCKET_STATE_RECEIVING_HEADER) {
while(datalen > 0 && s->state == WEBSOCKET_STATE_RECEIVING_HEADER) {
receive_header_byte(s, data[0]);
data++;
datalen--;
}
}
if(s->state == WEBSOCKET_STATE_HEADER_RECEIVED) {
/* If this is the start of an incoming websocket data frame, we
decode the header and check if we should act on in. If not, we
pipe the data to the application through a callback handler. If
data arrives in multiple packets, it is up to the application to
put it back together again. */
/* The websocket header is at the start of the incoming data. */
hdr = (struct websocket_frame_hdr *)s->headercache;
/* The s->left field holds the length of the application data
* chunk that we are about to receive. */
s->len = s->left = 0;
/* The s->mask field holds the bitmask of the data chunk, if
* any. */
memset(s->mask, 0, sizeof(s->mask));
/* We first read out the length of the application data
chunk. The length may be encoded over multiple bytes. If the
length is >= 126 bytes, it is encoded as two or more
bytes. The first length field determines if it is in 2 or 4
bytes. We also keep track of where the bitmask is held - its
place also differs depending on how the length is encoded. */
maskptr = (struct websocket_frame_mask *)hdr->extlen;
if((hdr->len & WEBSOCKET_LEN_MASK) < 126) {
s->len = s->left = hdr->len & WEBSOCKET_LEN_MASK;
} else if(hdr->len == 126) {
s->len = s->left = (hdr->extlen[0] << 8) + hdr->extlen[1];
maskptr = (struct websocket_frame_mask *)&hdr->extlen[2];
} else if(hdr->len == 127) {
s->len = s->left = ((uint32_t)hdr->extlen[0] << 24) +
((uint32_t)hdr->extlen[1] << 16) +
((uint32_t)hdr->extlen[2] << 8) +
hdr->extlen[3];
maskptr = (struct websocket_frame_mask *)&hdr->extlen[4];
}
/* Set user_data to point to the first byte of application data.
See if the application data chunk is masked or not. If it is,
we copy the bitmask into the s->mask field. */
if((hdr->len & WEBSOCKET_MASK_BIT) == 0) {
/* LOG_INFO("No mask\n");*/
} else {
memcpy(s->mask, &maskptr->mask, sizeof(s->mask));
/* LOG_INFO("There was a mask, %02x %02x %02x %02x\n",
s->mask[0], s->mask[1], s->mask[2], s->mask[3]);*/
}
/* Remember the opcode of the application chunk, put it in the
* s->opcode field. */
s->opcode = hdr->opcode & WEBSOCKET_OPCODE_MASK;
if(s->opcode == WEBSOCKET_OPCODE_PING) {
/* If the opcode is ping, we change the opcode to a pong, and
* send the data back. */
hdr->opcode = (hdr->opcode & (~WEBSOCKET_OPCODE_MASK)) |
WEBSOCKET_OPCODE_PONG;
websocket_http_client_send(&s->s, (const uint8_t*)hdr, 2);
if(s->left > 0) {
websocket_http_client_send(&s->s, (const uint8_t*)data, s->left);
}
LOG_INFO("Got ping\n");
call(s, WEBSOCKET_PINGED, NULL, 0);
s->state = WEBSOCKET_STATE_WAITING_FOR_HEADER;
} else if(s->opcode == WEBSOCKET_OPCODE_PONG) {
/* If the opcode is pong, we call the application to let it
know we got a pong. */
LOG_INFO("Got pong\n");
call(s, WEBSOCKET_PONG_RECEIVED, NULL, 0);
s->state = WEBSOCKET_STATE_WAITING_FOR_HEADER;
} else if(s->opcode == WEBSOCKET_OPCODE_CLOSE) {
/* If the opcode is a close, we send a close frame back. */
hdr->opcode = (hdr->opcode & (~WEBSOCKET_OPCODE_MASK)) |
WEBSOCKET_OPCODE_CLOSE;
websocket_http_client_send(&s->s, (const uint8_t*)hdr, 2);
if(s->left > 0) {
websocket_http_client_send(&s->s, (const uint8_t*)data, s->left);
}
LOG_INFO("Got close, sending close\n");
s->state = WEBSOCKET_STATE_WAITING_FOR_HEADER;
websocket_http_client_close(&s->s);
} else if(s->opcode == WEBSOCKET_OPCODE_BIN ||
s->opcode == WEBSOCKET_OPCODE_TEXT) {
/* If the opcode is bin or text, and there is application
* layer data in the packet, we call the application to
* process it. */
if(s->left > 0) {
s->state = WEBSOCKET_STATE_RECEIVING_DATA;
if(datalen > 0) {
int len;
len = MIN(s->left, datalen);
/* XXX todo: mask if needed. */
call(s, WEBSOCKET_DATA, data, len);
data += len;
s->left -= len;
datalen -= len;
}
}
}
if(s->left == 0) {
call(s, WEBSOCKET_DATA_RECEIVED, NULL, s->len);
s->state = WEBSOCKET_STATE_WAITING_FOR_HEADER;
/* Need to keep parsing the incoming data to check for more
frames, if the incoming datalen is > than s->left. */
if(datalen > 0) {
websocket_http_client_datahandler(client_state,
data, datalen);
}
}
} else if(s->state == WEBSOCKET_STATE_RECEIVING_DATA) {
/* XXX todo: mask if needed. */
if(datalen > 0) {
if(datalen < s->left) {
call(s, WEBSOCKET_DATA, data, datalen);
s->left -= datalen;
data += datalen;
datalen = 0;
} else {
call(s, WEBSOCKET_DATA, data, s->left);
data += s->left;
datalen -= s->left;
s->left = 0;
}
}
if(s->left == 0) {
call(s, WEBSOCKET_DATA_RECEIVED, NULL, s->len);
s->state = WEBSOCKET_STATE_WAITING_FOR_HEADER;
/* Need to keep parsing the incoming data to check for more
frames, if the incoming datalen is > than len. */
if(datalen > 0) {
websocket_http_client_datahandler(client_state,
data, datalen);
}
}
}
}
}
/*---------------------------------------------------------------------------*/
static void
init(void)
{
static uint8_t inited = 0;
if(!inited) {
process_start(&websocket_process, NULL);
list_init(websocketlist);
inited = 1;
}
}
/*---------------------------------------------------------------------------*/
void
websocket_init(struct websocket *s)
{
init();
websocket_http_client_init(&s->s);
}
/*---------------------------------------------------------------------------*/
void
websocket_set_proxy(struct websocket *s,
const uip_ipaddr_t *addr, uint16_t port)
{
websocket_http_client_set_proxy(&s->s, addr, port);
}
/*---------------------------------------------------------------------------*/
websocket_result_t
websocket_open(struct websocket *s, const char *url,
const char *subprotocol, const char *hdr,
websocket_callback c)
{
int ret;
char host[MAX_HOSTLEN + 1] = {0};
char path[MAX_PATHLEN + 1] = {0};
uint16_t port;
uip_ipaddr_t addr;
init();
if(s == NULL) {
return WEBSOCKET_ERR;
}
if(s->state != WEBSOCKET_STATE_CLOSED) {
LOG_INFO("Open: closing websocket before opening it again.\n");
websocket_close(s);
}
s->callback = c;
if(parse_url(url, host, &port, path)) {
list_add(websocketlist, s);
websocket_http_client_register(&s->s, host, port, path, subprotocol, hdr);
/* First check if the host is an IP address. */
if(uiplib_ip4addrconv(host, (uip_ip4addr_t *)&addr) == 0 &&
uiplib_ip6addrconv(host, (uip_ip6addr_t *)&addr) == 0) {
/* Try to lookup the hostname. If it fails, we initiate a hostname
lookup and print out an informative message on the
statusbar. */
ret = resolv_lookup(host, NULL);
if(ret != RESOLV_STATUS_CACHED) {
resolv_query(host);
s->state = WEBSOCKET_STATE_DNS_REQUEST_SENT;
LOG_INFO("Resolving host...\n");
return WEBSOCKET_OK;
}
}
PROCESS_CONTEXT_BEGIN(&websocket_process);
ret = start_get(s);
PROCESS_CONTEXT_END();
return ret;
}
return -1;
}
/*---------------------------------------------------------------------------*/
void
websocket_close(struct websocket *s)
{
websocket_http_client_close(&s->s);
s->state = WEBSOCKET_STATE_CLOSED;
}
/*---------------------------------------------------------------------------*/
static int
send_data(struct websocket *s, const void *data,
uint16_t datalen, uint8_t data_type_opcode)
{
uint8_t buf[WEBSOCKET_MAX_MSGLEN + 4 + 4]; /* The extra + 4 + 4 here
comes from the size of
the websocket framing
header. */
struct websocket_frame_hdr *hdr;
struct websocket_frame_mask *mask;
LOG_INFO("send data len %d %.*s\n", datalen, datalen, (char *)data);
if(s->state == WEBSOCKET_STATE_CLOSED ||
s->state == WEBSOCKET_STATE_DNS_REQUEST_SENT ||
s->state == WEBSOCKET_STATE_HTTP_REQUEST_SENT) {
/* Trying to send data on a non-connected websocket. */
LOG_ERR("send fail: not connected\n");
return -1;
}
/* We need to have 4 + 4 additional bytes for the websocket framing
header. */
if(4 + 4 + datalen > websocket_http_client_sendbuflen(&s->s)) {
LOG_ERR("too few bytes left (%d left, %d needed)\n",
websocket_http_client_sendbuflen(&s->s),
4 + 4 + datalen);
return -1;
}
if(datalen > sizeof(buf) - 4 - 4) {
LOG_ERR("trying to send too large data chunk %d > %d\n",
datalen, (int)sizeof(buf) - 4 - 4);
return -1;
}
hdr = (struct websocket_frame_hdr *)&buf[0];
hdr->opcode = WEBSOCKET_FIN_BIT | data_type_opcode;
/* If the datalen is larger than 125 bytes, we need to send the data
length as two bytes. If the data length would be larger than 64k,
we should send the length as 4 bytes, but since we specify the
datalen as an unsigned 16-bit int, we do not handle the 64k case
here. */
if(datalen > 125) {
/* Data from client must always have the mask bit set, and a data
mask sent right after the header. */
hdr->len = 126 | WEBSOCKET_MASK_BIT;
hdr->extlen[0] = datalen >> 8;
hdr->extlen[1] = datalen & 0xff;
mask = (struct websocket_frame_mask *)&buf[4];
mask->mask[0] =
mask->mask[1] =
mask->mask[2] =
mask->mask[3] = 0;
memcpy(&buf[8], data, datalen);
return websocket_http_client_send(&s->s, buf, 8 + datalen);
} else {
/* Data from client must always have the mask bit set, and a data
mask sent right after the header. */
hdr->len = datalen | WEBSOCKET_MASK_BIT;
mask = (struct websocket_frame_mask *)&buf[2];
mask->mask[0] =
mask->mask[1] =
mask->mask[2] =
mask->mask[3] = 0;
memcpy(&buf[6], data, datalen);
return websocket_http_client_send(&s->s, buf, 6 + datalen);
}
return -1;
}
/*---------------------------------------------------------------------------*/
int
websocket_send_str(struct websocket *s, const char *str)
{
return send_data(s, str, strlen(str), WEBSOCKET_OPCODE_TEXT);
}
/*---------------------------------------------------------------------------*/
int
websocket_send(struct websocket *s, const uint8_t *data,
uint16_t datalen)
{
return send_data(s, data, datalen, WEBSOCKET_OPCODE_BIN);
}
/*---------------------------------------------------------------------------*/
int
websocket_ping(struct websocket *s)
{
uint8_t buf[sizeof(struct websocket_frame_hdr) +
sizeof(struct websocket_frame_mask)];
struct websocket_frame_hdr *hdr;
struct websocket_frame_mask *mask;
/* We need 2 + 4 additional bytes for the websocket framing
header. */
if(2 + 4 > websocket_http_client_sendbuflen(&s->s)) {
return -1;
}
hdr = (struct websocket_frame_hdr *)&buf[0];
mask = (struct websocket_frame_mask *)&buf[2];
hdr->opcode = WEBSOCKET_FIN_BIT | WEBSOCKET_OPCODE_PING;
/* Data from client must always have the mask bit set, and a data
mask sent right after the header. */
hdr->len = 0 | WEBSOCKET_MASK_BIT;
/* XXX: We just set a dummy mask of 0 for now and hope that this
works. */
mask->mask[0] =
mask->mask[1] =
mask->mask[2] =
mask->mask[3] = 0;
websocket_http_client_send(&s->s, buf, 2 + 4);
return 1;
}
/*---------------------------------------------------------------------------*/
int
websocket_queuelen(struct websocket *s)
{
return websocket_http_client_queuelen(&s->s);
}
/*---------------------------------------------------------------------------*/
|
#include <parameter_assertions/assertions.h>
#include <ros/ros.h>
#include "differential_drive.h"
DifferentialDrive::DifferentialDrive()
{
ros::NodeHandle nh;
ros::NodeHandle pNh("~");
assertions::param(pNh, "axle_length", axle_length_, 0.48);
assertions::param(pNh, "max_vel", max_vel_, 3.0);
mbf_twist_ = nh.subscribe("/cmd_vel", 1, &DifferentialDrive::twistToVelocity, this);
vel_pub_ = nh.advertise<igvc_msgs::velocity_pair>("/motors", 1);
}
void DifferentialDrive::twistToVelocity(geometry_msgs::Twist twist)
{
double speed = twist.linear.x;
double rotation = twist.angular.z;
double vel_right = speed + (rotation * axle_length_) / 2;
double vel_left = speed - (rotation * axle_length_) / 2;
double max_calc_vel = fmax(vel_right, vel_left);
if (max_calc_vel > max_vel_)
{
vel_right *= max_vel_ / max_calc_vel;
vel_left *= max_vel_ / max_calc_vel;
}
igvc_msgs::velocity_pair vel_msg;
vel_msg.right_velocity = vel_right;
vel_msg.left_velocity = vel_left;
vel_msg.duration = 0.02;
vel_msg.header.stamp = ros::Time::now();
vel_pub_.publish(vel_msg);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "differential_drive");
DifferentialDrive differential_drive;
ros::spin();
}
|
# XSL - FO (XSL Formatting Objects)
* XML
* Traditionally used with XSLT - XSL Templates (yay, more XML)
# Pros
* XML feels like enterprise
# Cons
* Limited tooling - you can get **Apache FOP** for free or pay 5000 dollars for commercial tools
* Formatting and text setting is poor - on par with CSS1/CSS2 possibilities (and often worse)
* Almost no community
* Prehistoric - last specification version was released 5 years ago
* Writing XML by hand is a pain. Writing XSLT - too.
* Formatting must be done inline - styles and content aren't separated at all
* People use templates as workaround
|
//! Get Once
//! ```
//! # use libsugar::once_get::*;
//! let mut a = None;
//! let b = a.get_or_init(|| 1);
//! assert_eq!(*b, 1);
//! ```
/// Get Once
pub trait OnceGet<T> {
/// Get ref, init it with f if was empty
fn get_or_init<F: FnOnce() -> T>(&mut self, f: F) -> &T;
/// Get mut ref, init it with f if was empty
fn get_mut_or_init<F: FnOnce() -> T>(&mut self, f: F) -> &mut T;
}
impl<T> OnceGet<T> for Option<T> {
fn get_or_init<F: FnOnce() -> T>(&mut self, f: F) -> &T {
if let Some(v) = self {
return v;
}
*self = Some(f());
self.as_ref().unwrap()
}
fn get_mut_or_init<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
if let Some(v) = self {
return v;
}
*self = Some(f());
self.as_mut().unwrap()
}
}
#[test]
fn test() {
let mut a = None;
let b = a.get_or_init(|| 1);
assert_eq!(*b, 1);
}
|
/* Copyright© 2000 - 2021 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/
export { AddressMatchService } from './AddressMatchService';
export { ChartService } from './ChartService';
export { DataFlowService } from './DataFlowService';
export { DatasetService } from './DatasetService';
export { DatasourceService } from './DatasourceService';
export { FeatureService } from './FeatureService';
export { FieldService } from './FieldService';
export { GridCellInfosService } from './GridCellInfosService';
export { GeoprocessingService } from './GeoprocessingService';
export { LayerInfoService } from './LayerInfoService';
export { MapService } from './MapService';
export { MeasureService } from './MeasureService';
export { NetworkAnalystService } from './NetworkAnalystService';
export { NetworkAnalyst3DService } from './NetworkAnalyst3DService';
export { ProcessingService } from './ProcessingService';
export { QueryService } from './QueryService';
export { ServiceBase } from './ServiceBase';
export { SpatialAnalystService } from './SpatialAnalystService';
export { ThemeService } from './ThemeService';
export { TrafficTransferAnalystService } from './TrafficTransferAnalystService';
export { WebPrintingJobService } from './WebPrintingJobService';
export { ImageService } from './ImageService';
export { ImageCollectionService } from './ImageCollectionService';
|
/*
* Copyright 2018 Copenhagen Center for Health Technology (CACHET) at the
* Technical University of Denmark (DTU).
* Use of this source code is governed by a MIT-style license that can be
* found in the LICENSE file.
*/
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:weather/weather.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _res = 'Unknown';
String key = '12b6e28582eb9298577c734a31ba9f4f';
WeatherStation ws;
@override
void initState() {
super.initState();
ws = new WeatherStation(key);
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
queryWeather();
}
void queryForecast() async {
List<Weather> f = await ws.fiveDayForecast();
setState(() {
_res = f.toString();
});
}
void queryWeather() async {
Weather w = await ws.currentWeather();
setState(() {
_res = w.toString();
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Weather API Example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_res,
),
],
),
),
floatingActionButton: FloatingActionButton(onPressed: queryWeather, child: Icon(Icons.cloud_download)),
),
);
}
}
|
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// 数据结构:阅读数
const Monitor = new Schema({
postId: { type: 'ObjectId', ref: 'Post' }, // 关联文章id
updateAt: Date, // 更新时间
readNum: Number,// 阅读数
likeNum: Number,// 点赞数
});
Monitor.plugin(require('motime'));
Monitor.index({ updateAt: 1 });
mongoose.model('Monitor', Monitor);
|
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializerExample
{
/// <summary>
/// Helps with serializing an object to binary and back again.
/// </summary>
public static class Serializer
{
/// <summary>
/// Serializes an object to binary
/// </summary>
/// <param name="Object">Object to serialize</param>
/// <param name="Output">Binary output of the object</param>
public static void ObjectToBinary(object Object, out byte[] Output)
{
try
{
using (MemoryStream Stream = new MemoryStream())
{
BinaryFormatter Formatter = new BinaryFormatter();
Formatter.Serialize(Stream, Object);
Stream.Seek(0, 0);
Output = Stream.ToArray();
}
}
catch { throw; }
}
/// <summary>
/// Deserializes an object from binary
/// </summary>
/// <typeparam name="T">Type of the object</typeparam>
/// <param name="Binary">Binary representation of the object</param>
/// <param name="Object">Object after it is deserialized</param>
public static void BinaryToObject<T>(byte[] Binary, out T Object)
{
try
{
using (MemoryStream Stream = new MemoryStream())
{
Stream.Write(Binary, 0, Binary.Length);
Stream.Seek(0, 0);
BinaryFormatter Formatter = new BinaryFormatter();
Object = (T)Formatter.Deserialize(Stream);
}
}
catch { throw; }
}
}
}
|
// Copyright (c) 2012 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
package db
import (
"github.com/couchbaselabs/sync_gateway/auth"
"github.com/sdegutis/go.assert"
"testing"
)
func TestValidatorFunction(t *testing.T) {
validator, err := NewValidator(`function(doc, oldDoc) {
if (doc.foo !=oldDoc.foo)
throw({forbidden: "bad"});}`)
assertNoError(t, err, "Couldn't create validator")
status, msg, err := validator.callValidator(`{"foo":1}`, `{"foo": 1}`, nil)
assertNoError(t, err, "callValidator failed")
assert.Equals(t, status, 200)
status, msg, err = validator.callValidator(`{"foo":1}`, `{"foo": 0}`, nil)
assertNoError(t, err, "callValidator failed")
assert.Equals(t, status, 403)
assert.Equals(t, msg, "bad")
}
func TestValidatorException(t *testing.T) {
validator, err := NewValidator(`function(doc,oldDoc) {var x; return x[5];}`)
assertNoError(t, err, "Couldn't create validator")
status, _, err := validator.callValidator(`{"foo":1}`, `{"foo": 1}`, nil)
assertNoError(t, err, "callValidator failed")
assert.Equals(t, status, 500)
}
func TestValidatorUser(t *testing.T) {
validator, err := NewValidator(`function(doc,oldDoc,userCtx) {
if (doc.owner != userCtx.name)
throw({"forbidden": userCtx.name});}`)
assertNoError(t, err, "Couldn't create validator")
fred := &auth.User{Name: "fred"}
status, _, err := validator.callValidator(`{"owner":"fred"}`, `{"owner":"fred"}`, fred)
assertNoError(t, err, "callValidator failed")
assert.Equals(t, status, 200)
eve := &auth.User{Name: "eve"}
status, msg, err := validator.callValidator(`{"owner":"fred"}`, `{"owner":"fred"}`, eve)
assertNoError(t, err, "callValidator failed")
assert.Equals(t, status, 403)
assert.Equals(t, msg, "eve")
}
|
# Funcionalidades
## Conexões
- Rota para criar uma nova conexão;
- Rota para listar total de conexões realizadas;
## Aulas
-- Rota para criar Aulas;
-- Rota para listar Aulas;
-- Filtrar por matéria, dia da semana e horário;
|
require 'rubygems'
require 'erb'
require 'optparse'
require 'yaml'
require 'fileutils'
require 'pathname'
module LocalConfig
#jobid from command line, for external overwrite
attr_accessor :job_idx
def parse_cmdline
#config
$options = {}
option_parser = OptionParser.new do |opts|
# Create a switch
#opts.on("-i","--iteration") do
# $options[:iteration] = true
#end
# Create a flag
opts.on("--execloc NAME") do |it|
$exec_loc = it
end
# Create a flag
opts.on("--range RANGE") do |it|
$opt_rng = it
$opt_rng_min = it.split("-")[0].to_i
$opt_rng_max = it.split("-")[1].to_i
end
opts.on("--wall HOURS") do |it|
$opt_wall = it
end
opts.on("--procs NB") do |it|
$opt_procs = it
end
opts.on("--threads NB") do |it|
$opt_threads = it
end
opts.on("--jobid NB") do |it|
#sets it on command line parsing as default for @job_idx field
self.job_idx = it
end
end
#parse
option_parser.parse!
puts $options.inspect
end
def init
puts "in LocalConfig.init"
@config_yml = YAML.load_file('../templ/config.yml')
@exec_yml = YAML.load_file('../templ/exec.yml')
@files_yml = YAML.load_file('../templ/files.yml')
#puts "@config_yml: #{@config_yml.inspect}"
#puts "exec_yml: #{@exec_yml.inspect}"
#puts "files_yml: #{@files_yml.inspect}"
parse_cmdline()
super
end
def job_name
@config_yml["job_name"]
end
def queue
@config_yml["queue"]
end
def opt_wall
$opt_wall
end
def opt_procs
$opt_procs.to_i
end
def opt_threads
$opt_threads.to_i
end
def job_s
"%05d" % self.job_idx
# job_idx
end
def home_d
Pathname.new @exec_yml["home"]
end
def exec_d
key = @config_yml["exec_loc"]
val = Pathname.new @exec_yml[key]
#puts "key: #{key}, val: #{val}"
end
def local_dir
Pathname.new @config_yml["local_dir"]
end
def ldir
ldir = Pathname.new "#{home_d}/#{local_dir}"
#puts ldir
end
def sdir
sdir = Pathname.new "#{exec_d}/#{local_dir}"
#puts sdir
end
end
|
<?php
namespace CpChart\Behat\Context;
use Behat\Mink\Mink;
use Behat\Mink\Session;
use Behat\MinkExtension\Context\MinkAwareContext;
use SensioLabs\Behat\PageObjectExtension\Context\PageObjectContext;
/**
* @author Piotr Szymaszek
*/
abstract class MinkAwarePageContext extends PageObjectContext implements MinkAwareContext
{
private $mink;
private $minkParameters;
/**
* @param Mink $mink Mink session manager
*/
public function setMink(Mink $mink)
{
$this->mink = $mink;
}
/**
* @return Mink
*/
public function getMink()
{
return $this->mink;
}
/**
* @param array $parameters
*/
public function setMinkParameters(array $parameters)
{
$this->minkParameters = $parameters;
}
/**
* @param string|null $name name of the session OR active session will be used
*
* @return Session
*/
public function getSession($name = null)
{
return $this->mink->getSession($name);
}
}
|
/*
* Copyright 2017 Karlsruhe Institute of Technology.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.kit.datamanager.entities.repo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import edu.kit.datamanager.entities.BaseEnum;
import edu.kit.datamanager.util.json.CustomInstantDeserializer;
import edu.kit.datamanager.util.json.CustomInstantSerializer;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import lombok.Data;
/**
*
* @author jejkal
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "resource", namespace = "http://datacite.org/schema/kernel-4")
public class DataResource implements Serializable{
public enum State implements BaseEnum{
VOLATILE,
FIXED,
REVOKED,
GONE;
@Override
public String getValue(){
return toString();
}
}
//The internal resource identifier assigned once during creation
//mandatory
private PrimaryIdentifier identifier;
@XmlTransient
private String id = null;
//vocab
@XmlElementWrapper(name = "creators")
@XmlElement(name = "creator")
private Set<Agent> creators = new HashSet<>();
@XmlElementWrapper(name = "titles")
@XmlElement(name = "title")
private Set<Title> titles = new HashSet<>();
private String publisher;
//format: YYYY
private String publicationYear;
@XmlElement(name = "resourceType")
private ResourceType resourceType;
//recommended
@XmlElementWrapper(name = "subjects")
@XmlElement(name = "subject")
private Set<Subject> subjects = new HashSet<>();
@XmlElementWrapper(name = "contributors")
@XmlElement(name = "contributor")
private Set<Contributor> contributors = new HashSet<>();
@XmlElementWrapper(name = "dates")
@XmlElement(name = "date")
private Set<Date> dates = new HashSet<>();
@XmlElementWrapper(name = "relatedIdentifiers")
@XmlElement(name = "relatedIdentifier")
private Set<RelatedIdentifier> relatedIdentifiers = new HashSet<>();
@XmlElementWrapper(name = "descriptions")
@XmlElement(name = "description")
private Set<Description> descriptions = new HashSet<>();
private State state;
@XmlElementWrapper(name = "geoLocations")
@XmlElement(name = "geoLocation")
private Set<GeoLocation> geoLocations = new HashSet<>();
private String language;
@XmlElementWrapper(name = "alternateIdentifiers")
@XmlElement(name = "alternateIdentifier")
private Set<Identifier> alternateIdentifiers = new HashSet<>();
@XmlElementWrapper(name = "sizes")
@XmlElement(name = "size")
private Set<String> sizes = new HashSet<>();
@XmlElementWrapper(name = "formats")
@XmlElement(name = "format")
private Set<String> formats = new HashSet<>();
private String version;
@XmlElementWrapper(name = "rightsList")
@XmlElement(name = "rights")
private Set<Scheme> rights = new HashSet<>();
private Set<FundingReference> fundingReferences = new HashSet<>();
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'", timezone = "UTC")
@JsonDeserialize(using = CustomInstantDeserializer.class)
@JsonSerialize(using = CustomInstantSerializer.class)
private Instant lastUpdate;
@XmlElementWrapper(name = "aclEntries")
@XmlElement(name = "aclEntry")
private Set<AclEntry> acls = new HashSet<>();
@XmlTransient
@JsonIgnore
private List<ContentInformation> associatedContentInformation;
}
|
#include "Application.h"
#include <glm/gtc/matrix_transform.hpp>
#include "Draw.h"
Application::Application(
std::filesystem::path path,
std::unique_ptr<frame::WindowInterface>&& window) :
path_(path),
window_(std::move(window)) {}
void Application::Startup()
{
window_->SetDrawInterface(
std::make_unique<Draw>(
window_->GetSize(),
path_,
window_->GetUniqueDevice()));
}
void Application::Run()
{
window_->Run();
}
|
# Summary
This directory contains examples of how to use the Chocolatey Package Creator
module to dynamically create Chocolatey packages.
* `7zip`: Packages the 64-bit version of the 7zip CLI tool
* `dotnet-472`: Packages Microsoft .NET Framework 4.7.2
* `eps.extension`: Packages the Powershell EPS module as a Chocolatey extension. This is
used as a dependency in the `sql-express-adv` package.
* `ms-reportviewer2015`: Packages Microsoft SQL Server Report Viewer 2015. This is used as a dependency in `veeam`.
* `sql-2014-clr`: Packages Microsoft SQL Server 2014 runtime files. This is used as a dependency in `veeam`.
* `sql-2014-smo`: Packages Microsoft SQL Server 2014 management objects. This is used as a dependency in `veeam`.
* `sql-express-adv`: Packages Microsoft SQL Server 2019 (advanced)
* `vcredist`: Packages Microsoft Visual C++ runtime files. This is used as a dependency in `veeam`.
* `veeam`: Packages Veeam Backup & Replication
|
require 'spec_helper'
describe DataMigrate::DataMigrator do
let(:subject) { DataMigrate::DataMigrator }
describe :schema_migrations_table_name do
it "returns correct table name" do
expect(subject.schema_migrations_table_name).to eq("data_migrations")
end
end
describe :migrations_path do
it "returns correct migrations path" do
expect(subject.migrations_path).to eq("db/data")
end
end
end
|
package libp2p_pubsub
import (
"fmt"
"github.com/sivo4kin/ea-starter/libp2p/pub_sub_bls/modelBLS"
messageSigpb "github.com/sivo4kin/ea-starter/libp2p/pub_sub_bls/protobuf/messageWithSig"
"github.com/sivo4kin/ea-starter/libp2p/pub_sub_bls/protobuf/messagepb"
"github.com/sivo4kin/ea-starter/libp2p/pub_sub_bls/test_utils"
"github.com/stretchr/testify/require"
"go.dedis.ch/kyber/v3"
"go.dedis.ch/kyber/v3/pairing"
"go.dedis.ch/kyber/v3/sign"
"log"
"os"
"sync"
"testing"
"time"
core "github.com/libp2p/go-libp2p-core"
"github.com/sivo4kin/ea-starter/libp2p/pub_sub_bls/model"
)
type FailureModel int
const (
NoFailure = iota
MinorFailure
MajorFailure
RejoiningMinorityFailure
RejoiningMajorityFailure
LeaveRejoin
ThreeGroups
)
const FailureDelay = 3
const RejoinDelay = 15
const LeaveDelay = 10
// setupHosts is responsible for creating tlc nodes and also libp2p hosts.
func setupHosts(n int, initialPort int, failureModel FailureModel) ([]*model.Node, []*core.Host) {
fmt.Print("SETUP HOSTS\n")
// nodes used in tlc model
nodes := make([]*model.Node, n)
// hosts used in libp2p communications
hosts := make([]*core.Host, n)
for i := range nodes {
//var comm model.CommunicationInterface
var comm *Libp2pPubSub
comm = new(Libp2pPubSub)
comm.topic = "TLC"
// creating libp2p hosts
host := comm.CreatePeer(i, initialPort+i)
hosts[i] = host
// creating pubsubs
comm.InitializePubSub(*host)
// Simulating rejoining failures, where a node leaves the delayed set and joins other progressing nodes
nVictim := 0
switch failureModel {
case RejoiningMinorityFailure:
nVictim = (n - 1) / 2
case RejoiningMajorityFailure:
nVictim = (n + 1) / 2
case LeaveRejoin:
nVictim = (n - 1) / 2
case ThreeGroups:
nVictim = n
}
if failureModel == ThreeGroups {
if i < 3 {
comm.JoinGroup([]int{0, 1, 2})
} else if i < 6 {
comm.JoinGroup([]int{3, 4, 5})
} else {
comm.JoinGroup([]int{})
}
}
if i < nVictim {
comm.InitializeVictim(true)
go func() {
time.Sleep(2 * FailureDelay * time.Second)
comm.AttackVictim()
}()
nRejoin := 2
if failureModel == ThreeGroups {
nRejoin = 6
}
if i < nRejoin {
go func() {
// Delay for the node to get out of delayed(victim) group
time.Sleep((RejoinDelay + time.Duration(FailureDelay*i)) * time.Second)
comm.ReleaseVictim()
}()
}
} else {
if failureModel == LeaveRejoin {
if i == (n - 1) {
go func() {
// Delay for the node to leave the progressing group
time.Sleep(LeaveDelay * time.Second)
comm.Disconnect()
}()
}
}
comm.InitializeVictim(false)
}
nodes[i] = &model.Node{
Id: i,
TimeStep: 0,
ThresholdWit: n/2 + 1,
ThresholdAck: n/2 + 1,
Acks: 0,
ConvertMsg: &messagepb.Convert{},
Comm: comm,
History: make([]model.Message, 0)}
}
return nodes, hosts
}
// setupNetworkTopology sets up a simple network topology for test.
func setupNetworkTopology(hosts []*core.Host) (err error) {
// Connect hosts to each other in a topology
n := len(hosts)
for i := 0; i < n; i++ {
for j, nxtHost := range hosts {
if j == i {
continue
}
fmt.Printf("LOCAL HOST %s CONNECT TO nxtHost %s \n", GetLocalhostAddress(*hosts[i]), GetLocalhostAddress(*nxtHost))
err := connectHostToPeerWithError(*hosts[i], GetLocalhostAddress(*nxtHost))
if err != nil {
return err
}
}
}
for i := 0; i < n; i++ {
err = connectHostToPeerWithError(*hosts[i], GetLocalhostAddress(*hosts[(i+1)%n]))
if err != nil {
return
}
err = connectHostToPeerWithError(*hosts[i], GetLocalhostAddress(*hosts[(i+2)%n]))
if err != nil {
return
}
err = connectHostToPeerWithError(*hosts[i], GetLocalhostAddress(*hosts[(i+3)%n]))
if err != nil {
return
}
err = connectHostToPeerWithError(*hosts[i], GetLocalhostAddress(*hosts[(i+4)%n]))
if err != nil {
return
}
}
// Wait so that subscriptions on topic will be done and all peers will "know" of all other peers
time.Sleep(time.Second * 2)
return err
}
func minorityFailure(nodes []*model.Node, n int) int {
nFail := (n - 1) / 2
//nFail := 4
go func(nodes []*model.Node, nFail int) {
time.Sleep(FailureDelay * time.Second)
failures(nodes, nFail)
}(nodes, nFail)
return nFail
}
func majorityFailure(nodes []*model.Node, n int) int {
nFail := n/2 + 1
go func(nodes []*model.Node, nFail int) {
time.Sleep(FailureDelay * time.Second)
failures(nodes, nFail)
}(nodes, nFail)
return nFail
}
func failures(nodes []*model.Node, nFail int) {
for i, node := range nodes {
if i < nFail {
node.Comm.Disconnect()
}
}
}
func simpleTest(t *testing.T, n int, initialPort int, stop int, failureModel FailureModel) {
var nFail int
nodes, hosts := setupHosts(n, initialPort, failureModel)
defer func() {
fmt.Println("Closing hosts")
for _, h := range hosts {
_ = (*h).Close()
}
}()
err := setupNetworkTopology(hosts)
require.Nil(t, err)
// Put failures here
switch failureModel {
case MinorFailure:
nFail = minorityFailure(nodes, n)
case MajorFailure:
nFail = majorityFailure(nodes, n)
case RejoiningMinorityFailure:
nFail = (n-1)/2 - 1
case RejoiningMajorityFailure:
nFail = (n+1)/2 - 1
case LeaveRejoin:
nFail = (n-1)/2 - 1
case ThreeGroups:
nFail = (n - 1) / 2
}
// PubSub is ready and we can start our algorithm
fmt.Printf("STARTING TEST for %d nodes stop %d nfail %d\n", len(nodes), stop, nFail)
test_utils.StartTest(nodes, stop, nFail)
test_utils.LogOutput(t, nodes)
}
// Testing TLC with majority thresholds with no node failures
func TestWithNoFailure(t *testing.T) {
// Create hosts in libp2p
logFile, _ := os.OpenFile("../../../logs/TestWithNoFailure.log", os.O_RDWR|os.O_CREATE, 0666)
model.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
Delayed = false
simpleTest(t, 9, 9900, 9, NoFailure)
}
// Testing TLC with minor nodes failing
func TestWithMinorFailure(t *testing.T) {
// Create hosts in libp2p
logFile, _ := os.OpenFile("../../../logs/TestWithMinorFailure.log", os.O_RDWR|os.O_CREATE, 0666)
model.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
simpleTest(t, 11, 9900, 5, MinorFailure)
}
// Testing TLC with majority of nodes failing
func TestWithMajorFailure(t *testing.T) {
// Create hosts in libp2p
logFile, _ := os.OpenFile("../../../logs/log4.log", os.O_RDWR|os.O_CREATE, 0666)
model.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
simpleTest(t, 10, 9900, 5, MajorFailure)
}
// Testing TLC with majority of nodes working correctly and a set of delayed nodes. a node will leave the victim set
// after some seconds and rejoin to the progressing nodes.
func TestWithRejoiningMinorityFailure(t *testing.T) {
// Create hosts in libp2p
logFile, _ := os.OpenFile("../../../logs/RejoiningMinority.log", os.O_RDWR|os.O_CREATE, 0666)
model.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
simpleTest(t, 7, 9900, 3, RejoiningMinorityFailure)
}
// Testing TLC with majority of nodes being delayed. a node will leave the victim set after some seconds and rejoin to
// the other connected nodes. This will make progress possible.
func TestWithRejoiningMajorityFailure(t *testing.T) {
// Create hosts in libp2p
logFile, _ := os.OpenFile("../../../logs/RejoiningMajority.log", os.O_RDWR|os.O_CREATE, 0666)
model.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
simpleTest(t, 11, 9900, 10, RejoiningMajorityFailure)
}
// Testing TLC with majority of nodes working correctly and a set of delayed nodes. a node will lose connection to
// progressing nodes and will stop the progress. After some seconds another node will join to the set, making progress
// possible.
func TestWithLeaveRejoin(t *testing.T) {
// Create hosts in libp2p
logFile, _ := os.OpenFile("../../../logs/log8.log", os.O_RDWR|os.O_CREATE, 0666)
model.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
simpleTest(t, 11, 9900, 8, LeaveRejoin)
}
// TODO: Find a way to simualte this onw, since I have removed the case for this simulation
func TestWithThreeGroups(t *testing.T) {
// Create hosts in libp2p
logFile, _ := os.OpenFile("../../../logs/TestWithThreeGroups.log", os.O_RDWR|os.O_CREATE, 0666)
model.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
simpleTest(t, 11, 9900, 8, ThreeGroups)
}
func TestBLS(t *testing.T) {
logFile, _ := os.OpenFile("../../../logs/logBLS.log", os.O_RDWR|os.O_CREATE, 0666)
modelBLS.Logger1 = log.New(logFile, "", log.Ltime|log.Lmicroseconds)
Delayed = false
simpleTestBLS(t, 8, 9900, 3)
}
func simpleTestBLS(t *testing.T, n int, initialPort int, stop int) {
nodes, hosts := setupHostsBLS(n, initialPort)
defer func() {
fmt.Println("Closing hosts")
for _, h := range hosts {
_ = (*h).Close()
}
}()
err := setupNetworkTopology(hosts)
require.Nil(t, err)
// PubSub is ready and we can start our algorithm
StartTestBLS(nodes, stop, stop/3)
LogOutputBLS(t, nodes)
}
func setupHostsBLS(n int, initialPort int) ([]*modelBLS.Node, []*core.Host) {
// nodes used in tlc model
nodes := make([]*modelBLS.Node, n)
// hosts used in libp2p communications
hosts := make([]*core.Host, n)
publicKeys := make([]kyber.Point, 0)
privateKeys := make([]kyber.Scalar, 0)
suite := pairing.NewSuiteBn256()
for range nodes {
prvKey := suite.Scalar().Pick(suite.RandomStream())
privateKeys = append(privateKeys, prvKey)
// list of public keys
publicKeys = append(publicKeys, suite.Point().Mul(prvKey, nil))
}
fmt.Println(publicKeys)
for i := range nodes {
//var comm model.CommunicationInterface
var comm *Libp2pPubSub
comm = new(Libp2pPubSub)
comm.topic = "TLC"
// creating libp2p hosts
host := comm.CreatePeer(i, initialPort+i)
hosts[i] = host
// creating pubsubs
comm.InitializePubSub(*host)
comm.InitializeVictim(false)
mask, _ := sign.NewMask(suite, publicKeys, nil)
//////
nodes[i] = &modelBLS.Node{
Id: i,
TimeStep: 0,
ThresholdWit: n/2 + 1,
ThresholdAck: n/2 + 1,
Acks: 0,
ConvertMsg: &messageSigpb.Convert{},
Comm: comm,
History: make([]modelBLS.MessageWithSig, 0),
Signatures: make([][]byte, n),
SigMask: mask,
PublicKeys: publicKeys,
PrivateKey: privateKeys[i],
Suite: suite,
}
}
return nodes, hosts
}
// StartTest is used for starting tlc nodes
func StartTestBLS(nodes []*modelBLS.Node, stop int, fails int) {
fmt.Print("START")
wg := &sync.WaitGroup{}
for _, node := range nodes {
node.Advance(0)
}
for _, node := range nodes {
wg.Add(1)
go runNodeBLS(node, stop, wg)
}
wg.Add(-fails)
wg.Wait()
fmt.Println("The END")
}
func LogOutputBLS(t *testing.T, nodes []*modelBLS.Node) {
for i := range nodes {
t.Logf("nodes: %d , TimeStep : %d", i, nodes[i].TimeStep)
modelBLS.Logger1.Printf("%d,%d\n", i, nodes[i].TimeStep)
}
}
func runNodeBLS(node *modelBLS.Node, stop int, wg *sync.WaitGroup) {
defer wg.Done()
err := node.WaitForMsg(stop)
if err != nil {
fmt.Errorf(err.Error())
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package io.github.jass2125.sistema.alocacao.core.actions.location;
import io.github.jass2125.sistema.alocacao.core.util.Command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Anderson Souza
*/
public class ListLocationCommand implements Command {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
return null;
}
}
|
"""Disable headers and some other blocks for comment-like markdown peaces"""
from django.utils.deconstruct import deconstructible
from markdown.extensions import Extension
@deconstructible
class CommentExtension(Extension):
"""Disable headers and some other blocks for comment-like messages"""
def extendMarkdown(self, md, md_globals):
"""Disable <hr>, <h.>
To disable rendering of these blocks,
we need to delete theirs processors.
:param md: Current markdown instance.
:param md_globals: Global markdown vars.
"""
md.parser.blockprocessors.pop('hr', '')
md.parser.blockprocessors.pop('hashheader', '')
md.parser.blockprocessors.pop('setextheader', '')
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "abstractprocessstep.h"
#include "ansifilterparser.h"
#include "buildstep.h"
#include "project.h"
#include "task.h"
#include <coreplugin/reaper.h>
#include <utils/qtcassert.h>
#include <QTimer>
#include <QDir>
using namespace ProjectExplorer;
/*!
\class ProjectExplorer::AbstractProcessStep
\brief The AbstractProcessStep class is a convenience class that can be
used as a base class instead of BuildStep.
It should be used as a base class if your buildstep just needs to run a process.
Usage:
\list
\li Use processParameters() to configure the process you want to run
(you need to do that before calling AbstractProcessStep::init()).
\li Inside YourBuildStep::init() call AbstractProcessStep::init().
\li Inside YourBuildStep::run() call AbstractProcessStep::run(), which automatically starts the process
and by default adds the output on stdOut and stdErr to the OutputWindow.
\li If you need to process the process output override stdOut() and/or stdErr.
\endlist
The two functions processStarted() and processFinished() are called after starting/finishing the process.
By default they add a message to the output window.
Use setEnabled() to control whether the BuildStep needs to run. (A disabled BuildStep immediately returns true,
from the run function.)
\sa ProjectExplorer::ProcessParameters
*/
/*!
\fn void ProjectExplorer::AbstractProcessStep::setEnabled(bool b)
Enables or disables a BuildStep.
Disabled BuildSteps immediately return true from their run function.
Should be called from init().
*/
/*!
\fn ProcessParameters *ProjectExplorer::AbstractProcessStep::processParameters()
Obtains a reference to the parameters for the actual process to run.
Should be used in init().
*/
AbstractProcessStep::AbstractProcessStep(BuildStepList *bsl, Core::Id id) :
BuildStep(bsl, id)
{
m_timer.setInterval(500);
connect(&m_timer, &QTimer::timeout, this, &AbstractProcessStep::checkForCancel);
}
/*!
Deletes all existing output parsers and starts a new chain with the
given parser.
Derived classes need to call this function.
*/
void AbstractProcessStep::setOutputParser(IOutputParser *parser)
{
m_outputParserChain.reset(new AnsiFilterParser);
m_outputParserChain->appendOutputParser(parser);
connect(m_outputParserChain.get(), &IOutputParser::addOutput, this, &AbstractProcessStep::outputAdded);
connect(m_outputParserChain.get(), &IOutputParser::addTask, this, &AbstractProcessStep::taskAdded);
}
/*!
Appends the given output parser to the existing chain of parsers.
*/
void AbstractProcessStep::appendOutputParser(IOutputParser *parser)
{
if (!parser)
return;
QTC_ASSERT(m_outputParserChain, return);
m_outputParserChain->appendOutputParser(parser);
}
IOutputParser *AbstractProcessStep::outputParser() const
{
return m_outputParserChain.get();
}
void AbstractProcessStep::emitFaultyConfigurationMessage()
{
emit addOutput(tr("Configuration is faulty. Check the Issues view for details."),
BuildStep::OutputFormat::NormalMessage);
}
bool AbstractProcessStep::ignoreReturnValue()
{
return m_ignoreReturnValue;
}
/*!
If \a ignoreReturnValue is set to true, then the abstractprocess step will
return success even if the return value indicates otherwise.
Should be called from init.
*/
void AbstractProcessStep::setIgnoreReturnValue(bool b)
{
m_ignoreReturnValue = b;
}
/*!
Reimplemented from BuildStep::init(). You need to call this from
YourBuildStep::init().
*/
bool AbstractProcessStep::init(QList<const BuildStep *> &earlierSteps)
{
Q_UNUSED(earlierSteps);
return !m_process;
}
/*!
Reimplemented from BuildStep::init(). You need to call this from
YourBuildStep::run().
*/
void AbstractProcessStep::run(QFutureInterface<bool> &fi)
{
QDir wd(m_param.effectiveWorkingDirectory());
if (!wd.exists()) {
if (!wd.mkpath(wd.absolutePath())) {
emit addOutput(tr("Could not create directory \"%1\"")
.arg(QDir::toNativeSeparators(wd.absolutePath())),
BuildStep::OutputFormat::ErrorMessage);
reportRunResult(fi, false);
return;
}
}
QString effectiveCommand = m_param.effectiveCommand();
if (!QFileInfo::exists(effectiveCommand)) {
processStartupFailed();
reportRunResult(fi, false);
return;
}
m_futureInterface = &fi;
m_process.reset(new Utils::QtcProcess());
m_process->setUseCtrlCStub(Utils::HostOsInfo::isWindowsHost());
m_process->setWorkingDirectory(wd.absolutePath());
m_process->setEnvironment(m_param.environment());
m_process->setCommand(effectiveCommand, m_param.effectiveArguments());
connect(m_process.get(), &QProcess::readyReadStandardOutput,
this, &AbstractProcessStep::processReadyReadStdOutput);
connect(m_process.get(), &QProcess::readyReadStandardError,
this, &AbstractProcessStep::processReadyReadStdError);
connect(m_process.get(), static_cast<void (QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished),
this, &AbstractProcessStep::slotProcessFinished);
m_process->start();
if (!m_process->waitForStarted()) {
processStartupFailed();
m_process.reset();
m_outputParserChain.reset();
reportRunResult(fi, false);
return;
}
processStarted();
m_timer.start();
}
void AbstractProcessStep::cleanUp(QProcess *process)
{
// The process has finished, leftover data is read in processFinished
processFinished(process->exitCode(), process->exitStatus());
const bool returnValue = processSucceeded(process->exitCode(), process->exitStatus()) || m_ignoreReturnValue;
m_outputParserChain.reset();
m_process.reset();
// Report result
reportRunResult(*m_futureInterface, returnValue);
}
/*!
Called after the process is started.
The default implementation adds a process-started message to the output
message.
*/
void AbstractProcessStep::processStarted()
{
emit addOutput(tr("Starting: \"%1\" %2")
.arg(QDir::toNativeSeparators(m_param.effectiveCommand()),
m_param.prettyArguments()),
BuildStep::OutputFormat::NormalMessage);
}
/*!
Called after the process is finished.
The default implementation adds a line to the output window.
*/
void AbstractProcessStep::processFinished(int exitCode, QProcess::ExitStatus status)
{
if (m_outputParserChain)
m_outputParserChain->flush();
QString command = QDir::toNativeSeparators(m_param.effectiveCommand());
if (status == QProcess::NormalExit && exitCode == 0) {
emit addOutput(tr("The process \"%1\" exited normally.").arg(command),
BuildStep::OutputFormat::NormalMessage);
} else if (status == QProcess::NormalExit) {
emit addOutput(tr("The process \"%1\" exited with code %2.")
.arg(command, QString::number(exitCode)),
BuildStep::OutputFormat::ErrorMessage);
} else {
emit addOutput(tr("The process \"%1\" crashed.").arg(command), BuildStep::OutputFormat::ErrorMessage);
}
}
/*!
Called if the process could not be started.
By default, adds a message to the output window.
*/
void AbstractProcessStep::processStartupFailed()
{
emit addOutput(tr("Could not start process \"%1\" %2")
.arg(QDir::toNativeSeparators(m_param.effectiveCommand()),
m_param.prettyArguments()),
BuildStep::OutputFormat::ErrorMessage);
m_timer.stop();
}
/*!
Called to test whether a process succeeded or not.
*/
bool AbstractProcessStep::processSucceeded(int exitCode, QProcess::ExitStatus status)
{
if (outputParser() && outputParser()->hasFatalErrors())
return false;
return exitCode == 0 && status == QProcess::NormalExit;
}
void AbstractProcessStep::processReadyReadStdOutput()
{
if (!m_process)
return;
m_process->setReadChannel(QProcess::StandardOutput);
while (m_process->canReadLine()) {
QString line = QString::fromLocal8Bit(m_process->readLine());
stdOutput(line);
}
}
/*!
Called for each line of output on stdOut().
The default implementation adds the line to the application output window.
*/
void AbstractProcessStep::stdOutput(const QString &line)
{
if (m_outputParserChain)
m_outputParserChain->stdOutput(line);
emit addOutput(line, BuildStep::OutputFormat::Stdout, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::processReadyReadStdError()
{
if (!m_process)
return;
m_process->setReadChannel(QProcess::StandardError);
while (m_process->canReadLine()) {
QString line = QString::fromLocal8Bit(m_process->readLine());
stdError(line);
}
}
/*!
Called for each line of output on StdErrror().
The default implementation adds the line to the application output window.
*/
void AbstractProcessStep::stdError(const QString &line)
{
if (m_outputParserChain)
m_outputParserChain->stdError(line);
emit addOutput(line, BuildStep::OutputFormat::Stderr, BuildStep::DontAppendNewline);
}
QFutureInterface<bool> *AbstractProcessStep::futureInterface() const
{
return m_futureInterface;
}
void AbstractProcessStep::checkForCancel()
{
if (m_futureInterface->isCanceled() && m_timer.isActive()) {
m_timer.stop();
Core::Reaper::reap(m_process.release());
}
}
void AbstractProcessStep::taskAdded(const Task &task, int linkedOutputLines, int skipLines)
{
// Do not bother to report issues if we do not care about the results of
// the buildstep anyway:
if (m_ignoreReturnValue)
return;
// flush out any pending tasks before proceeding:
if (!m_skipFlush && m_outputParserChain) {
m_skipFlush = true;
m_outputParserChain->flush();
m_skipFlush = false;
}
Task editable(task);
QString filePath = task.file.toString();
if (!filePath.isEmpty() && !filePath.startsWith('<') && !QDir::isAbsolutePath(filePath)) {
// We have no save way to decide which file in which subfolder
// is meant. Therefore we apply following heuristics:
// 1. Check if file is unique in whole project
// 2. Otherwise try again without any ../
// 3. give up.
QList<QFileInfo> possibleFiles;
QString fileName = Utils::FileName::fromString(filePath).fileName();
foreach (const Utils::FileName &file, project()->files(Project::AllFiles)) {
QFileInfo candidate = file.toFileInfo();
if (candidate.fileName() == fileName)
possibleFiles << candidate;
}
if (possibleFiles.count() == 1) {
editable.file = Utils::FileName(possibleFiles.first());
} else {
// More then one filename, so do a better compare
// Chop of any "../"
while (filePath.startsWith("../"))
filePath.remove(0, 3);
int count = 0;
QString possibleFilePath;
foreach (const QFileInfo &fi, possibleFiles) {
if (fi.filePath().endsWith(filePath)) {
possibleFilePath = fi.filePath();
++count;
}
}
if (count == 1)
editable.file = Utils::FileName::fromString(possibleFilePath);
else
qWarning() << "Could not find absolute location of file " << filePath;
}
}
emit addTask(editable, linkedOutputLines, skipLines);
}
void AbstractProcessStep::outputAdded(const QString &string, BuildStep::OutputFormat format)
{
emit addOutput(string, format, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::slotProcessFinished(int, QProcess::ExitStatus)
{
m_timer.stop();
QProcess *process = m_process.get();
if (!process) // Happens when the process was canceled and handed over to the Reaper.
process = qobject_cast<QProcess *>(sender()); // The process was canceled!
const QString stdErrLine = process ? QString::fromLocal8Bit(process->readAllStandardError()) : QString();
for (const QString &l : stdErrLine.split('\n'))
stdError(l);
const QString stdOutLine = process ? QString::fromLocal8Bit(process->readAllStandardOutput()) : QString();
for (const QString &l : stdOutLine.split('\n'))
stdError(l);
cleanUp(process);
}
|
package ru.fizteh.fivt.students.Soshilov.junit;
/**
* Created with IntelliJ IDEA.
* User: soshikan
* Date: 23 October 2014
* Time: 1:08
*/
public final class Exit implements Command {
/**
* Stop working with database.
* @param args Commands that were entered.
* @param db Our main table.
*/
@Override
public void execute(final String[] args, final DataBaseTableProvider db) {
boolean isExitPossible = db.isExitPossible();
if (isExitPossible) {
try {
db.write();
} catch (Exception ex) {
System.err.println(ex.getMessage());
System.exit(1);
}
System.exit(0);
} else {
System.out.println("commit or rollback changes");
}
}
}
|
require 'oriented'
class Model
include Oriented::Vertex
property :name
has_n(:stylists)
has_one(:drug_dealer).from(:clients)
has_n(:requests).from(:target)
end
class DrugDealer
include Oriented::Vertex
property :name
property :product
has_n(:clients)
end
class Stylist
include Oriented::Vertex
property :name
has_n(:pieces_of_gossip)
has_one(:drug_dealer).from(:clients)
has_n(:requests).from(:guru)
end
class ModelingRequest
include Oriented::Vertex
has_one(:target)
has_one(:issuer)
has_one(:guru)
end
class Agency
include Oriented::Vertex
has_n(:requests).from(:issuer)
has_n(:models)
end
|
import React, { FC } from 'react';
import styled from 'styled-components';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import { useTranslation } from 'react-i18next';
import logo from '../static/logo.svg';
interface Props {
onSelectFiles: () => void;
onOpenSettings: () => void;
}
const Container = styled.div`
height: 5rem;
width: 100%;
padding: 0 2rem;
display: flex;
flex-direction: row;
justify-content: space-between;
`;
const Logo = styled.div`
align-self: center;
width: 14rem;
img {
width: 3.5rem;
filter: grayscale(1);
opacity: 0.5;
transition: opacity 0.1s ease-in, filter 0.1s ease-in;
cursor: pointer;
&:hover {
filter: grayscale(0);
opacity: 1;
}
}
`;
const Middle = styled.div`
display: flex;
flex-direction: column;
justify-items: center;
align-items: center;
`;
const Links = styled.div`
display: flex;
justify-content: flex-end;
align-self: center;
width: 14rem;
`;
const Link = styled.a`
padding: 1rem;
font-size: 1rem;
font-weight: 500;
color: ${({ theme }) => theme.palette.text.secondary};
text-decoration: none;
cursor: pointer;
&:hover {
color: ${({ theme }) => theme.palette.secondary.main};
}
`;
const Footer: FC<Props> = ({ onSelectFiles, onOpenSettings }) => {
const { t } = useTranslation();
return (
<Container>
<Logo>
<a href="https://octosign.com" target="blank">
<img src={logo} alt={t('Logo')} />
</a>
</Logo>
<Middle>
<Button variant="contained" color="primary" onClick={onSelectFiles}>
{t('Select files')}
</Button>
<Box m={1} fontSize="1rem" fontWeight="500" color="text.secondary">
{t('or drag and drop your files anywhere')}
</Box>
</Middle>
<Links>
<Link href="https://octosign.com/help" target="blank">
{t('Help')}
</Link>
<Link href="#settings" onClick={onOpenSettings}>
{t('Settings')}
</Link>
</Links>
</Container>
);
};
export default React.memo(Footer);
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protob.proto
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_message "protob.Version" do
optional :value, :string, 1
end
add_message "protob.Void" do
end
add_message "protob.Title" do
optional :id, :int32, 1
optional :archive_id, :string, 2
optional :path, :string, 3
optional :lang, :string, 4
end
add_message "protob.TitlesOpt" do
end
add_message "protob.Page" do
optional :id, :string, 1
optional :offset, :int32, 2
optional :text, :bytes, 3
optional :title_id, :string, 4
optional :title_path, :string, 5
repeated :names, :message, 6, "protob.NameString"
end
add_message "protob.PagesOpt" do
optional :with_text, :bool, 1
repeated :title_ids, :int32, 2
end
add_message "protob.NameString" do
optional :value, :string, 1
optional :odds, :float, 2
optional :path, :string, 3
optional :curated, :bool, 4
optional :edit_distance, :int32, 5
optional :edit_distance_stem, :int32, 6
optional :source_id, :int32, 7
optional :match, :enum, 8, "protob.MatchType"
optional :offset_start, :int32, 9
optional :offset_end, :int32, 10
end
add_enum "protob.MatchType" do
value :NONE, 0
value :EXACT, 1
value :CANONICAL_EXACT, 2
value :CANONICAL_FUZZY, 3
value :PARTIAL_EXACT, 4
value :PARTIAL_FUZZY, 5
end
end
module Protob
Version = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.Version").msgclass
Void = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.Void").msgclass
Title = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.Title").msgclass
TitlesOpt = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.TitlesOpt").msgclass
Page = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.Page").msgclass
PagesOpt = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.PagesOpt").msgclass
NameString = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.NameString").msgclass
MatchType = Google::Protobuf::DescriptorPool.generated_pool.lookup("protob.MatchType").enummodule
end
|
---
title: "How to Choose the Journal That's Right for Your Study"
source: "New"
date: "2021-07-27"
categories:
- Recommendation
tags:
- Writing research papers
output: html_document
---
An easy to read guide on picking the right journal to send your publication to.
<!--more-->
How to Choose the Journal That's Right for Your Study. PLOS. Available in [html format][plos].
[plos]: https://plos.org/resource/how-to-choose-journal/
|
package com.codingblocks;
import java.util.ArrayList;
public class Examples {
public static void main(String[] args) {
ArrayList list = new ArrayList();
System.out.println(list.size());
list.add(1);
list.add(4);
list.add(7);
list.add(9);
System.out.println(list.size());
System.out.println(list.get(2));
list.set(2, 77);
System.out.println(list.get(2));
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
|
import {EntityPropertyType} from '@/erdiagram/parser/types/entity-relationship-model-types';
import {
TableColumnDescriptor,
TableReferenceDescriptor
} from '@/erdiagram/converter/database/model/database-model-types';
import OracleColumnCodeGenerator
from '@/erdiagram/converter/database/code-converter/sql/dialect/oracle/column/OracleColumnCodeGenerator';
import CaseConverter from '@/erdiagram/converter/common/case-format/CaseConverter';
import {ForeignKeyColumnCode} from '@/erdiagram/converter/database/code-converter/sql/dialect/common/sql-script-types';
import SqlForeignColumnCodeGenerator
from '@/erdiagram/converter/database/code-converter/sql/dialect/common/column/SqlForeignColumnCodeGenerator';
export default class OracleForeignColumnCodeGenerator implements SqlForeignColumnCodeGenerator {
constructor(
private readonly columnCodeGenerator: OracleColumnCodeGenerator,
private readonly tableNameCaseConverter: CaseConverter,
private readonly columnNameCaseConverter: CaseConverter
) {
}
public generateForeignColumnCode(outputTableName: string, reference: TableReferenceDescriptor): ForeignKeyColumnCode {
const columnDescriptor = this.createForeignKeyColumnDescriptor(reference);
const {
columnLine,
uniqueConstraintLine
} = this.columnCodeGenerator.generateColumnCode(outputTableName, columnDescriptor);
return {
columnLine,
uniqueConstraintLine,
fkConstraintLine: this.createForeignKeyConstraint(outputTableName, reference)
};
}
private createForeignKeyColumnDescriptor(reference: TableReferenceDescriptor): TableColumnDescriptor {
const {
columnName,
notNull,
unique
} = reference;
return {
name: columnName,
type: EntityPropertyType.IDENTITY,
length: [],
notNull,
unique
};
}
private createForeignKeyConstraint(outputTableName: string, reference: TableReferenceDescriptor) {
const outputColumnName = this.columnNameCaseConverter.convertCase(reference.columnName);
const outputTargetTableName = this.tableNameCaseConverter.convertCase(reference.targetTableName);
const outputTargetColumnName = this.columnNameCaseConverter.convertCase(reference.targetTableIdentityColumnName);
return `CONSTRAINT "${outputTableName}_${outputColumnName}_FK" FOREIGN KEY ("${outputColumnName}")`
+ ` REFERENCES "${outputTargetTableName}" ("${outputTargetColumnName}")`;
}
}
|
# Goal: Simulate a dataset from the OLS model and obtain
# obtain OLS estimates for it.
x <- runif(100, 0, 10) # 100 draws from U(0,10)
y <- 2 + 3*x + rnorm(100) # beta = [2, 3] and sigma = 1
# You want to just look at OLS results?
summary(lm(y ~ x))
# Suppose x and y were packed together in a data frame --
D <- data.frame(x,y)
summary(lm(y ~ x, D))
# Full and elaborate steps --
d <- lm(y ~ x)
# Learn about this object by saying ?lm and str(d)
# Compact model results --
print(d)
# Pretty graphics for regression diagnostics --
par(mfrow=c(2,2))
plot(d)
d <- summary(d)
# Detailed model results --
print(d)
# Learn about this object by saying ?summary.lm and by saying str(d)
cat("OLS gave slope of ", d$coefficients[2,1],
"and a error sigma of ", d$sigma, "\n")
## I need to drop down to a smaller dataset now --
x <- runif(10)
y <- 2 + 3*x + rnorm(10)
m <- lm(y ~ x)
# Now R supplies a wide range of generic functions which extract
# useful things out of the result of estimation of many kinds of models.
residuals(m)
fitted(m)
AIC(m)
AIC(m, k=log(10)) # SBC
vcov(m)
logLik(m)
|
// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use
// of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package main
import (
"context"
"os"
"time"
"github.com/flosch/pongo2"
"github.com/google/safebrowsing"
)
var safeBrowser *safebrowsing.SafeBrowser
func init() {
pongo2.RegisterFilter("threatdefinition", safeTypeToStringFilter)
}
func initSafeBrowsing() {
if conf.SafeBrowsing.APIKey == "" {
return
}
debug.Println("safebrowsing support enabled, initializing")
// Validate the part of the config that we can.
if conf.SafeBrowsing.UpdatePeriod < 30*time.Minute {
// Minimum 30m.
conf.SafeBrowsing.UpdatePeriod = 30 * time.Minute
}
if conf.SafeBrowsing.UpdatePeriod > 168*time.Hour {
// Maximum 7 days.
conf.SafeBrowsing.UpdatePeriod = 168 * time.Minute
}
var err error
safeBrowser, err = safebrowsing.NewSafeBrowser(safebrowsing.Config{
APIKey: conf.SafeBrowsing.APIKey,
DBPath: conf.SafeBrowsing.DBPath,
UpdatePeriod: conf.SafeBrowsing.UpdatePeriod,
RequestTimeout: 15 * time.Second,
Logger: os.Stdout,
})
if err != nil {
debug.Fatalf("error initializing google safebrowsing: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
if err = safeBrowser.WaitUntilReady(ctx); err != nil {
debug.Fatalf("error initializing google safebrowsing: %v", err)
}
}
func safeTypeToString(t safebrowsing.ThreatType) string {
switch t {
case safebrowsing.ThreatType_Malware:
return "Site is known for hosting malware"
case safebrowsing.ThreatType_PotentiallyHarmfulApplication:
return "Site provides potentially harmful applications"
case safebrowsing.ThreatType_SocialEngineering:
return "Site is known for social engineering"
case safebrowsing.ThreatType_UnwantedSoftware:
return "Site provides unwanted software"
}
return "Unknown threat"
}
func safeTypeToStringFilter(in, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
input := in.Integer()
t := safebrowsing.ThreatType(input)
return pongo2.AsValue(safeTypeToString(t)), nil
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Apache.NMS.Stomp.Util
{
public class IdGenerator
{
private static readonly String UNIQUE_STUB;
private static int instanceCount;
private static readonly String hostName;
private readonly String seed;
private long sequence;
static IdGenerator()
{
String stub = "-1-" + DateTime.Now.Ticks;
hostName = "localhost";
try
{
hostName = Dns.GetHostName();
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
Socket tempSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
tempSocket.Bind(endPoint);
stub = "-" + ((IPEndPoint)tempSocket.LocalEndPoint).Port + "-" + DateTime.Now.Ticks + "-";
Thread.Sleep(100);
tempSocket.Close();
}
catch(Exception ioe)
{
Tracer.Warn("could not generate unique stub: " + ioe.Message);
}
UNIQUE_STUB = stub;
}
/**
* Construct an IdGenerator
*/
public IdGenerator(String prefix)
{
lock(UNIQUE_STUB)
{
this.seed = prefix + UNIQUE_STUB + (instanceCount++) + ":";
}
}
public IdGenerator() : this("ID:" + hostName)
{
}
/// <summary>
/// As we have to find the hostname as a side-affect of generating a unique
/// stub, we allow it's easy retrevial here
/// </summary>
public static String HostName
{
get { return hostName; }
}
/// <summary>
/// Generate a Unique Id
/// </summary>
public String GenerateId()
{
lock(UNIQUE_STUB)
{
return this.seed + (this.sequence++);
}
}
/// <summary>
/// Generate a unique ID - that is friendly for a URL or file system
/// </summary>
public String GenerateSanitizedId()
{
String result = GenerateId();
result = result.Replace(':', '-');
result = result.Replace('_', '-');
result = result.Replace('.', '-');
return result;
}
/// <summary>
/// From a generated id - return the seed (i.e. minus the count)
/// </summary>
public static String GetSeedFromId(String id)
{
String result = id;
if(id != null)
{
int index = id.LastIndexOf(':');
if(index > 0 && (index + 1) < id.Length)
{
result = id.Substring(0, index + 1);
}
}
return result;
}
/// <summary>
/// From a generated id - return the generator count
/// </summary>
public static long GetSequenceFromId(String id)
{
long result = -1;
if(id != null)
{
int index = id.LastIndexOf(':');
if(index > 0 && (index + 1) < id.Length)
{
String numStr = id.Substring(index + 1, id.Length);
result = Int64.Parse(numStr);
}
}
return result;
}
/// <summary>
/// Does a proper compare on the ids
/// </summary>
public static int Compare(String id1, String id2)
{
int result = -1;
String seed1 = IdGenerator.GetSeedFromId(id1);
String seed2 = IdGenerator.GetSeedFromId(id2);
if(seed1 != null && seed2 != null)
{
result = seed1.CompareTo(seed2);
if(result == 0)
{
long count1 = IdGenerator.GetSequenceFromId(id1);
long count2 = IdGenerator.GetSequenceFromId(id2);
result = (int)(count1 - count2);
}
}
return result;
}
}
}
|
<?php
namespace Tests\Unit;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\Models\Nave;
use App\Models\Itinerario;
use App\Models\Ruta;
use Illuminate\Database\Eloquent\Collection;
class NaveTest extends TestCase
{
use RefreshDatabase;
public function test_una_nave_posee_uno_o_varios_itinerarios()
{
$ruta = Ruta::factory()->create();
$nave = Nave::factory()->create();
$itinerario = Itinerario::factory()->create();
$this->assertInstanceOf(Collection::class, $nave->itinerarios);
}
}
|
app.controller('serviceCtrl', function($scope, demoService) {
console.log(demoService.serviceFN());
$scope.dataFromService = demoService.serviceFN();
});
app.controller('factoryCtrl', function($scope, demoFactory) {
console.log(demoFactory.factoryFN());
$scope.dataFromFactory = demoFactory.factoryFN();
});
|
# ABC110 C. String Transformation
## @2020-04-26
わからなかった。
300点ではゲキムズだと思う。
ていうかなんで過去の自分は解けたのか?謎。
**1対1の写像が成立するかどうかを調べる問題。**
。。なんだけど、正直深く理解しきれていない。。
### ポイント
- PDFにある通り「1対1の置換表を作ることを目標にする」と考えるとわかりやすいかも
- 順方向と逆方向の変換両方をケアして、両方に矛盾がないかをチェックしないといけない
### chokudaiさんの解説
[動画のこのあたり](https://youtu.be/gdQxKESnXKs?t=1923)が具体例レベルで一番わかり易い気がする。
|
export 'post_details_reactions_list/index.dart';
export 'post_comments_list/index.dart';
export 'post_details_bottom_bar/index.dart';
|
SCRIPT_DIR=$(cd $(dirname $0); pwd)
cd "$SCRIPT_DIR"
# SQLファイルを作成する。
echo "create table T(C text);
insert into T values('AAA');
.tables
.headers on
.mode column
select * from T;
" > create_dot.sql
# `.read`してテーブルやレコードを確認する。
sqlite3 :memory: ".read create_dot.sql"
|
$(document).ready(function(){
alert("gola");
$("#comm").hide();
$("#comentar").on("click", function(){
$("#comm").show();
})
})
|
#!/bin/sh
# set -e
vms=( "myvm1"
"myvm2" )
i=0
for vm in ${vms[@]:0:2}
do
docker-machine env ${vm}
eval $(docker-machine env ${vm})
HOST_IP=$(docker-machine ip ${vm})
echo ${HOST_IP}
# echo $PWD
docker build -f Dockerfile -t haproxy-rabbitmq-cluster:latest .
let "i++"
done
echo "Script completed..."
|
Spree::Shipment.class_eval do
has_many :notes, class_name: 'ShipmentNote', foreign_key: 'shipment_id'
end
|
<?php
declare(strict_types=1);
/*
* This file is part of Clivern Memcached Bundle
* (c) Clivern <hello@clivern.com>
*/
namespace Tests;
use Clivern\Memcached\MemcachedClient;
use PHPUnit\Framework\TestCase;
class MemcachedClientTest extends TestCase
{
private $memcachedClient;
/**
* Setup.
*/
protected function setUp(): void
{
$this->memcachedClient = $this->createMock(MemcachedClient::class);
$this->memcachedClient->method('quit')
->willReturn(true);
$this->memcachedClient->method('ping')
->willReturn(true);
$this->memcachedClient->method('add')
->willReturn(true);
$this->memcachedClient->method('set')
->willReturn(true);
$this->memcachedClient->method('replace')
->willReturn(true);
$this->memcachedClient->method('get')
->willReturn(true);
$this->memcachedClient->method('increment')
->willReturn(true);
}
/**
* Test ping.
*/
public function testPing()
{
self::assertTrue($this->memcachedClient->ping());
}
/**
* Test add.
*/
public function testAdd()
{
self::assertTrue($this->memcachedClient->add('key', 'value'));
}
/**
* Test set.
*/
public function testSet()
{
self::assertTrue($this->memcachedClient->set('key', 'value'));
}
/**
* Test replace.
*/
public function testReplace()
{
self::assertTrue($this->memcachedClient->replace('key', 'value'));
}
/**
* Test get.
*/
public function testGet()
{
self::assertTrue($this->memcachedClient->get('key'));
}
/**
* Test increment.
*/
public function testIncrement()
{
self::assertTrue($this->memcachedClient->increment('key'));
}
/**
* Test quit.
*/
public function testQuit()
{
self::assertTrue($this->memcachedClient->quit());
}
}
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4s
import org.junit.runner.RunWith
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4s.Implicits._
import org.nd4j.linalg.factory.Nd4j
import org.scalatest.junit.JUnitRunner
import org.scalatest.{ FlatSpec, Matchers }
@RunWith(classOf[JUnitRunner])
class OperatableNDArrayTest extends FlatSpec with Matchers {
"RichNDArray" should "use the apply method to access values" in {
// -- 2D array
val nd2 = Nd4j.create(Array[Double](1, 2, 3, 4), Array[Int](1, 4): _*)
nd2.get(0) should be(1)
nd2.get(0, 3) should be(4)
// -- 3D array
val nd3 = Nd4j.create(Array[Double](1, 2, 3, 4, 5, 6, 7, 8), Array[Int](2, 2, 2): _*)
nd3.get(0, 0, 0) should be(1)
nd3.get(1, 1, 1) should be(8)
}
it should "use transpose abbreviation" in {
val nd1 = Nd4j.create(Array[Double](1, 2, 3), Array(3, 1): _*)
nd1.shape should equal(Array(3, 1))
val nd1t = nd1.T
nd1t.shape should equal(Array(1, 3))
}
it should "add correctly" in {
val a = Nd4j.create(Array[Double](1, 2, 3, 4, 5, 6, 7, 8), Array(2, 2, 2): _*)
val b = a + 100
a.get(0, 0, 0) should be(1)
b.get(0, 0, 0) should be(101)
a += 1
a.get(0, 0, 0) should be(2)
}
it should "subtract correctly" in {
val a = Nd4j.create(Array[Double](1, 2, 3, 4, 5, 6, 7, 8), Array(2, 2, 2): _*)
val b = a - 100
a.get(0, 0, 0) should be(1)
b.get(0, 0, 0) should be(-99)
a -= 1
a.get(0, 0, 0) should be(0)
val c = Nd4j.create(Array[Double](1, 2))
val d = c - c
d.get(0) should be(0)
d.get(1) should be(0)
}
it should "divide correctly" in {
val a = Nd4j.create(Array[Double](1, 2, 3, 4, 5, 6, 7, 8), Array(2, 2, 2): _*)
val b = a / a
a.get(1, 1, 1) should be(8)
b.get(1, 1, 1) should be(1)
a /= a
a.get(1, 1, 1) should be(1)
}
it should "element-by-element multiply correctly" in {
val a = Nd4j.create(Array[Double](1, 2, 3, 4), Array(4, 1): _*)
val b = a * a
a.get(3) should be(4) // [1.0, 2.0, 3.0, 4.0
b.get(3) should be(16) // [1.0 ,4.0 ,9.0 ,16.0]
a *= 5 // [5.0 ,10.0 ,15.0 ,20.0]
a.get(0) should be(5)
}
it should "use the update method to mutate values" in {
val nd3 = Nd4j.create(Array[Double](1, 2, 3, 4, 5, 6, 7, 8), Array(2, 2, 2): _*)
nd3(0) = 11
nd3.get(0) should be(11)
val idx = Array(1, 1, 1)
nd3(idx) = 100
nd3.get(idx) should be(100)
}
it should "use === for equality comparisons" in {
val a = Nd4j.create(Array[Double](1, 2))
val b = Nd4j.create(Array[Double](1, 2))
val c = a === b
c.get(0) should be(1)
c.get(1) should be(1)
val d = Nd4j.create(Array[Double](10, 20))
val e = a === d
e.get(0) should be(0)
e.get(1) should be(0)
val f = a === 1 // === from our DSL
f.get(0) should be(1)
f.get(1) should be(0)
}
it should "use - prefix for negation" in {
val a = Nd4j.create(Array[Float](1, 3))
val b = -a
b.get(0) should be(-1)
b.get(1) should be(-3)
}
it should "not prevent any2stringadd syntax" in {
val s: String = Nd4j.create(2, 2) + ""
}
"Sum function" should "choose return value depending on INDArray type" in {
val ndArray =
Array(
Array(1, 2),
Array(4, 5)
).toNDArray
//return Double in real NDArray at default
ndArray.get(0) shouldBe a[java.lang.Double]
val sumValue = ndArray.sumT
sumValue shouldBe a[java.lang.Double]
//switch return value with passing corresponding evidence explicitly
val sumValueInFloatExplicit = ndArray.sumT(FloatNDArrayEvidence)
sumValueInFloatExplicit shouldBe a[java.lang.Float]
//switch return value with declaring implicit value but explicit one would be more readable.
import org.nd4s.Evidences.float
val sumValueInFloatImplicit = ndArray.sumT
sumValueInFloatImplicit shouldBe a[java.lang.Float]
}
it should "provide matrix multiplicaton operations " in {
val a = Nd4j.create(Array[Float](4, 6, 5, 7)).reshape(2, 2)
val b = Nd4j.create(Array[Float](1, 3, 4, 8)).reshape(2, 2)
a **= b
val expected = Array[Float](28.0000f, 60.0000f, 33.0000f, 71.0000f).toNDArray.reshape(2, 2)
a shouldBe expected
}
it should "provide matrix division operations " in {
val a = Nd4j.create(Array[Float](4, 6, 5, 7)).reshape(2, 2)
a /= 12
a.get(0) shouldBe (0.3333 +- 0.0001)
a.get(1) shouldBe (0.5 +- 0.0001)
a.get(2) shouldBe (0.4167 +- 0.0001)
a.get(3) shouldBe (0.5833 +- 0.0001)
val b = Nd4j.create(Array[Float](4, 6, 5, 7)).reshape(2, 2)
b %= 12
b.get(0) shouldBe (4.0)
b.get(1) shouldBe (6.0)
b.get(2) shouldBe (5.0)
b.get(3) shouldBe (-5.0)
val c = Nd4j.create(Array[Float](4, 6, 5, 7)).reshape(2, 2)
c \= 12
c.get(0) shouldBe (3.0)
c.get(1) shouldBe (2.0)
c.get(2) shouldBe (2.4000 +- 0.0001)
c.get(3) shouldBe (1.7143 +- 0.0001)
}
it should "provide math operations for vectors " in {
val a = Nd4j.create(Array[Float](4, 6))
val b = Nd4j.create(Array[Float](1, 3))
a /= b
val expected1 = Nd4j.create(Array[Float](4, 2))
assert(a == expected1)
a *= b
val expected2 = Nd4j.create(Array[Float](4, 6))
assert(a == expected2)
a += b
val expected3 = Nd4j.create(Array[Float](5, 9))
assert(a == expected3)
a -= b
val expected4 = Nd4j.create(Array[Float](4, 6))
assert(a == expected4)
a \= b
val expected5 = Array[Float](0.25f, 0.5f).toNDArray
assert(a == expected5)
val c = a * b
val expected6 = Array[Float](0.25f, 1.5f).toNDArray
assert(c == expected6)
val d = a + b
val expected7 = Array[Float](1.25f, 3.5f).toNDArray
assert(d == expected7)
val e = a / b
e.get(0) should be(0.2500 +- 0.0001)
e.get(1) should be(0.1667 +- 0.0001)
val f = a \ b
f.get(0) should be(4.0 +- 0.0001)
f.get(1) should be(6.0 +- 0.0001)
val g = a ** b
g.get(0) shouldBe 1.7500
val h = a dot b
g.get(0) shouldBe 1.7500
d.sumT shouldBe 4.75
d.meanT shouldBe 2.375
d.norm1T shouldBe 4.75
d.maxT shouldBe 3.5
d.minT shouldBe 1.25
d.prodT shouldBe 4.375
d.varT shouldBe 2.53125
d.norm2T should be(3.7165 +- 0.0001)
d.stdT should be(1.5909 +- 0.0001)
}
it should "provide arithmetic ops calls on integers " in {
val ndArray = Array(1, 2).toNDArray
val c = ndArray + 5
c shouldBe Array(6, 7).toNDArray
val d = 5 + ndArray
c shouldBe Array(6, 7).toNDArray
}
it should "broadcast add ops calls on vectors with different length " in {
val x = Array(1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f).mkNDArray(Array(3, 5))
val y = Array[Float](1f, 1f, 1f, 1f, 1f).toNDArray
val e = x + 1f.toScalar
assert((x + y) == e)
val x1 = Array(1f, 1f, 1f, 1f, 1f, 1f).mkNDArray(Array(3, 1, 2))
val y1 = Array[Float](1f, 1f, 1f, 1f).toNDArray.reshape(2, 2)
val t1 = Array(1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f).mkNDArray(Array(3, 2, 2))
val e1 = t1 + 1f
assert((x1 + y1) == e1)
val e2 = 1f + t1
assert(e1 == e2)
}
it should "broadcast multiplication ops " in {
val x1 = Array(1f, 1f, 1f, 1f, 1f, 1f).mkNDArray(Array(3, 1, 2))
val y1 = Array[Float](1f, 1f, 1f, 1f).toNDArray.reshape(2, 2)
val t1 = Array(1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f).mkNDArray(Array(3, 2, 2))
val e1 = t1 * 1f
assert((x1 * y1) == e1)
val e2 = 1f * t1
assert(e1 == e2)
}
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##############################
# import dependencies
##############################
import pickle
import argparse
import numpy as np
from pathlib import Path
from collections import Counter
from keras.preprocessing.text import text_to_word_sequence
from keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
##############################
# define key functions
##############################
def read_order(files):
# read in files
corpus = []
for i in range(len(files)):
with open(files[i], "r", encoding="latin-1") as reader:
corpus.append(reader.readlines())
corpus = [[el.strip() for el in ls] for ls in corpus]
corpus = [" ".join(ls) for ls in corpus]
return corpus
def tokenize(obj):
return [text_to_word_sequence(el) for el in obj]
def integerEncode(vocab_size=5000, padding_words=500, padding_chars=1000):
ham = [filename for filename in Path('./data/enron').glob('**/*ham.txt')]
spam = [filename for filename in Path('./data/enron').glob('**/*spam.txt')]
hamCorpus = read_order(ham)
spamCorpus = read_order(spam)
label_ham = [0 for _ in range(len(hamCorpus))]
label_spam = [1 for _ in range(len(spamCorpus))]
# separate into training, test
ham_train, ham_test, ham_train_labels, ham_test_labels = train_test_split(
hamCorpus, label_ham, test_size=0.33, random_state=42)
spam_train, spam_test, spam_train_labels, spam_test_labels = train_test_split(
spamCorpus, label_spam, test_size=0.33, random_state=42)
# re-separate into training and validation
ham_train, ham_valid, ham_train_labels, ham_valid_labels = train_test_split(
ham_train, ham_train_labels, test_size=0.15, random_state=42)
spam_train, spam_valid, spam_train_labels, spam_valid_labels = train_test_split(
spam_train, spam_train_labels, test_size=0.15, random_state=42)
# create train dataset
X_train = tokenize(ham_train + spam_train)
y_train = np.array(ham_train_labels + spam_train_labels)
# create validation dataset
X_valid = tokenize(ham_valid + spam_valid)
y_valid = np.array(ham_valid_labels + spam_valid_labels)
# create test dataset
X_test = tokenize(ham_test + spam_test)
y_test = np.array(ham_test_labels + spam_test_labels)
# save labels which will stay fixed
np.save("./data/rnn/y_train.npy", y_train)
np.save("./data/rnn/y_valid.npy", y_valid)
np.save("./data/rnn/y_test.npy", y_test)
# integer encode data from tokens perspective
tokens_flat = [token for el in X_train for token in el]
tokens_common = Counter(tokens_flat).most_common()
tokens_common = dict(tokens_common[:vocab_size - 1])
for i, key in enumerate(tokens_common.keys()):
tokens_common[key] = i + 1
# encode training set
X_train = pad_sequences(
[[tokens_common[el] if el in tokens_common.keys() else 0 for el in ls]
for ls in X_train],
maxlen=padding_words)
# encode validation set
X_valid = pad_sequences(
[[tokens_common[el] if el in tokens_common.keys() else 0 for el in ls]
for ls in X_valid],
maxlen=padding_words)
# encode test set
X_test = pad_sequences(
[[tokens_common[el] if el in tokens_common.keys() else 0 for el in ls]
for ls in X_test],
maxlen=padding_words)
# save all numpy arrays to file
np.save("./data/rnn/words/X_train.npy", X_train)
np.save("./data/rnn/words/X_valid.npy", X_valid)
np.save("./data/rnn/words/X_test.npy", X_test)
# save indexing dictionary to file
with open("./data/rnn/words/integer_index_tokens.pickle", "wb") as f:
pickle.dump(tokens_common, f, protocol=pickle.HIGHEST_PROTOCOL)
# integer encode data from character perspective
X_train = ham_train + spam_train
X_valid = ham_valid + spam_valid
X_test = ham_test + spam_test
# clean word index by removing hexadecimal characters
tokens_flat = [char.lower() for el in X_train for char in el]
tokens_common = dict(Counter(tokens_flat).most_common())
for key in list(tokens_common.keys()):
if tokens_common[key] < 2000:
tokens_common.pop(key, None)
for i, key in enumerate(tokens_common):
tokens_common[key] = i + 1
# encode training set
X_train = pad_sequences([[
tokens_common[el.lower()] if el.lower() in tokens_common.keys() else 0
for el in ls
] for ls in X_train],
maxlen=padding_chars)
# encode validation set
X_valid = pad_sequences([[
tokens_common[el.lower()] if el.lower() in tokens_common.keys() else 0
for el in ls
] for ls in X_valid],
maxlen=padding_chars)
# encode test set
X_test = pad_sequences([[
tokens_common[el.lower()] if el.lower() in tokens_common.keys() else 0
for el in ls
] for ls in X_test],
maxlen=padding_chars)
# save all numpy arrays to file
np.save("./data/rnn/char/X_train.npy", X_train)
np.save("./data/rnn/char/X_valid.npy", X_valid)
np.save("./data/rnn/char/X_test.npy", X_test)
# save indexing dictionary to file
with open("./data/rnn/char/integer_index_char.pickle", "wb") as f:
pickle.dump(tokens_common, f, protocol=pickle.HIGHEST_PROTOCOL)
##############################
# main command call
##############################
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--vocab-size",
type=int,
default=5000,
help="size of vocabulary used in word vector embedding <default:5000>")
parser.add_argument(
"--padding-tokens",
type=int,
default=500,
help="maximum length of email padding for tokens <default:500>")
parser.add_argument(
"--padding-char",
type=int,
default=1000,
help="maximum length of email padding for characters <default:1000>")
args = parser.parse_args()
# execute main command
integerEncode(vocab_size=args.vocab_size,
padding_words=args.padding_tokens,
padding_chars=args.padding_char)
|
# Copyright (c) 2019 Eric Steinberger
import numpy as np
import torch
class ReservoirBufferBase:
def __init__(self, owner, max_size, env_bldr, nn_type, iter_weighting_exponent):
self._owner = owner
self._env_bldr = env_bldr
self.device = torch.device("cpu")
self._owner = owner
self._env_bldr = env_bldr
self._max_size = max_size
self._nn_type = nn_type
self.device = torch.device("cpu")
self.size = 0
self.n_entries_seen = 0
if nn_type == "recurrent":
self._pub_obs_buffer = np.empty(shape=(max_size,), dtype=object)
elif nn_type == "feedforward":
self._pub_obs_buffer = torch.zeros((max_size, self._env_bldr.pub_obs_size), dtype=torch.float32,
device=self.device)
else:
raise ValueError(nn_type)
self._range_idx_buffer = torch.zeros((max_size,), dtype=torch.long, device=self.device)
self._legal_action_mask_buffer = torch.zeros((max_size, env_bldr.N_ACTIONS,),
dtype=torch.float32, device=self.device)
self._iteration_buffer = torch.zeros((max_size,), dtype=torch.float32, device=self.device)
self._iter_weighting_exponent = iter_weighting_exponent
self._last_iterationation_seen = None
def add(self, **kwargs):
"""
Dont forget to n_entries_seen+=1 !!
"""
raise NotImplementedError
def sample(self, batch_size, device):
raise NotImplementedError
def _should_add(self):
return np.random.random() < (float(self._max_size) / float(self.n_entries_seen))
def _np_to_torch(self, arr):
return torch.from_numpy(np.copy(arr)).to(self.device)
def _random_idx(self):
return np.random.randint(low=0, high=self._max_size)
def state_dict(self):
return {
"owner": self._owner,
"max_size": self._max_size,
"nn_type": self._nn_type,
"size": self.size,
"n_entries_seen": self.n_entries_seen,
"iter_weighting_exponent": self._iter_weighting_exponent,
"pub_obs_buffer": self._pub_obs_buffer,
"range_idx_buffer": self._range_idx_buffer,
"legal_action_mask_buffer": self._legal_action_mask_buffer,
"iteration_buffer": self._iteration_buffer,
}
def load_state_dict(self, state):
assert self._owner == state["owner"]
assert self._max_size == state["max_size"]
assert self._nn_type == state["nn_type"]
self.size = state["size"]
self.n_entries_seen = state["n_entries_seen"]
self._iter_weighting_exponent = state["iter_weighting_exponent"]
if self._nn_type == "recurrent":
self._pub_obs_buffer = state["pub_obs_buffer"]
self._range_idx_buffer = state["range_idx_buffer"]
self._legal_action_mask_buffer = state["legal_action_mask_buffer"]
self._iteration_buffer = state["iteration_buffer"]
elif self._nn_type == "feedforward":
self._pub_obs_buffer = state["pub_obs_buffer"].to(self.device)
self._range_idx_buffer = state["range_idx_buffer"].to(self.device)
self._legal_action_mask_buffer = state["legal_action_mask_buffer"].to(self.device)
self._iteration_buffer = state["iteration_buffer"].to(self.device)
else:
raise ValueError(self._nn_type)
|
bash -c "pacman-key --init"
bash -c "pacman-key --populate msys2"
bash -c "pacman-key --refresh-keys"
|
<?php
namespace Packlink\BusinessLogic\Registration;
class RegistrationInfo
{
/**
* @var string
*/
private $email;
/**
* @var string
*/
private $phone;
/**
* @var string
*/
private $source;
/**
* RegistrationInfo constructor.
*
* @param string $email
* @param string $phone
* @param string $source
*/
public function __construct($email, $phone, $source)
{
$this->email = $email !== null ? $email : '';
$this->phone = $phone !== null ? $phone : '';
$this->source = $source !== null ? $source : '';
}
/**
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* @return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* @return string
*/
public function getSource()
{
return $this->source;
}
}
|
#!/bin/bash
SIGNAL_NAME=(ZERO $(kill -l `seq 1 64` 2>/dev/null))
function pretty_exit_status {
local pretty_status;
if (($1 == 0)); then
pretty_status=OK;
else
local number;
pretty_status="ERROR $1"
if (($1 > 128)); then
number=$(($1 - 128));
if ( [ -n "${SIGNAL_NAME[$number]}" ] ); then
pretty_status="$pretty_status (SIG${SIGNAL_NAME[$number]}, $number)"
fi
fi
fi
echo $pretty_status;
return $1;
}
|
### Todos
- [x] Write Integration Test (usecase, storages layer).
- [x] Structure code by simple MVC Architecture.
- [x] Limit Create Task per day can avoid race condition.
- [x] Split `services` layer to `use case` and `transport` layer.
- [x] Change from using `SQLite` to both `SQLite` and `Postgres`.
- [x] Hashing user's password.
- [x] Error handling.
- [ ] Write Integration Test (transport layer).
- [ ] Using docker-compose.
### How to run
- Please set env to `config.json` and run `go run main.go`
### How to test
- Please set env to `test.config.json` for every layer before run test
|
const { createFilePath } = require('gatsby-source-filesystem')
const isEmpty = require('lodash/isEmpty')
const path = require('path')
const PAGINATION_OFFSET = 7
function createPosts(createPage, createRedirect, edges) {
edges.forEach(({ node }, i) => {
const prev = i === 0 ? null : edges[i - 1].node
const next = i === edges.length - 1 ? null : edges[i + 1].node
const pagePath = node.fields.slug
if (node.fields.redirects) {
for (const fromPath of node.fields.redirects) {
createRedirect({
fromPath,
toPath: pagePath,
redirectInBrowser: true,
isPermanent: true,
})
}
}
createPage({
path: pagePath,
component: path.resolve('./src/templates/post.jsx'),
context: {
id: node.id,
prev,
next,
},
})
})
}
function createBlogPages({ data, actions }) {
if (isEmpty(data.edges)) {
throw new Error('There are no posts!')
}
const { edges } = data
const { createRedirect, createPage } = actions
createPosts(createPage, createRedirect, edges)
}
exports.createPages = async ({ actions, graphql }) => {
const { data, errors } = await graphql(`
fragment PostDetails on Mdx {
fileAbsolutePath
id
parent {
... on File {
name
sourceInstanceName
}
}
excerpt(pruneLength: 250)
fields {
title
slug
description
date
redirects
}
}
query {
blog: allMdx(
filter: {
frontmatter: { published: { ne: false } }
fileAbsolutePath: { regex: "//content/blog//" }
}
sort: {
order: DESC
fields: [frontmatter___date]
}
) {
edges {
node {
...PostDetails
}
}
}
}
`)
if (errors) {
return Promise.reject(errors)
}
const { blog } = data
createBlogPages({
data: blog,
actions,
})
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === 'Mdx') {
const value = createFilePath({ node, getNode })
createNodeField({
node,
name: 'slug',
value: `/blog${value}`,
})
createNodeField({
node,
name: 'id',
value: node.id,
})
createNodeField({
node,
name: 'title',
value: node.frontmatter.title,
})
createNodeField({
node,
name: 'description',
value: node.frontmatter.description,
})
createNodeField({
node,
name: 'author',
value: node.frontmatter.author || 'Michael Auderer',
})
createNodeField({
node,
name: 'published',
value: node.frontmatter.published,
})
createNodeField({
node,
name: 'date',
value: node.frontmatter.date ? node.frontmatter.date.split(' ')[0] : '',
})
createNodeField({
node,
name: 'categories',
value: node.frontmatter.categories || [],
})
createNodeField({
node,
name: 'redirects',
value: node.frontmatter.redirects || [],
})
const editPath = node.fileAbsolutePath.replace(__dirname, '')
createNodeField({
node,
name: 'editLink',
value: `https://github.com/auderer/auderer.dev/edit/master${editPath}`,
})
}
}
|
$input = File.read "day-09.input"
# --- Part One ---
$groups = []
def parse_group idx, depth
$groups << depth
loop do
idx =
case $input[idx]
when nil
return
when "{"
parse_group (idx + 1), depth + 1
when "}"
return idx + 1
when "<"
parse_garbage (idx + 1)
else
idx + 1
end
end
end
def parse_garbage idx
loop do
idx =
case $input[idx]
when "!"
idx + 2
when ">"
return idx + 1
else
idx + 1
end
end
end
parse_group 0, 0
puts "Part One: #{$groups.sum}"
# --- Part Two ---
$garbage = 0
def parse_garbage_ idx
loop do
idx =
case $input[idx]
when "!"
idx + 2
when ">"
return idx + 1
else
$garbage += 1
idx + 1
end
end
end
def parse_group_ idx
loop do
idx =
case $input[idx]
when nil
return
when "{"
parse_group_ (idx + 1)
when "}"
return idx + 1
when "<"
parse_garbage_ (idx + 1)
else
idx + 1
end
end
end
parse_group_ 0
puts "Part Two: #{$garbage}"
|
import { FullCwdGameView } from '../../../types/cwd.types'
import { connectToDatabase } from '../../../util/mongodb'
import { fromCwdGames } from '../cwd-game-store'
export default async function setGuess(game: FullCwdGameView, guess: unknown) {
const player = game.currentPlayer
const isPlayerTurn = player?.team === game.team_turn
if (!isPlayerTurn && !player.designatedPsychic)
throw new Error('Only non-psychic players on turn team can set guess.')
if (game.phase !== 'guess')
throw new Error('Can only set guess in the guess phase.')
if (player && game.guesses?.[player.id]?.locked)
throw new Error('Cannot set guess once its locked.')
if (typeof guess !== 'number')
throw new TypeError("Command 'set_guess' requires numeric 'guess'.")
const { db } = await connectToDatabase()
const filter = { room: game.room.toLowerCase() }
await fromCwdGames(db).updateOne(filter, {
$set: { [`guesses.${player.id}.value`]: guess },
})
}
|
package org.clulab.factuality
import org.clulab.factuality.utils.Serializer
import scala.collection.mutable.ArrayBuffer
import scala.io.Source
import scala.util.Try
/**
* Reads the CoNLL-like column format
*/
object ColumnReader {
def readColumnsFromFile(fn: String): Array[Array[Row]] =
Serializer.using(Source.fromFile(fn, "UTF-8")) { source =>
readColumns(source)
}
def readColumnsFromResource(fn: String): Array[Array[Row]] =
Serializer.using(Source.fromResource(fn)) { source =>
readColumns(source)
}
def readColumns(fn: String): Array[Array[Row]] = {
val result1 = Try(readColumnsFromFile(fn))
val result2 = result1.orElse(Try(readColumnsFromResource(fn)))
result2.get
}
def readColumns(source: Source): Array[Array[Row]] = {
var sentence = new ArrayBuffer[Row]()
val sentences = new ArrayBuffer[Array[Row]]()
for (line <- source.getLines()) {
val l = line.trim
if (l.isEmpty) {
// end of sentence
if (sentence.nonEmpty) {
sentences += sentence.toArray
sentence = new ArrayBuffer[Row]
}
} else {
// within the same sentence
val bits = l.split("\\s")
if (bits.length < 2)
throw new RuntimeException(s"ERROR: invalid line [$l]!")
sentence += Row(bits)
}
}
if (sentence.nonEmpty) {
sentences += sentence.toArray
}
source.close()
sentences.toArray
}
}
case class Row(val tokens:Array[String]) {
def get(idx:Int): String =
if(idx < tokens.length) tokens(idx)
else ""
}
|
#pragma once
#include ".\JointArray.hpp"
#include ".\vec4.hpp"
#include ".\mat4.hpp"
#include ".\Component.hpp"
namespace regenny::via {
struct Transform;
}
namespace regenny::via {
struct Scene;
}
namespace regenny::via {
#pragma pack(push, 1)
struct Transform : public Component {
regenny::via::vec4 Position; // 0x30
regenny::via::vec4 Rotation; // 0x40
regenny::via::vec4 Scale; // 0x50
regenny::via::Scene* Scene; // 0x60
regenny::via::Transform* Child; // 0x68
regenny::via::Transform* Next; // 0x70
regenny::via::Transform* Parent; // 0x78
regenny::via::mat4 WorldTransform; // 0x80
void* JointHashTbl; // 0xc0
int32_t ParentJointIndex; // 0xc8
int32_t UpdateFrame; // 0xcc
bool SameJointsConstraint; // 0xd0
bool DirtySelf; // 0xd1
bool DirtyUpwards; // 0xd2
bool AbsoluteScaling; // 0xd3
char pad_d4[0x4];
regenny::via::JointArray JointTbl; // 0xd8
regenny::via::mat4* JointMatrixTbl; // 0xe8
char pad_f0[0x20];
}; // Size: 0x110
#pragma pack(pop)
}
|
/* global describe, it */
/* jshint -W030 */
var chai = require('chai'),
adhoc = require('../'),
expect = chai.expect;
chai.use(adhoc);
// Code to test
function Model (type) {
this._type = type;
this._attrs = {};
}
Model.prototype.set = function (key, value) {
this._attrs[key] = value;
};
Model.prototype.get = function (key) {
return this._attrs[key];
};
var arthur = new Model('person');
arthur.set('name', 'Arthur Dent');
arthur.set('occupation', 'traveller');
arthur.set('age', 27);
arthur.set('id', 42);
var joe = new Model('dog');
joe.set('id', 'not a number');
// Define custom assertions
// Property `model`
adhoc.addAssertion('model', function(ctx) {
ctx.assert(
ctx.obj instanceof Model
, 'expected #{this} to be a Model'
, 'expected #{this} to not be a Model'
);
});
// Method `model2`
var flagList = [];
adhoc.addAssertion('model2', function(ctx, type) {
flagList.push(ctx.flag('negate'));
ctx.expect(ctx.obj, 'model type check').flags().to.be.instanceof(Model);
ctx.expect(ctx.obj, 'model type check').flags('negate').to.be.instanceof(Model);
ctx.assert(
ctx.obj._type === type
, "expected #{this} to be of type #{exp} but got #{act}"
, "expected #{this} to not be of type #{act}"
, type // expected
, ctx.obj._type // actual
);
});
// Chainable method `age`
adhoc.addAssertion('age', function(ctx, n) {
// make sure we are working with a model
ctx.expect(ctx.obj).to.be.instanceof(Model);
// make sure we have an age and its a number
var age = ctx.obj.get('age');
ctx.expect(age).to.be.a('number');
// do our comparison
ctx.assert(
age === n
, "expected #{this} to have have #{exp} but got #{act}"
, "expected #{this} to not have age #{act}"
, n
, age
);
}, function(flag) {
flag('model.age', true);
});
// Extend property `ok`
adhoc.extendAssertion('ok', function(ctx) {
if (ctx.obj && ctx.obj instanceof Model) {
ctx.expect(ctx.obj).to.have.deep.property('_attrs.id');
ctx.expect(ctx.obj._attrs.id, 'model assert ok id type').flags().a('number');
return true;
} else {
return false;
}
});
// Extend method `above`
adhoc.extendAssertion('above', function(ctx, n) {
if (ctx.flag('model.age')) {
// first we assert we are actually working with a model
ctx.expect(ctx.obj).instanceof(Model);
// next, make sure we have an age
ctx.expect(ctx.obj).to.have.deep.property('_attrs.age').a('number');
// now we compare
var age = ctx.obj.get('age');
ctx.assert(
age > n
, "expected #{this} to have an age above #{exp} but got #{act}"
, "expected #{this} to not have an age above #{exp} but got #{act}"
, n
, age
);
return true;
}
return false;
});
// Wrap the extended method `above`
adhoc.wrapAssertion('above', function(error, ctx, n) {
if (error) {
// Suppress the error if both operands are > 10000.
if (ctx.obj > 10000 && n > 10000) {
return true;
}
error.message = 'Custom prefix: ' + error.message;
}
return false;
});
// Do the tests
describe('New assertions', function() {
it('should not be added if they already exist', function() {
var noop = function() {};
expect(function() {
adhoc.addAssertion('contain', noop);
}).to.throw(TypeError);
expect(function() {
adhoc.addAssertion('above', noop, noop);
}).to.throw(TypeError);
});
});
describe('Non-existent assertions', function() {
it('should not be extended', function() {
var noop = function() {};
expect(function() {
adhoc.extendAssertion('idontexist', noop);
}).to.throw(TypeError);
});
it('should not be wrapped', function() {
var noop = function() {};
expect(function() {
adhoc.wrapAssertion('idontexist', noop);
}).to.throw(TypeError);
});
});
describe('Property model', function() {
it('should be successfully added', function() {
expect(expect(new Model())).to.have.property('model');
expect(function() {
expect(expect(1)).to.have.property('model');
}).to.throw();
});
it('should behave as expected', function() {
expect(arthur).to.be.a.model;
expect(1).to.not.be.a.model;
expect(function() {
expect(arthur).to.not.be.a.model;
}).to.throw();
expect(function() {
expect(1).to.be.a.model;
}).to.throw();
});
});
describe('Method model2', function() {
it('should be successfully added', function() {
expect(expect(new Model())).to.have.property('model2').that.is.a('function');
expect(function() {
expect(expect(1)).to.have.property('model2');
}).to.not.throw();
});
it('should behave as expected', function() {
expect(arthur).to.be.a.model2('person');
expect(1).to.not.be.a.model2('person');
expect(function() {
expect(arthur).to.not.be.a.model2('person');
}).to.throw();
expect(function() {
expect(1).to.be.a.model2('person');
}).to.throw();
expect(function() {
expect(arthur).to.be.a.model2('animal');
}).to.throw();
expect(function() {
expect(arthur).to.not.be.a.model2('animal');
}).to.throw();
expect(flagList).to.eql([undefined, true, true, undefined, undefined, true]);
});
});
describe('Chainable method age', function() {
it('should be successfully added', function() {
expect(expect(new Model())).to.have.property('age').that.is.a('function');
expect(function() {
expect(expect(1)).to.have.property('age');
}).to.not.throw();
});
it('should behave as expected', function() {
expect(arthur).to.have.age(27);
expect(arthur).to.not.have.age(20);
expect(arthur).to.have.age.above(17);
expect(arthur).to.not.have.age.above(37);
expect(function() {
expect(arthur).to.not.have.age(27);
}).to.throw();
expect(function() {
expect(arthur).to.have.age(20);
}).to.throw();
expect(function() {
expect(arthur).to.not.have.age.above(17);
}).to.throw();
expect(function() {
expect(arthur).to.have.age.above(37);
}).to.throw();
});
});
describe('Overwritten method above', function() {
it('should behave as before when model.age flag is not present', function() {
expect(20).to.be.above(10);
expect(function() {
expect(10).to.be.above(20);
}).to.throw();
});
});
describe('Overwritten property ok', function() {
it('should behave as expected for Model instances', function() {
expect(arthur).to.be.ok;
expect(joe).to.be.not.ok;
expect(function() {
expect(arthur).to.be.not.ok;
}).to.throw();
expect(function() {
expect(joe).to.be.ok;
}).to.throw();
});
it('should behave as before for other values', function() {
expect(true).to.be.ok;
expect(false).to.be.not.ok;
expect(function() {
expect(true).to.be.not.ok;
}).to.throw();
expect(function() {
expect(false).to.be.ok;
}).to.throw();
});
});
describe('Wrapped method above', function() {
it('should suppress errors for operands > 10000', function() {
expect(function() {
expect(9000).to.be.above(9500);
}).to.throw();
expect(function() {
expect(10100).to.be.above(10500);
}).to.not.throw();
});
it('should prepend the custom message to errors thrown', function() {
expect(function() {
expect(100).to.be.above(200);
}).to.throw(/^Custom prefix: /);
});
});
|
<?php
// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Rds\V20140815\Models;
use AlibabaCloud\Tea\Model;
class CreateDdrInstanceRequest extends Model
{
/**
* @var int
*/
public $ownerId;
/**
* @var string
*/
public $resourceOwnerAccount;
/**
* @var int
*/
public $resourceOwnerId;
/**
* @var string
*/
public $regionId;
/**
* @var string
*/
public $engine;
/**
* @var string
*/
public $engineVersion;
/**
* @var string
*/
public $DBInstanceClass;
/**
* @var int
*/
public $DBInstanceStorage;
/**
* @var string
*/
public $systemDBCharset;
/**
* @var string
*/
public $DBInstanceNetType;
/**
* @var string
*/
public $DBInstanceDescription;
/**
* @var string
*/
public $securityIPList;
/**
* @var string
*/
public $clientToken;
/**
* @var string
*/
public $payType;
/**
* @var string
*/
public $zoneId;
/**
* @var string
*/
public $instanceNetworkType;
/**
* @var string
*/
public $connectionMode;
/**
* @var string
*/
public $VPCId;
/**
* @var string
*/
public $vSwitchId;
/**
* @var string
*/
public $privateIpAddress;
/**
* @var string
*/
public $ownerAccount;
/**
* @var string
*/
public $usedTime;
/**
* @var string
*/
public $period;
/**
* @var string
*/
public $resourceGroupId;
/**
* @var string
*/
public $restoreType;
/**
* @var string
*/
public $backupSetId;
/**
* @var string
*/
public $restoreTime;
/**
* @var string
*/
public $sourceRegion;
/**
* @var string
*/
public $sourceDBInstanceName;
/**
* @var string
*/
public $DBInstanceStorageType;
/**
* @var string
*/
public $binlogName;
/**
* @var string
*/
public $binlogPosition;
/**
* @var string
*/
public $binlogRole;
protected $_name = [
'ownerId' => 'OwnerId',
'resourceOwnerAccount' => 'ResourceOwnerAccount',
'resourceOwnerId' => 'ResourceOwnerId',
'regionId' => 'RegionId',
'engine' => 'Engine',
'engineVersion' => 'EngineVersion',
'DBInstanceClass' => 'DBInstanceClass',
'DBInstanceStorage' => 'DBInstanceStorage',
'systemDBCharset' => 'SystemDBCharset',
'DBInstanceNetType' => 'DBInstanceNetType',
'DBInstanceDescription' => 'DBInstanceDescription',
'securityIPList' => 'SecurityIPList',
'clientToken' => 'ClientToken',
'payType' => 'PayType',
'zoneId' => 'ZoneId',
'instanceNetworkType' => 'InstanceNetworkType',
'connectionMode' => 'ConnectionMode',
'VPCId' => 'VPCId',
'vSwitchId' => 'VSwitchId',
'privateIpAddress' => 'PrivateIpAddress',
'ownerAccount' => 'OwnerAccount',
'usedTime' => 'UsedTime',
'period' => 'Period',
'resourceGroupId' => 'ResourceGroupId',
'restoreType' => 'RestoreType',
'backupSetId' => 'BackupSetId',
'restoreTime' => 'RestoreTime',
'sourceRegion' => 'SourceRegion',
'sourceDBInstanceName' => 'SourceDBInstanceName',
'DBInstanceStorageType' => 'DBInstanceStorageType',
'binlogName' => 'BinlogName',
'binlogPosition' => 'BinlogPosition',
'binlogRole' => 'BinlogRole',
];
public function validate()
{
}
public function toMap()
{
$res = [];
if (null !== $this->ownerId) {
$res['OwnerId'] = $this->ownerId;
}
if (null !== $this->resourceOwnerAccount) {
$res['ResourceOwnerAccount'] = $this->resourceOwnerAccount;
}
if (null !== $this->resourceOwnerId) {
$res['ResourceOwnerId'] = $this->resourceOwnerId;
}
if (null !== $this->regionId) {
$res['RegionId'] = $this->regionId;
}
if (null !== $this->engine) {
$res['Engine'] = $this->engine;
}
if (null !== $this->engineVersion) {
$res['EngineVersion'] = $this->engineVersion;
}
if (null !== $this->DBInstanceClass) {
$res['DBInstanceClass'] = $this->DBInstanceClass;
}
if (null !== $this->DBInstanceStorage) {
$res['DBInstanceStorage'] = $this->DBInstanceStorage;
}
if (null !== $this->systemDBCharset) {
$res['SystemDBCharset'] = $this->systemDBCharset;
}
if (null !== $this->DBInstanceNetType) {
$res['DBInstanceNetType'] = $this->DBInstanceNetType;
}
if (null !== $this->DBInstanceDescription) {
$res['DBInstanceDescription'] = $this->DBInstanceDescription;
}
if (null !== $this->securityIPList) {
$res['SecurityIPList'] = $this->securityIPList;
}
if (null !== $this->clientToken) {
$res['ClientToken'] = $this->clientToken;
}
if (null !== $this->payType) {
$res['PayType'] = $this->payType;
}
if (null !== $this->zoneId) {
$res['ZoneId'] = $this->zoneId;
}
if (null !== $this->instanceNetworkType) {
$res['InstanceNetworkType'] = $this->instanceNetworkType;
}
if (null !== $this->connectionMode) {
$res['ConnectionMode'] = $this->connectionMode;
}
if (null !== $this->VPCId) {
$res['VPCId'] = $this->VPCId;
}
if (null !== $this->vSwitchId) {
$res['VSwitchId'] = $this->vSwitchId;
}
if (null !== $this->privateIpAddress) {
$res['PrivateIpAddress'] = $this->privateIpAddress;
}
if (null !== $this->ownerAccount) {
$res['OwnerAccount'] = $this->ownerAccount;
}
if (null !== $this->usedTime) {
$res['UsedTime'] = $this->usedTime;
}
if (null !== $this->period) {
$res['Period'] = $this->period;
}
if (null !== $this->resourceGroupId) {
$res['ResourceGroupId'] = $this->resourceGroupId;
}
if (null !== $this->restoreType) {
$res['RestoreType'] = $this->restoreType;
}
if (null !== $this->backupSetId) {
$res['BackupSetId'] = $this->backupSetId;
}
if (null !== $this->restoreTime) {
$res['RestoreTime'] = $this->restoreTime;
}
if (null !== $this->sourceRegion) {
$res['SourceRegion'] = $this->sourceRegion;
}
if (null !== $this->sourceDBInstanceName) {
$res['SourceDBInstanceName'] = $this->sourceDBInstanceName;
}
if (null !== $this->DBInstanceStorageType) {
$res['DBInstanceStorageType'] = $this->DBInstanceStorageType;
}
if (null !== $this->binlogName) {
$res['BinlogName'] = $this->binlogName;
}
if (null !== $this->binlogPosition) {
$res['BinlogPosition'] = $this->binlogPosition;
}
if (null !== $this->binlogRole) {
$res['BinlogRole'] = $this->binlogRole;
}
return $res;
}
/**
* @param array $map
*
* @return CreateDdrInstanceRequest
*/
public static function fromMap($map = [])
{
$model = new self();
if (isset($map['OwnerId'])) {
$model->ownerId = $map['OwnerId'];
}
if (isset($map['ResourceOwnerAccount'])) {
$model->resourceOwnerAccount = $map['ResourceOwnerAccount'];
}
if (isset($map['ResourceOwnerId'])) {
$model->resourceOwnerId = $map['ResourceOwnerId'];
}
if (isset($map['RegionId'])) {
$model->regionId = $map['RegionId'];
}
if (isset($map['Engine'])) {
$model->engine = $map['Engine'];
}
if (isset($map['EngineVersion'])) {
$model->engineVersion = $map['EngineVersion'];
}
if (isset($map['DBInstanceClass'])) {
$model->DBInstanceClass = $map['DBInstanceClass'];
}
if (isset($map['DBInstanceStorage'])) {
$model->DBInstanceStorage = $map['DBInstanceStorage'];
}
if (isset($map['SystemDBCharset'])) {
$model->systemDBCharset = $map['SystemDBCharset'];
}
if (isset($map['DBInstanceNetType'])) {
$model->DBInstanceNetType = $map['DBInstanceNetType'];
}
if (isset($map['DBInstanceDescription'])) {
$model->DBInstanceDescription = $map['DBInstanceDescription'];
}
if (isset($map['SecurityIPList'])) {
$model->securityIPList = $map['SecurityIPList'];
}
if (isset($map['ClientToken'])) {
$model->clientToken = $map['ClientToken'];
}
if (isset($map['PayType'])) {
$model->payType = $map['PayType'];
}
if (isset($map['ZoneId'])) {
$model->zoneId = $map['ZoneId'];
}
if (isset($map['InstanceNetworkType'])) {
$model->instanceNetworkType = $map['InstanceNetworkType'];
}
if (isset($map['ConnectionMode'])) {
$model->connectionMode = $map['ConnectionMode'];
}
if (isset($map['VPCId'])) {
$model->VPCId = $map['VPCId'];
}
if (isset($map['VSwitchId'])) {
$model->vSwitchId = $map['VSwitchId'];
}
if (isset($map['PrivateIpAddress'])) {
$model->privateIpAddress = $map['PrivateIpAddress'];
}
if (isset($map['OwnerAccount'])) {
$model->ownerAccount = $map['OwnerAccount'];
}
if (isset($map['UsedTime'])) {
$model->usedTime = $map['UsedTime'];
}
if (isset($map['Period'])) {
$model->period = $map['Period'];
}
if (isset($map['ResourceGroupId'])) {
$model->resourceGroupId = $map['ResourceGroupId'];
}
if (isset($map['RestoreType'])) {
$model->restoreType = $map['RestoreType'];
}
if (isset($map['BackupSetId'])) {
$model->backupSetId = $map['BackupSetId'];
}
if (isset($map['RestoreTime'])) {
$model->restoreTime = $map['RestoreTime'];
}
if (isset($map['SourceRegion'])) {
$model->sourceRegion = $map['SourceRegion'];
}
if (isset($map['SourceDBInstanceName'])) {
$model->sourceDBInstanceName = $map['SourceDBInstanceName'];
}
if (isset($map['DBInstanceStorageType'])) {
$model->DBInstanceStorageType = $map['DBInstanceStorageType'];
}
if (isset($map['BinlogName'])) {
$model->binlogName = $map['BinlogName'];
}
if (isset($map['BinlogPosition'])) {
$model->binlogPosition = $map['BinlogPosition'];
}
if (isset($map['BinlogRole'])) {
$model->binlogRole = $map['BinlogRole'];
}
return $model;
}
}
|
import {DateTime} from 'luxon';
import {Mapping} from '../model/mapping';
export const START_NAME = 'Starting Activities';
export const STOP_NAME = 'Stopping Activities';
export function normalizeColumnName(columnName: string): string {
return columnName.replace('_', ' ');
}
export function encodeColumnName(columnName: string): string {
return columnName.replace(' ', '_');
}
export function transformMapping(mapping: Mapping) {
const colMappObj = {};
for (const key of Object.keys(mapping)) {
if (mapping[key]) {
if (typeof (mapping[key]) === 'string') {
colMappObj[key] = encodeColumnName(mapping[key]);
// this.mapping[key] = encodeColumnName(this.mapping[key]);
}
}
}
return colMappObj;
}
export function calculateColumns(columns: any[]): any[] {
return columns.map(column => {
let name = column
if (column.COLUMN_NAME) {
name = column.COLUMN_NAME
}
const newColumn = {
headerName: name,
field: name,
sortable: false,
filter: false,
resizable: false
};
return newColumn;
})
}
export function getRelativeTime(millisec: number) {
const diff = new Date().getTime() - new Date(millisec).getTime();
if (diff < 60000) {
return 'Less than a minute ago...'
}
return millisec ? DateTime.fromMillis(millisec).toRelative() : '';
}
export function stripOrgFolder(dxpLocation): string {
let re = '';
if (dxpLocation) {
const fpArr = dxpLocation.split('/');
if (fpArr.length > 2) {
let folder = '';
for (let i = 3; i < fpArr.length; i++) {
folder += '/' + fpArr[i];
}
re = folder;
} else {
re = dxpLocation;
}
}
return re;
}
export function convertDateFromLocale(date: string): string {
// 3/13/2010 2:16:20 PM
console.log('convertDateFromLocale: ', date)
const locale = window.navigator.language;
const newDateLocale = Intl.DateTimeFormat(locale).formatToParts(new Date());
let format = '';
newDateLocale.forEach((element: Intl.DateTimeFormatPart) => {
switch (element.type) {
case 'day':
format = format + 'd';
break;
case 'month':
format = format + 'M';
break;
case 'year':
format = format + (element.value.length === 2 ? 'yy' : 'yyyy');
break;
case 'literal':
// TODO: This does not work for dutch keyboard ('-' signs are separators)
format = format + element.value;
// format = format + '/';
break;
default:
break;
}
})
if(date.indexOf('PM') > - 1 || date.indexOf('AM') > - 1) {
format = format + ' tt';
} else {
format = format + ' hh:mm:ss';
}
// format = format + ' hh:mm:ss';
const newDate = DateTime.fromFormat(date, format, {locale}).toISO();
console.log('OLD DATE: ' + date + ' NEW DATE: ' + newDate);
return newDate;
}
export function convertDateToLocale(date: string): string {
const currentDate = new Date(date);
const locale = window.navigator.language;
return currentDate.toLocaleDateString(locale) + ' ' + currentDate.toLocaleTimeString(locale)
}
|
# Entidades y controladores
Una entidad en el motor es cualquier elemento que aparezca de manera independiente
en la pantalla y tenga posición, rutina de dibujado y lógica de actualización.
Las entidades son manejadas por un gestor de entidades, el cual es actualizado por
la escena. El gestor de entidades a su vez llama al método `Update` y `Draw` de las
entidades. Cada entidad implementa su lógica y su rutina de dibujado.
## Controladores
Los controladores pueden ser externos o internos.
- Controladores externos: Son una capa que contiene a la entidad a controlar. El
gestor de entidades llama a su método `Update` y el controlador externo es el que
llama al método `Update` de la entidad controlada. O no, si quiere tomar el control
y evitar su lógica interna. Útil para cinemáticas. Se podría decir que es 'push'
- Controlador interno: Un controlador interno es llamado por la propia entidad
controlada, para obtener las acciones que debe realizar. Los detalles sobre cómo
realizarlas son gestionadas por la implementación de la entidad.
## Rutinas de dibujado y animaciones
La rutina de dibujo es implementada por una estructura `Animation` la cual
tiene un método de actualización (para hacer correr la animación) y otro de obtención
del frame actual. Este último método puede aplicar una subdivisión para una animación
por cambio de frame, o puede aplicar una transformación (rotación, escala, traslación, etc.)
Estas transformaciones y la división de frame son métodos diferentes, ya que en el motor
ebiten se hacen en dos pasos diferentes.
Todas las animaciones tienen un principio y un fin, pudiendo ser cíclicas. También
tienen un método para indicar si han llegado a ese fin en este frame.
|
# frozen_string_literal: true
class CreateOrgUnits < ActiveRecord::Migration[6.0]
include Partynest::Migration
def change
create_table :org_units do |t|
t.timestamps null: false
t.string :short_name, null: false, index: { unique: true }
t.string :name, null: false, index: { unique: true }
t.references :kind,
null: false,
index: true,
foreign_key: { to_table: :org_unit_kinds }
t.references :parent,
null: true,
index: true,
foreign_key: { to_table: :org_units }
end
add_constraint :org_units, :short_name, <<~SQL
is_good_small_text(short_name)
SQL
add_constraint :org_units, :name, <<~SQL
is_good_small_text(name)
SQL
end
end
|
Make sure you have npm and node installed, then:
Run `npm install`
Run `npm start`
Enjoy AnyTool!
|
import { PolicyDocument } from '@aws-cdk/aws-iam';
import { RemovalPolicy, Resource } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { IBucket } from './bucket';
import { CfnBucketPolicy } from './s3.generated';
export interface BucketPolicyProps {
/**
* The Amazon S3 bucket that the policy applies to.
*/
readonly bucket: IBucket;
/**
* Policy to apply when the policy is removed from this stack.
*
* @default - RemovalPolicy.DESTROY.
*/
readonly removalPolicy?: RemovalPolicy;
}
/**
* Applies an Amazon S3 bucket policy to an Amazon S3 bucket.
*/
export class BucketPolicy extends Resource {
/**
* A policy document containing permissions to add to the specified bucket.
* For more information, see Access Policy Language Overview in the Amazon
* Simple Storage Service Developer Guide.
*/
public readonly document = new PolicyDocument();
private resource: CfnBucketPolicy;
constructor(scope: Construct, id: string, props: BucketPolicyProps) {
super(scope, id);
if (!props.bucket.bucketName) {
throw new Error('Bucket doesn\'t have a bucketName defined');
}
this.resource = new CfnBucketPolicy(this, 'Resource', {
bucket: props.bucket.bucketName,
policyDocument: this.document,
});
if (props.removalPolicy) {
this.resource.applyRemovalPolicy(props.removalPolicy);
}
}
/**
* Sets the removal policy for the BucketPolicy.
* @param removalPolicy the RemovalPolicy to set.
*/
public applyRemovalPolicy(removalPolicy: RemovalPolicy) {
this.resource.applyRemovalPolicy(removalPolicy);
}
}
|
# Release 2020.8.1
## Major feature: More Info
Learn more about it in [%UbK6ZACB6uFJU0+JDHtnvPW1mV2c2QAq3dXYnKkmcFg=.sha256](ssb:message/sha256/UbK6ZACB6uFJU0%2BJDHtnvPW1mV2c2QAq3dXYnKkmcFg%3D).
## Fixes:
* **Core Components:**
* LAYOUT: hovering an `AvatarTile` now shows a pointer cursor.
* MAYBE FEATURE: changed the `VoteCounter` to require a click before fetching votes. The amount of `ssb-ws` calls flying around in a message list was too damn high.
* **Hub:**
* LAYOUT: changed the size of message id display on top of thread.
* LAYOUT: optimized the text on the top of channel display options.
* FEATURE: the channel view has a new option to show only root messages.
|
#!/usr/bin/env bash
# ==============================================================================
# Open Peer Power Community Add-ons: Bashio
# Bashio is an bash function library for use with Open Peer Power add-ons.
#
# It contains a set of commonly used operations and can be used
# to be included in add-on scripts to reduce code duplication across add-ons.
# ==============================================================================
# ------------------------------------------------------------------------------
# Returns a JSON object with generic version information about repositories.
#
# Arguments:
# $1 Add-on slug (optional)
# $1 Cache key to store results in (optional)
# $2 jq Filter to apply on the result (optional)
# ------------------------------------------------------------------------------
function bashio::repositories() {
local slug=${1:-false}
local cache_key=${2:-'repositories.list'}
local filter=${3:-'.repositories[].slug'}
local info
local response
bashio::log.trace "${FUNCNAME[0]}" "$@"
if bashio::cache.exists "${cache_key}"; then
bashio::cache.get "${cache_key}"
return "${__BASHIO_EXIT_OK}"
fi
if bashio::var.false "${slug}"; then
if bashio::cache.exists "repositories.list"; then
info=$(bashio::cache.get 'repositories.list')
else
info=$(bashio::api.supervisor GET "/addons" false)
bashio::cache.set "repositories.list" "${info}"
fi
else
if bashio::cache.exists "repositories.${slug}.info"; then
info=$(bashio::cache.get "repositories.${slug}.info")
else
info=$(bashio::api.supervisor GET "/addons" \
false ".repositories[] | select(.slug==\"${slug}\")")
bashio::cache.set "repositories.${slug}.info" "${info}"
fi
fi
response="${info}"
if bashio::var.has_value "${filter}"; then
response=$(bashio::jq "${info}" "${filter}")
fi
bashio::cache.set "${cache_key}" "${response}"
printf "%s" "${response}"
return "${__BASHIO_EXIT_OK}"
}
# ------------------------------------------------------------------------------
# Returns the name of a repository.
#
# Arguments:
# $1 Repository slug
# ------------------------------------------------------------------------------
function bashio::repository.name() {
local slug=${1}
bashio::log.trace "${FUNCNAME[0]}" "$@"
bashio::repositories "${slug}" "repositories.${slug}.name" '.name'
}
# ------------------------------------------------------------------------------
# Returns the source of a repository.
#
# Arguments:
# $1 Repository slug
# ------------------------------------------------------------------------------
function bashio::repository.source() {
local slug=${1}
bashio::log.trace "${FUNCNAME[0]}" "$@"
bashio::repositories "${slug}" "repositories.${slug}.source" '.source'
}
# ------------------------------------------------------------------------------
# Returns the URL of a repository.
#
# Arguments:
# $1 Repository slug
# ------------------------------------------------------------------------------
function bashio::repository.url() {
local slug=${1}
bashio::log.trace "${FUNCNAME[0]}" "$@"
bashio::repositories "${slug}" "repositories.${slug}.url" '.url'
}
# ------------------------------------------------------------------------------
# Returns the maintainer of a repository.
#
# Arguments:
# $1 Repository slug
# ------------------------------------------------------------------------------
function bashio::repository.maintainer() {
local slug=${1}
bashio::log.trace "${FUNCNAME[0]}" "$@"
bashio::repositories "${slug}" "repositories.${slug}.maintainer" '.maintainer'
}
|
import React from "react"
const inputStyles = {
width: `100%`,
border: 0,
borderBottom: `1px solid gray`,
margin: `10px 0`,
}
const submitStyles = {
width: `100%`,
border: 0,
margin: `10px 0`,
background: `black`,
color: `white`,
}
const ContactForm = props => (
<form className="ContactForm" name="contactForm" method="POST" netlify>
<input
type="text"
placeholder="Tu nombre"
title="Tu nombre"
className="ContactForm__input"
style={inputStyles}
/>
<input
type="email"
placeholder="Tu correo"
className="ContactForm__input"
title="Tu correo"
style={inputStyles}
/>
<textarea
placeholder="¿Qué me quieres decir?"
title="¿Qué me quieres decir?"
rows="4"
style={inputStyles}
/>
<section>
<input
type="submit"
title="Enviar"
value="Enviar"
style={submitStyles}
className="ContactForm__submit"
/>
</section>
</form>
)
export default ContactForm
|
package Baby.Com;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
/**
*
*/
public class KickStatisticsAdapter extends BaseAdapter {
private Context context;
private HashMap<Long, ArrayList<Date>> dates = new HashMap<Long, ArrayList<Date>>();
private Long[] keys = new Long[0];
private ArrayList<Boolean> expanded = new ArrayList<Boolean>();
long trimToDay(Date date) {
long dateTime = date.getTime();
// reset milliseconds
dateTime = dateTime - (dateTime % 1000);
// reset hours, minutes, seconds
Date newDate = new Date(dateTime);
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
return newDate.getTime();
}
public KickStatisticsAdapter(Context context) {
this.context = context;
}
synchronized public void setList(ArrayList<Date> list) {
dates.clear();
for (Date date : list) {
addDateInternal(date);
}
prepareKeysAndProvideSorting();
if (list.size() > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
private void prepareKeysAndProvideSorting() {
ArrayList<Long> list = new ArrayList<Long>();
list.addAll(dates.keySet());
Collections.sort(list);
Collections.reverse(list);
keys = list.toArray(keys);
// sort values
for (Long key : keys) {
Collections.sort(dates.get(key));
}
}
private void addDateInternal(Date date) {
long day = trimToDay(date);
ArrayList<Date> datesList;
if (dates.containsKey(day)) {
datesList = dates.get(day);
} else {
datesList = new ArrayList<Date>();
dates.put(day, datesList);
expanded.add(false);
}
datesList.add(date);
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getCount()
*/
@Override
public int getCount() {
return keys.length;
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItem(int)
*/
@Override
public Object getItem(int position) {
return keys[position];
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getItemId(int)
*/
@Override
public long getItemId(int position) {
return position;
}
class Listener implements OnClickListener {
int position;
KicksDayLayout view;
public Listener(KicksDayLayout view, int position) {
this.position = position;
this.view = view;
}
@Override
public void onClick(View v) {
boolean isExpanded = expanded.get(position);
isExpanded = !isExpanded;
expanded.set(position, isExpanded);
view.setExpanded(isExpanded);
}
}
/*
* (non-Javadoc)
*
* @see android.widget.Adapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
@Override
synchronized public View getView(int position, View convertView, ViewGroup parent) {
KicksDayLayout view = (KicksDayLayout)convertView;
if(position < getCount()) {
long day = keys[position];
if(view == null) {
view = new KicksDayLayout(context);
} else {
view.unsubscribeAll();
}
view.subscribe(new Listener(view, position));
view.init(day, dates.get(day), expanded.get(position));
}
return view;
}
synchronized public void addDate(Date date) {
addDateInternal(date);
prepareKeysAndProvideSorting();
notifyDataSetChanged();
}
synchronized public ArrayList<Date> getList() {
ArrayList<Date> datesList = new ArrayList<Date>();
for (ArrayList<Date> dayDatesList : dates.values()) {
datesList.addAll(dayDatesList);
}
return datesList;
}
}
|
import interfaces.Action;
import java.util.List;
//Implementation of methods in interfaces.LearningModule interface
public class ActionImpl implements Action {
private boolean toSwitch;
public ActionImpl(boolean toSwitch) {
this.toSwitch = toSwitch;
}
public ActionImpl() {
this(false);
}
public boolean action() {
return toSwitch;
}
public int actionInt() {
return toSwitch ? 1 : 0;
}
}
|
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="{{asset('assets/css/style.css')}}"/>
<!-- bootstrab css files cdn -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
/>
<!-- font-awesome cdn -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<!-- google fonts [Almarai] -->
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link
href="https://fonts.googleapis.com/css2?family=Almarai&display=swap"
rel="stylesheet"
/>
<style>
.choose-country .title i {
font-size: 40px;
color: #72ab8e;
}
.choose-country .title .text {
margin-right: 10px;
}
.choose-country .title .text h2 {
color: #000656;
}
.choose-country .title .text h5 {
font-weight: 900;
opacity: 0.5;
}
.choose-country .country-flag {
background-color: white;
}
.choose-country .country-flag img {
width: 80%;
height: 170px;
margin: auto;
display: block;
}
.choose-country .country-name {
background-color: #f7f9fa;
border: 2px solid #e5e9f1;
}
.choose-country .country-name h5 {
font-weight: 900 !important;
color: #6aada0;
}
.choose-country label {
cursor: pointer;
}
.choose-country input[type="radio"] {
display: none;
}
.box.checked .country-name,
.box.checked .country-flag {
background-color: rgb(178, 180, 184);
}
</style>
<title>إختيار الدولة</title>
</head>
<body>
<div class="choose-country page p-5">
<div class="container">
<div class="title d-flex">
<div class="icon">
<i class="fas fa-home"></i>
</div>
<div class="text">
<h2>نظام الادارة</h2>
<h5>اضغط على أي دولة للدخول إلى النظام الخاص بالدولة</h5>
</div>
</div>
<!-- countries -->
<div class="row mt-5">
@foreach($countries as $country)
@can($country->name)
<div class="col-md-4 col-sm-6 col-12">
<div class="box mb-4">
<div class="country-flag py-3">
<a href="{{route('country.SendCountry',$country ->id)}}"> <img
src="{{$country -> banner}}" alt=""/> </a>
</div>
<div class="country-name p-2">
<h5>{{$country->name}}</h5>
</div>
</div>
</div>
@endcan
@endforeach
</div>
</div>
</div>
<!-- include jquery -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"
></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
<script>
document.onchange = function (e) {
document.querySelector(".box.checked").classList.remove("checked");
e.target.labels[0].querySelector(".box").classList.add("checked");
};
</script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.