text
stringlengths 27
775k
|
|---|
import React, { forwardRef } from 'react'
import { Link } from 'react-router-dom'
import posed from 'react-pose'
import classNames from 'classnames'
import SvgChar from '~/components/svg/char'
const CharItem = forwardRef((props, ref) => {
const wrapperClasses = classNames(`char-section__item`, {
[`class-${props.class}`]: props.class,
'is-obsolete': props.obsolete,
})
const letterClasses = classNames(`thai-letter`, props.longId, {
'thai-letter--vowel': props.isVowel,
})
const charUrl = { pathname: `/char/${props.longId}` }
if (__IS_DEV__) charUrl.search = `?id=${props.id}`
return (
<li className={wrapperClasses} ref={ref}>
<Link to={charUrl} className="char-section__item-link">
<p className="preview-list-item-rtgs">{props.rtgs}</p>
<p className={letterClasses}>
<SvgChar svgId={props.longId} />
</p>
<p className="preview-list-item-meaning">{props.meaning}</p>
</Link>
</li>
)
})
const PosedCharItem = posed(CharItem)({
enter: { y: 0, opacity: 1 },
exit: { y: 25, opacity: 0 },
})
export default props => <PosedCharItem {...props} />
|
pub type Stage = (&'static str, &'static str);
#[derive(Copy, Clone)]
pub enum Category {
LastWarp,
Cavern,
Developer,
DragonRoostCavern,
DragonRoostIsland,
EarthTemple,
ForbiddenWoods,
ForestHaven,
ForsakenFortress,
GanonsTower,
GreatFairy,
Hyrule,
NintendoGallery,
Other,
Outset,
SavageLabyrinth,
Sea,
ToweroftheGods,
WindTemple,
Windfall,
}
pub static CATEGORIES: [(&str, Category); 20] = [
("Last Warp", Category::LastWarp),
("Cavern", Category::Cavern),
("Developer", Category::Developer),
("Dragon Roost Cavern", Category::DragonRoostCavern),
("Dragon Roost Island", Category::DragonRoostIsland),
("Earth Temple", Category::EarthTemple),
("Forbidden Woods", Category::ForbiddenWoods),
("Forest Haven", Category::ForestHaven),
("Forsaken Fortress", Category::ForsakenFortress),
("Ganon's Tower", Category::GanonsTower),
("Great Fairy", Category::GreatFairy),
("Hyrule", Category::Hyrule),
("Nintendo Gallery", Category::NintendoGallery),
("Other", Category::Other),
("Outset", Category::Outset),
("Savage Labyrinth", Category::SavageLabyrinth),
("Sea", Category::Sea),
("Tower of the Gods", Category::ToweroftheGods),
("Wind Temple", Category::WindTemple),
("Windfall", Category::Windfall),
];
pub static STAGES_CAVERN: &[Stage; 19] = &[
("Bomb Island", "Cave01"),
("Star Island", "Cave02"),
("Cliff Plateau Isles", "Cave03"),
("Rock Spire Isle", "Cave04"),
("Horseshoe Island", "Cave05"),
("Pawprint Isle Wizzrobe", "Cave07"),
("Shark Island", "ITest63"),
("Ice Ring Isle", "MiniHyo"),
("Fire Mountain", "MiniKaz"),
("Needle Rock Isle", "SubD42"),
("Angular Isles", "SubD43"),
("Boating Course", "SubD71"),
("Stone Watcher Island", "TF_01"),
("Overlook Island", "TF_02"),
("Birds Peak Rock", "TF_03"),
("Cabana", "TF_04"),
("Dragon Roost Island", "TF_06"),
("Pawprint Isle Chuchu", "TyuTyu"),
("Diamond Steppe Island", "WarpD"),
];
pub static STAGES_DEV: &[Stage; 45] = &[
("Invisible Island", "A_nami"),
("E3 Forest", "A_R00"),
("Amos T", "Amos_T"),
("Wind Temple", "Cave08"),
("Outset Island", "DmSpot0"),
("E3 Boating Course", "E3ROOP"),
("Island With House", "Ebesso"),
("Pig Chamber", "H_test"),
("Fire Cavern With Switches", "ITest61"),
("Ice Ring Isle Cavern", "ITest62"),
("Fire Mountain Cavern", "I_SubAN"),
("Basic Actions", "I_TestM"),
("Rope Room", "I_TestR"),
("Bridge Room", "KATA_HB"),
("Large Empty Room", "KATA_RM"),
("Fire Mountain", "kazan"),
("K Test2", "K_Test2"),
("K Test3", "K_Test3"),
("K Test4", "K_Test4"),
("K Test5", "K_Test5"),
("K Test6", "K_Test6"),
("K Test8", "K_Test8"),
("K Test9", "K_Test9"),
("K Testa", "K_Testa"),
("K Testb", "K_Testb"),
("K Testc", "K_Testc"),
("K Testd", "K_Testd"),
("K Teste", "K_Teste"),
("Camera Test", "morocam"),
("Smoke Test Room", "Msmoke"),
("Headstone Island", "Mukao"),
("Early Pirate Ship", "Obshop"),
("Dev Ending", "ENDumi"),
("Orcas Room", "Ojhous2"),
("Ghost Ship 1", "PShip2"),
("Ghost Ship 2", "PShip3"),
("Ghost Ship 3", "SubD45"),
("Ship Control Test", "sea_E"),
("Stone Watcher Island Cavern", "SubD44"),
("Bomb Island Cavern", "SubD51"),
("Decorative Pedestals", "TEST"),
("Dark Cavern With Switches", "TF_05"),
("Grotto With Darknuts", "TF_07"),
("Tingles Room", "tincle"),
("Basic Island", "VrTest"),
];
pub static STAGES_DRAGON_ROOST_CAVERN: &[Stage; 3] = &[
("Dungeon", "M_NewD2"),
("Boss", "M_DragB"),
("Mini Boss", "M_Dra09"),
];
pub static STAGES_DRAGON_ROOST_ISLAND: &[Stage; 3] = &[
("Pond", "Adanmae"),
("Komalis Room", "Comori"),
("Postal Service", "Atorizk"),
];
pub static STAGES_EARTH_TEMPLE: &[Stage; 4] = &[
("Entrance", "Edaichi"),
("Temple", "M_Dai"),
("Boss", "M_DaiB"),
("Mini Boss", "M_DaiMB"),
];
pub static STAGES_FORBIDDEN_WOODS: &[Stage; 3] = &[
("Dungeon", "kindan"),
("Boss", "kinBOSS"),
("Mini Boss", "kinMB"),
];
pub static STAGES_FOREST_HAVEN: &[Stage; 3] = &[
("Potion Room", "Ocrogh"),
("Forest Haven", "Omori"),
("Makars Hiding Place", "Otkura"),
];
pub static STAGES_FORSAKEN_FORTRESS: &[Stage; 7] = &[
("Ganondorfs Room", "M2ganon"),
("FF1 Tower", "Mjtower"),
("FF2 Tower", "M2tower"),
("FF1 Interior", "majroom"),
("FF2 Interior", "ma2room"),
("FF3 Interior", "ma3room"),
("FF1", "MajyuE"),
];
pub static STAGES_GANONS_TOWER: &[Stage; 15] = &[
("Entrance", "GanonA"),
("Room Towards Gohma", "GanonB"),
("Room Towards Molgera", "GanonC"),
("Room Towards Kalle Demos", "GanonD"),
("Room Towards Jalhalla", "GanonE"),
("Phantom Ganons Maze", "GanonJ"),
("Puppet Ganon", "GanonK"),
("Staircase Towards Puppet Ganon", "GanonL"),
("Main Room", "GanonM"),
("Staircase To Main Room", "GanonN"),
("Tower", "GTower"),
("Gohma", "Xboss0"),
("Kalle Demos", "Xboss1"),
("Jalhalla", "Xboss2"),
("Molgera", "Xboss3"),
];
pub static STAGES_GREAT_FAIRY: &[Stage; 6] = &[
("North", "Fairy01"),
("East", "Fairy02"),
("West", "Fairy03"),
("Forest Of Fairies", "Fairy04"),
("Thorned", "Fairy05"),
("South", "Fairy06"),
];
pub static STAGES_HYRULE: &[Stage; 3] = &[
("Castle", "Hyroom"),
("Field", "Hyrule"),
("Master Sword Chamber", "kenroom"),
];
pub static STAGES_NINTENDO_GALLERY: &[Stage; 8] = &[
("Great Sea", "figureA"),
("Windfall Island", "figureB"),
("Outset Island", "figureC"),
("Forsaken Fortress", "figureD"),
("Secret Cavern", "figureE"),
("Dragon Roost Island", "figureF"),
("Forest Haven", "figureG"),
("Main Room", "Pfigure"),
];
pub static STAGES_OTHER: &[Stage; 3] = &[
("Name Select", "Name"),
("Ending", "ENDING"),
("Title Screen", "sea_T"),
];
pub static STAGES_OUTSET: &[Stage; 7] = &[
("Links House", "LinkRM"),
("Under Links House", "LinkUG"),
("Forest Of Fairies", "A_mori"),
("Orcas Room", "Ojhous"),
("Mesas House", "Omasao"),
("Abe And Roses House", "Onobuta"),
("Jabuns Room", "Pjavdou"),
];
pub static STAGES_SAVAGE_LABYRINTH: &[Stage; 4] = &[
("Entrance", "Cave09"),
("Room11", "Cave10"),
("Room32", "Cave11"),
("End", "Cave06"),
];
pub static STAGES_SEA: &[Stage; 8] = &[
("Sea", "sea"),
("Tetras Ship Inside", "Asoko"),
("Tetras Ship Outside", "A umikz"),
("Submarine", "Abship"),
("Cabana", "Abesso"),
("Boating Course", "Ocean"),
("Ghost Ship", "PShip"),
("Islet Of Steel", "ShipD"),
];
pub static STAGES_TOWER_OF_THE_GODS: &[Stage; 4] = &[
("Dungeon", "Siren"),
("Boss", "SirenB"),
("Mini Boss", "SirenMB"),
("Outside", "ADMumi"),
];
pub static STAGES_WIND_TEMPLE: &[Stage; 4] = &[
("Entrance", "Ekaze"),
("Temple", "kaze"),
("Boss", "kazeB"),
("Mini Boss", "kazeMB"),
];
pub static STAGES_WINDFALL: &[Stage; 8] = &[
("Game Room", "Kaisen"),
("School Of Joy", "Nitiyou"),
("Bomb Shop", "Obombh"),
("Lenzos House", "Ocmera"),
("Cafe Bar", "Opub"),
("House Of Wealth", "Orichh"),
("Chu Jelly Juice Shop", "Pdrgsh"),
("Jail", "Pnezumi"),
];
pub static SEA_ROOMS: &[&str; 49] = &[
"Forsaken Fortress",
"Star Island",
"Northern Fairy Island",
"Gale Isle",
"Crescent Moon Island",
"Seven-Star Isles",
"Overlook Island",
"Four-Eye Reef",
"Mother and Child Isles",
"Spectacle Island",
"Windfall Island",
"Pawprint Isle",
"Dragon Roost Island",
"Flight Control Platform",
"Western Fairy Island",
"Rock Spire Isle",
"Tingle Island",
"Northern Triangle Island",
"Eastern Fairy Island",
"Fire Mountain",
"Star Belt Archipelago",
"Three-Eye Reef",
"Greatfish Isle",
"Cyclops Reef",
"Six-Eye Reef",
"Tower of the Gods",
"Eastern Triangle Island",
"Thorned Fairy Island",
"Needle Rock Isle",
"Islet of Steel",
"Stone Watcher Island",
"Southern Triangle Island",
"Private Oasis",
"Bomb Island",
"Bird's Peak Rock",
"Diamond Steppe Island",
"Five-Eye Reef",
"Shark Island",
"Southern Fairy Island",
"Ice Ring Isle",
"Forest Haven",
"Cliff Plateau Isles",
"Horseshoe Island",
"Outset Island",
"Headstone Island",
"Two-Eye Reef",
"Angular Isles",
"Boating Course",
"Five-Star Isles",
];
|
module Lazada
module API
module Image
def set_images(params)
url = request_url('Image')
params = { 'ProductImage' => params }
response = self.class.post(url, body: params.to_xml(root: 'Request', skip_types: true))
response
end
def migrate_image(image_url)
url = request_url('MigrateImage')
params = { 'Image' => { 'Url' => image_url } }
response = self.class.post(url, body: params.to_xml(root: 'Request', skip_types: true))
process_response_errors! response
response['SuccessResponse'].present? ? response['SuccessResponse']['Body']['Image']['Url'] : ''
end
def migrate_images(image_url_list)
url = request_url('MigrateImages')
# Allow duplicate keys in dict
urls = {}.compare_by_identity
image_url_list.each { |image_url| urls.merge!({ String.new('Url') => image_url }) }
params = { 'Images' => urls }
response = self.class.post(url, body: params.to_xml(root: 'Request', skip_types: true))
process_response_errors! response
# At the moment of this writing, the API does not seem to be working in Lazada
# The response is successful, but does not return a body with the details
# of the migrated images.
response['SuccessResponse'].present? ? response['SuccessResponse'] : nil
end
end
end
end
|
G_DURATION=10
START=100; STEP=100 END=100
OFFSET=5
CMD="LD_LIBRARY_PATH=../appgen/6month-demo ./halperf.py"
TYPE="bw"
ADDP="ipc:///tmp/hal"
RES="results_halperf_$G_DURATION_"
INT="--interval 10000"
run_g="$CMD -i ${ADDP}sub${TYPE}green -o ${ADDP}pub${TYPE}green -r 2 2 1 -t $G_DURATION $INT -Z -s 1 1 1 "
run_o="$CMD -i ${ADDP}sub${TYPE}orange -o ${ADDP}pub${TYPE}orange -r 1 1 1 -t $((G_DURATION+OFFSET)) $INT -s 2 2 1 "
DIR=$(pwd | sed 's:test/.*$:test/:')
# main loop
cd "$DIR"
for i in $(seq $START $STEP $END); do
eval ${run_o}$i -z ${RES}$i.csv &
sleep 2
eval ${run_g}$i
sleep $OFFSET
python3 plot_halperf.py -c ${RES}batch.csv -p results -i ${RES}$i.csv
cat ${RES}batch.csv
done
|
var firebase = require('firebase-admin')
var crypto = require('crypto')
function decrypt (encrypted) {
var decipher = crypto.createDecipheriv(algorithm, password, iv)
decipher.setAuthTag(encrypted.tag)
var dec = decipher.update(encrypted.content, 'hex', 'utf8')
dec += decipher.final('utf8')
return dec
}
var algorithm = 'aes-256-gcm'
var password = process.env.FIREBASE_PASSWORD
var iv = process.env.FIREBASE_IV
var encryptedPrivateKey = require('../private.enc.json')
encryptedPrivateKey.tag = Buffer.from(encryptedPrivateKey.tag.data)
var decryptedPrivateKey = JSON.parse(decrypt(encryptedPrivateKey))
firebase.initializeApp({
credential: firebase.credential.cert(decryptedPrivateKey),
databaseURL: 'https://webuildsg.firebaseio.com'
})
module.exports = firebase.database().ref('/')
|
package io.elytra.api.chat
/**
* Allows for a tooltip to be displayed when the player hovers their mouse over text.
*/
data class HoverEvent(val action: Action, val value: JsonComponent) : JsonComponent {
override fun toJson(buff: Appendable) {
buff.append('{')
buff.append("\"action\":\"").append(action.actionName).append('"')
buff.append(",\"value\":").append(value.toJson())
buff.append('}')
}
override fun toString(): String = toJson()
enum class Action(val actionName: String) {
/**
* Shows raw JSON text.
*/
SHOW_TEXT("show_text"),
/**
* Shows the tooltip of an item that can have NBT tags.
*/
SHOW_ITEM("show_item"),
/**
* Shows an entity's name, possibly its type, and its UUID.
*/
SHOW_ENTITY("show_entity")
}
}
|
import cors from 'cors';
import express from 'express';
import { json } from 'body-parser';
// book routes
import { createBook } from './routes/book/createBook';
import { updateBook } from './routes/book/updateBook';
import { deleteBook } from './routes/book/deleteBook';
import { getBookById } from './routes/book/getBookById';
import { getBookList } from './routes/book/getBookList';
// users routes
import { createUser } from './routes/users/createUser';
import { updateUser } from './routes/users/updateUser';
import { deleteUser } from './routes/users/deteleUser';
import { getUserById } from './routes/users/getUserById';
import { getUserList } from './routes/users/getUserList';
import { signIn } from './services/signIn';
import { lendBook } from './routes/book/lendBook';
import { giveBackBook } from './routes/book/giveBackBooks';
import { getUserLendBooks } from './routes/users/getUserLendBooks';
const app = express();
app.use(cors());
app.use(json());
// book routes
app.use(
createBook,
deleteBook,
updateBook,
getBookById,
getBookList
)
// users routes
app.use(
createUser,
deleteUser,
updateUser,
getUserById,
getUserList,
signIn,
lendBook,
giveBackBook,
getUserLendBooks,
)
export { app }
|
if defined?(ActiveAdmin) and News.config.engine_active_admin
ActiveAdmin.register News::Item, {:sort_order => :created_at} do
controller do
cache_sweeper News.config.news_item_sweeper if News.config.news_item_sweeper
defaults :finder => :find_by_url
end
menu :label => 'Story', :parent => "News", :priority => 1
index do
column :title
column :created_at
column :updated_at
column :text do |news_item|
news_item.text[0, 100]
end
column :lead_image do |news_item|
unless news_item.lead_image.blank?
image_tag news_item.lead_image(:thumb)
end
end
column :sticky
column :published do |news_item|
if news_item.published
"Yes"
else
"No"
end
end
column :author
default_actions
end
form do |f|
f.inputs "News Item" do
f.input :title
f.input :text
f.input :lead_image, :as => :file
f.input :author
f.input :published
f.has_many :related_links do |f_link|
f_link.inputs do
f_link.input :title
f_link.input :text
f_link.input :url, :input_html => {:placeholder => "http://www.example.com"}
f_link.input :image, :as => :file
end
end
end
f.actions
end
end
end
|
namespace MassTransit.RabbitMqTransport
{
using System;
using System.Text;
using RabbitMQ.Client;
public static class RabbitMqExtensions
{
/// <summary>
/// Close and dispose of a RabbitMQ channel without throwing any exceptions
/// </summary>
/// <param name="model">The channel (can be null)</param>
/// <param name="replyCode"></param>
/// <param name="message">Message for channel closure</param>
public static void Cleanup(this IModel model, ushort replyCode = 200, string message = "Unknown")
{
if (model != null)
{
try
{
if (model.IsOpen)
model.Close(replyCode, message);
}
catch (Exception)
{
}
model.Dispose();
}
}
/// <summary>
/// Close and dispose of a RabbitMQ connection without throwing any exceptions
/// </summary>
/// <param name="connection">The channel (can be null)</param>
/// <param name="replyCode"></param>
/// <param name="message">Message for channel closure</param>
public static void Cleanup(this IConnection connection, ushort replyCode = 200, string message = "Unknown")
{
if (connection != null)
{
try
{
if (connection.IsOpen)
connection.Close(replyCode, message);
}
catch (Exception)
{
}
}
}
public static string ToDescription(this RabbitMqHostSettings settings)
{
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(settings.Username))
sb.Append(settings.Username).Append('@');
sb.Append(settings.Host);
ClusterNode? actualHost = settings.EndpointResolver?.LastHost;
if (actualHost != null)
sb.Append('(').Append(actualHost).Append(')');
if (settings.Port != -1)
sb.Append(':').Append(settings.Port);
if (string.IsNullOrWhiteSpace(settings.VirtualHost))
sb.Append('/');
else if (settings.VirtualHost.StartsWith("/"))
sb.Append(settings.VirtualHost);
else
sb.Append("/").Append(settings.VirtualHost);
return sb.ToString();
}
}
}
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\AdminRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
class QuanTriVienController extends Controller
{
protected $rederectTo = 'trang-chu';
public function dangnhap()
{
return view('dang-nhap');
}
public function xulyDangNhap(AdminRequest $request)
{
//$validated = $request->validated();
$ten_dang_nhap = $request->ten_dang_nhap;
$mat_khau = $request->mat_khau;
if(Auth::attempt(['ten_dang_nhap' => $ten_dang_nhap, 'password' => $mat_khau])){
return \redirect()->route('trang-chu')->with('thong_diep','Đăng nhập thành công');
}
return redirect()->route('dang_nhap')->with('thong_diep','Đăng nhập thất bại');
}
public function dangXuat(){
Auth::logout();
return redirect()->route('dang_nhap');
}
public function layThongTin(){
return Auth::user();
}
}
|
package com.escodro.task.di
import com.escodro.task.mapper.AlarmIntervalMapper
import com.escodro.task.mapper.CategoryMapper
import com.escodro.task.mapper.TaskMapper
import com.escodro.task.mapper.TaskWithCategoryMapper
import com.escodro.task.presentation.add.AddTaskViewModel
import com.escodro.task.presentation.detail.alarm.TaskAlarmViewModel
import com.escodro.task.presentation.detail.main.TaskDetailViewModel
import com.escodro.task.presentation.list.TaskListViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
/**
* Task dependency injection module.
*/
val taskModule = module {
// Presentation
viewModel { TaskListViewModel(get(), get(), get()) }
viewModel { TaskDetailViewModel(get(), get(), get(), get(), get()) }
viewModel { TaskAlarmViewModel(get(), get(), get(), get()) }
viewModel { AddTaskViewModel(get()) }
// Mappers
factory { AlarmIntervalMapper() }
factory { TaskMapper(get()) }
factory { TaskWithCategoryMapper(get(), get()) }
factory { CategoryMapper() }
}
|
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: Scaffold(
body: ListaTransferencias(),
appBar: AppBar(
title: Text('Transferências'),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.home),
),
),
));
class ListaTransferencias extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Column(children: <Widget>[
ItemTransferencia(Transferencia(100, 1000)),
ItemTransferencia(Transferencia(200, 1001)),
ItemTransferencia(Transferencia(300, 2000)),
]);
}
}
class ItemTransferencia extends StatelessWidget {
final Transferencia _transferencia;
ItemTransferencia(this._transferencia);
@override
Widget build(BuildContext context) {
// TODO: implement build
return Card(
child: ListTile(
leading: Icon(Icons.monetization_on),
title: Text(_transferencia.valor.toString()),
subtitle: Text(_transferencia.numeroConta.toString()),
),
);
}
}
class Transferencia {
final double valor;
final int numeroConta;
Transferencia(this.valor, this.numeroConta);
}
|
; Basic Axe rules about BVs
;
; Copyright (C) 2008-2011 Eric Smith and Stanford University
; Copyright (C) 2013-2020 Kestrel Institute
; Copyright (C) 2016-2020 Kestrel Technology, LLC
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: Eric Smith (eric.smith@kestrel.edu)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
;; Simple rules needed by Axe but not by ACL2 (e.g., because ACL2 uses
;; :type-prescription rules but Axe does not). Unlike bv-rules-axe.lisp, this
;; file does not use the Axe syntax functions.
(include-book "kestrel/bv/bvplus" :dir :system)
(include-book "kestrel/bv/bvxor" :dir :system)
(include-book "kestrel/bv/bvor" :dir :system)
(include-book "kestrel/bv/bvnot" :dir :system)
(include-book "kestrel/bv/bvand" :dir :system)
(include-book "kestrel/bv/bitxor" :dir :system)
(include-book "kestrel/bv/sbvlt" :dir :system)
(include-book "kestrel/bv/bvlt" :dir :system)
(include-book "kestrel/bv/rotate" :dir :system)
; TODO: Disable all of these?
(defthm integerp-of-bvplus
(integerp (bvplus size x y)))
(defthm natp-of-bvplus
(natp (bvplus size x y)))
(defthm integerp-of-floor
(integerp (floor i j)))
(defthm rational-of-floor
(rationalp (floor i j)))
(defthm acl2-numberp-of-floor
(acl2-numberp (floor i j)))
(defthm integerp-of-leftrotate
(integerp (leftrotate width amt val)))
(defthm integerp-of-leftrotate32
(integerp (leftrotate32 amt val)))
(defthm natp-of-leftrotate
(natp (leftrotate width amt val)))
(defthm natp-of-leftrotate32
(natp (leftrotate32 amt val))
:hints (("Goal" :in-theory (enable leftrotate32))))
(defthm leftrotate32-non-negative
(not (< (leftrotate32 amt val) 0))
:hints (("Goal" :in-theory (enable leftrotate32))))
(defthm integerp-of-rightrotate
(integerp (rightrotate width amt val)))
(defthm integerp-of-rightrotate32
(integerp (rightrotate32 amt val)))
(defthm natp-of-rightrotate
(natp (rightrotate width amt val)))
(defthm natp-of-rightrotate32
(natp (rightrotate32 amt val))
:hints (("Goal" :in-theory (enable rightrotate32))))
(defthm integerp-of-bvcat
(integerp (bvcat highsize highval lowsize lowval)))
;improve logapp-<-0?
(defthm bvcat-non-negative
(not (< (bvcat highsize highval lowsize lowval) 0))
:hints (("Goal" :in-theory (e/d (bvcat natp) ()))))
(defthm integerp-of-bvxor
(integerp (bvxor size x y)))
(defthm natp-of-bvxor
(natp (bvxor size x y)))
(defthm integerp-of-bitxor
(integerp (bitxor x y)))
(defthm natp-of-bitxor
(natp (bitxor x y)))
(defthm natp-of-bvcat
(natp (bvcat highsize highval lowsize lowval)))
(defthm integerp-of-bvand
(integerp (bvand size x y)))
(defthm natp-of-bvand
(natp (bvand size x y)))
(defthm integerp-of-bvor
(integerp (bvor size x y)))
(defthm natp-of-bvor
(natp (bvor size x y)))
(defthm bvor-non-negative
(not (< (bvor size x y) 0)))
;only needed by Axe
(defthm integerp-of-bvnot
(integerp (bvnot size x)))
;only needed by Axe
(defthm natp-of-bvnot
(natp (bvnot size x)))
;only needed by Axe
(defthm acl2-numberp-of-mod
(acl2-numberp (mod x y)))
;; Only needed for Axe
(defthm booleanp-of-sbvlt
(booleanp (sbvlt size x y)))
;; Only needed for Axe
(defthm booleanp-of-sbvle
(booleanp (sbvle size x y)))
;; Only needed for Axe
;or just open bvle
(defthm booleanp-of-bvle
(booleanp (bvle size x y)))
|
package com.carlosedp.scalautils.riscvassembler.internal
import com.carlosedp.scalautils.ObjectUtils._
object InstructionParser {
/** Parse an assembly instruction and return the opcode and opdata
*
* @param input
* the assembly instruction string
* @return
* the opcode and opdata
*/
def apply(
input: String
): (Map[String, String], Map[String, Long]) = {
var instructionParts = input.trim.split("[\\s,\\(\\)]+").filter(_.nonEmpty)
val inst = Instructions(instructionParts(0).toUpperCase)
// Check here if it's a pseudo instruction
if (inst.contains("pseudo_inst")) {
instructionParts = PseudoInstructions(instructionParts)
}
inst("inst_type") match {
case "INST_R" =>
(
inst,
Map(
"rd" -> RegMap(instructionParts(1)),
"rs1" -> RegMap(instructionParts(2)),
"rs2" -> RegMap(instructionParts(3))
)
)
case "INST_I" => {
if (inst.contains("has_offset")) {
val imm =
if (instructionParts(2).startsWith("0x")) BigInt(instructionParts(2).substring(2), 16).toLong
else instructionParts(2).toLong
(
inst,
Map(
"rd" -> RegMap(instructionParts(1)),
"rs1" -> RegMap(instructionParts(3)),
"imm" -> imm
)
)
} else {
val imm =
if (instructionParts(3).startsWith("0x")) BigInt(instructionParts(3).substring(2), 16).toLong
else instructionParts(3).toLong
(
inst,
Map(
"rd" -> RegMap(instructionParts(1)),
"rs1" -> RegMap(instructionParts(2)),
"imm" -> imm
)
)
}
}
case "INST_S" => {
val imm =
if (instructionParts(2).startsWith("0x")) BigInt(instructionParts(2).substring(2), 16).toLong
else instructionParts(2).toLong
(
inst,
Map(
"rs2" -> RegMap(instructionParts(1)),
"rs1" -> RegMap(instructionParts(3)),
"imm" -> imm
)
)
}
case "INST_B" => {
val imm =
if (instructionParts(3).startsWith("0x")) BigInt(instructionParts(3).substring(2), 16).toLong
else instructionParts(3).toLong
(
inst,
Map(
"rs1" -> RegMap(instructionParts(1)),
"rs2" -> RegMap(instructionParts(2)),
"imm" -> imm
)
)
}
case "INST_U" => {
val imm =
if (instructionParts(2).startsWith("0x")) BigInt(instructionParts(2).substring(2), 16).toLong
else instructionParts(2).toLong
(inst, Map("rd" -> RegMap(instructionParts(1)), "imm" -> imm))
}
case "INST_J" => {
val imm =
if (instructionParts(2).startsWith("0x")) BigInt(instructionParts(2).substring(2), 16).toLong
else instructionParts(2).toLong
(inst, Map("rd" -> RegMap(instructionParts(1)), "imm" -> imm))
}
}
}
}
object FillInstruction {
/** Fills the instruction arguments based on instruction type
*
* @param instType
* the instruction type
* @param data
* the received instruction arguments
* @param op
* the instruction opcode and type
* @return
* the filled instruction binary
*/
def apply(instType: String, data: Map[String, Long], op: Map[String, String]): String =
instType match {
case "INST_R" => {
val rd = data("rd").toBinaryString.padZero(5)
val rs1 = data("rs1").toBinaryString.padZero(5)
val rs2 = data("rs2").toBinaryString.padZero(5)
op("funct7") + rs2 + rs1 + op("funct3") + rd + op("opcode")
}
case "INST_I" => {
val rd = data("rd").toBinaryString.padZero(5)
val rs1 = data("rs1").toBinaryString.padZero(5)
val imm = data("imm").to32Bit.toBinaryString.padZero(12)
imm + rs1 + op("funct3") + rd + op("opcode")
}
case "INST_S" => {
val rs1 = data("rs1").toBinaryString.padZero(5)
val rs2 = data("rs2").toBinaryString.padZero(5)
val imm = data("imm").to32Bit.toBinaryString.padZero(12).reverse // reverse to have binary in little endian
imm.slice(5, 12).reverse + rs2 + rs1 + op("funct3") + imm.slice(0, 5).reverse + op("opcode")
}
case "INST_B" => {
val rs1 = data("rs1").toBinaryString.padZero(5)
val rs2 = data("rs2").toBinaryString.padZero(5)
val imm = data("imm").to32Bit.toBinaryString.padZero(13).reverse // reverse to have binary in little endian
imm.slice(12, 13).reverse + imm.slice(5, 11).reverse + rs2 + rs1 + op("funct3") +
imm.slice(1, 5).reverse + imm.slice(11, 12).reverse + op("opcode")
}
case "INST_U" => {
val rd = data("rd").toBinaryString.padZero(5)
val imm = data("imm").to32Bit.toBinaryString.padZero(32).take(20)
imm + rd + op("opcode")
}
case "INST_J" => {
val rd = data("rd").toBinaryString.padZero(5)
val imm = data("imm").to32Bit.toBinaryString.padZero(21).reverse // reverse to have binary in little endian
imm.slice(20, 21).reverse + imm.slice(1, 11).reverse + imm.slice(11, 12).reverse + imm
.slice(12, 20)
.reverse + rd + op(
"opcode"
)
}
}
}
object GenHex {
/** Generate the hex string of the instruction from binary
*
* @param input
* the binary string of the instruction
* @return
* the hex string of the instruction
*/
def apply(
input: String
): String = {
// Make this 64bit in the future
val x = BigInt(input, 2).toLong
f"0x$x%08X".toString.takeRight(8)
}
}
object RegMap {
/** Maps the register name or ABI name to the register number
*
* @param regName
* the register name
* @return
* the register number
*/
def apply(
input: String
): Long =
input match {
case "x0" | "zero" => 0
case "x1" | "ra" => 1
case "x2" | "sp" => 2
case "x3" | "gp" => 3
case "x4" | "tp" => 4
case "x5" | "t0" => 5
case "x6" | "t1" => 6
case "x7" | "t2" => 7
case "x8" | "s0" | "fp" => 8
case "x9" | "s1" => 9
case "x10" | "a0" => 10
case "x11" | "a1" => 11
case "x12" | "a2" => 12
case "x13" | "a3" => 13
case "x14" | "a4" => 14
case "x15" | "a5" => 15
case "x16" | "a6" => 16
case "x17" | "a7" => 17
case "x18" | "s2" => 18
case "x19" | "s3" => 19
case "x20" | "s4" => 20
case "x21" | "s5" => 21
case "x22" | "s6" => 22
case "x23" | "s7" => 23
case "x24" | "s8" => 24
case "x25" | "s9" => 25
case "x26" | "s10" => 26
case "x27" | "s11" => 27
case "x28" | "t3" => 28
case "x29" | "t4" => 29
case "x30" | "t5" => 30
case "x31" | "t6" => 31
}
}
|
namespace Reportr.Data
{
using Reportr.Data.Querying;
using System;
using System.Linq;
/// <summary>
/// Represents a single data binding
/// </summary>
public sealed class DataBinding
{
/// <summary>
/// Constructs the data binding with the details
/// </summary>
/// <param name="expression">The expression</param>
public DataBinding
(
string expression
)
: this(DataBindingType.QueryPath, expression)
{ }
/// <summary>
/// Constructs the data binding with the details
/// </summary>
/// <param name="bindingType">The binding type</param>
/// <param name="expression">The expression</param>
public DataBinding
(
DataBindingType bindingType,
string expression
)
{
Validate.IsNotEmpty(expression);
this.BindingType = bindingType;
this.Expression = expression;
}
/// <summary>
/// Gets the data binding type
/// </summary>
public DataBindingType BindingType { get; private set; }
/// <summary>
/// Gets the binding expression
/// </summary>
/// <remarks>
/// The expression syntax varies depending on the binding
/// type, but the result is always returned as an object.
/// </remarks>
public string Expression { get; private set; }
/// <summary>
/// Resolves the data binding value using a query row
/// </summary>
/// <param name="row">The query row</param>
/// <returns>The resolved value</returns>
public object Resolve
(
QueryRow row
)
{
Validate.IsNotNull(row);
switch (this.BindingType)
{
case DataBindingType.TemplateContent:
return ResolveTemplateContent(row);
case DataBindingType.MathExpression:
return ResolveMathExpression(row);
default:
return ResolveQueryPath(row);
}
}
/// <summary>
/// Resolves the data binding value using a query row
/// </summary>
/// <typeparam name="T">The value type to resolve</typeparam>
/// <param name="row">The query row</param>
/// <returns>The resolved value as the type specified</returns>
public T Resolve<T>
(
QueryRow row
)
{
var rawValue = Resolve(row);
return new ObjectConverter<T>().Convert
(
rawValue
);
}
/// <summary>
/// Resolves the query path for a query row specified
/// </summary>
/// <param name="row">The query row</param>
/// <returns>The resolved value</returns>
private object ResolveQueryPath
(
QueryRow row
)
{
var pathInfo = new QueryPathInfo
(
this.Expression
);
var columnName = pathInfo.ColumnName;
var currentValue = row[columnName].Value;
if (currentValue == null)
{
return row[columnName].Value;
}
else
{
var currentPath = columnName;
var currentType = currentValue.GetType();
foreach (var propertyName in pathInfo.NestedProperties)
{
if (currentValue == null)
{
throw new NullReferenceException
(
$"The path '{currentPath}' has a null reference."
);
}
var nextPropertyFound = currentType.GetProperties().Any
(
p => p.Name == propertyName
);
if (false == nextPropertyFound)
{
throw new MissingFieldException
(
$"'{currentPath}' does not contain the property '{propertyName}'."
);
}
var nextProperty = currentType.GetProperty
(
propertyName
);
currentValue = nextProperty.GetValue
(
currentValue
);
currentPath += "." + propertyName;
}
return currentValue;
}
}
/// <summary>
/// Resolves the template content for a query row
/// </summary>
/// <param name="row">The query row</param>
/// <returns>The resolved content</returns>
private string ResolveTemplateContent
(
QueryRow row
)
{
var template = this.Expression;
var renderer = ReportrEngine.TemplateRenderer;
if (renderer == null)
{
throw new InvalidOperationException
(
"The template renderer has not been configured."
);
}
return renderer.Render
(
template,
row
);
}
/// <summary>
/// Resolves the math expression for a query row
/// </summary>
/// <param name="row">The query row</param>
/// <returns>The resolved value</returns>
private object ResolveMathExpression
(
QueryRow row
)
{
var expression = ResolveTemplateContent
(
row
);
var evaluator = ReportrEngine.MathEvaluator;
if (evaluator == null)
{
throw new InvalidOperationException
(
"The math expression evaluator has not been configured."
);
}
return evaluator.Evaluate
(
expression
);
}
}
}
|
(ns aoc2019.day02.core
(:require [intcode.core :refer [run]]))
(defn inc-verb
"Increment verb"
[verb]
(if (= verb 99)
0
(inc verb)))
(defn inc-noun
"Increment noun"
[noun verb]
(if (= verb 99)
(inc noun)
noun))
(defn day02a
"Calculate int codes for puzzle input"
[program]
(first (:memory (run program))))
(defn day02b
"Calculate int codes for puzzle input"
[program noun verb target]
(let [memory (assoc (assoc (:memory program) 1 noun) 2 verb)
result (day02a (run (assoc program :memory memory)))]
(if (= result target)
(+ (* 100 noun) verb)
(recur program (inc-noun noun verb) (inc-verb verb) target))))
|
#!/bin/bash
set -e
RETRIES=50
while [ $RETRIES -gt 0 ]; do
if $(curl --connect-timeout 30 --speed-time 60 --speed-limit 1000 "$@"); then
exit 0
else
RETRIES=$((RETRIES - 1))
PAUSE=$(( ( RANDOM % 5 ) + 1 ))
echo "Retry in $PAUSE seconds, $RETRIES times remaining..."
sleep "$PAUSE"
fi
done
exit 1
|
package stat
import (
"crypto/sha256"
"encoding/binary"
"os"
"path/filepath"
"sort"
"github.com/bmatcuk/doublestar"
)
type Stater struct {
checkContent bool
}
func New(checkContent bool) *Stater {
s := &Stater{
checkContent: checkContent,
}
return s
}
// Stat creates a hash of all the files given by expr (using root), either
// by using contents of files or only the mod-time.
// TODO: include a ref to cache so we can write for each individual file
func (s *Stater) Stat(root string, expr string) (hash []byte, err error) {
if !filepath.IsAbs(expr) {
expr = filepath.Join(root, expr)
}
files, err := doublestar.Glob(expr)
if err != nil {
return nil, err
}
h := sha256.New224()
// We must be carefull with the ordering when hashing
sort.Strings(files)
for _, f := range files {
// TODO: Stat or LStat - should also be configurable?
fi, err := os.Stat(f) // Todo - really should be merged with the recursive directory handling
if err != nil {
return nil, err
}
binary.Write(h, binary.BigEndian, fi.Name())
binary.Write(h, binary.BigEndian, fi.Size())
binary.Write(h, binary.BigEndian, fi.ModTime().UnixNano())
}
return h.Sum(nil), nil
}
|
// Copyright 2021 Datafuse Labs.
//
// 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.
use std::fmt;
use anyerror::AnyError;
use core_sled::{sled, SledOrderedSerde, SledStorageError};
use serde::{Deserialize, Serialize};
use sled::IVec;
use crate::types::openraft::{EffectiveMembership, LogId, NodeId, Vote};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum LogMetaKey {
/// The last purged log id in the log.
///
/// Log entries are purged after being applied to state machine.
/// Even when all logs are purged the last purged log id has to be stored.
/// Because raft replication requires logs to be consecutive.
LastPurged,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, derive_more::TryInto)]
pub enum LogMetaValue {
LogId(LogId),
}
impl fmt::Display for LogMetaKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LogMetaKey::LastPurged => {
write!(f, "last-purged")
}
}
}
}
impl SledOrderedSerde for LogMetaKey {
fn ser(&self) -> Result<IVec, SledStorageError> {
let i = match self {
LogMetaKey::LastPurged => 1,
};
Ok(IVec::from(&[i]))
}
fn de<V: AsRef<[u8]>>(v: V) -> Result<Self, SledStorageError>
where
Self: Sized,
{
let slice = v.as_ref();
if slice[0] == 1 {
return Ok(LogMetaKey::LastPurged);
}
Err(SledStorageError::SledError(AnyError::error(
"invalid key IVec",
)))
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum RaftStateKey {
/// The node id.
Id,
Vote,
/// The id of the only active state machine.
/// When installing a state machine snapshot:
/// 1. A temp state machine is written into a new sled::Tree.
/// 2. Update this field to point to the new state machine.
/// 3. Cleanup old state machine.
StateMachineId,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RaftStateValue {
NodeId(NodeId),
Vote(Vote),
/// active state machine, previous state machine
StateMachineId((u64, u64)),
}
impl fmt::Display for RaftStateKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RaftStateKey::Id => {
write!(f, "Id")
}
RaftStateKey::Vote => {
write!(f, "Vote")
}
RaftStateKey::StateMachineId => {
write!(f, "StateMachineId")
}
}
}
}
impl SledOrderedSerde for RaftStateKey {
fn ser(&self) -> Result<IVec, SledStorageError> {
let i = match self {
RaftStateKey::Id => 1,
RaftStateKey::Vote => 2,
RaftStateKey::StateMachineId => 3,
};
Ok(IVec::from(&[i]))
}
fn de<V: AsRef<[u8]>>(v: V) -> Result<Self, SledStorageError>
where
Self: Sized,
{
let slice = v.as_ref();
match slice[0] {
1 => Ok(RaftStateKey::Id),
2 => Ok(RaftStateKey::Vote),
3 => Ok(RaftStateKey::StateMachineId),
_ => Err(SledStorageError::SledError(AnyError::error(
"invalid key IVec",
))),
}
}
}
impl From<RaftStateValue> for NodeId {
fn from(v: RaftStateValue) -> Self {
match v {
RaftStateValue::NodeId(x) => x,
_ => panic!("expect NodeId"),
}
}
}
impl From<RaftStateValue> for Vote {
fn from(v: RaftStateValue) -> Self {
match v {
RaftStateValue::Vote(vt) => vt,
_ => panic!("expect Vote"),
}
}
}
impl From<RaftStateValue> for (u64, u64) {
fn from(v: RaftStateValue) -> Self {
match v {
RaftStateValue::StateMachineId(x) => x,
_ => panic!("expect StateMachineId"),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum FSMMetaKey {
/// The last applied log id in the state machine.
LastApplied,
/// Whether the state machine is initialized.
Initialized,
/// The last membership config
LastMembership,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, derive_more::TryInto)]
pub enum StateMachineMetaValue {
LogId(LogId),
Bool(bool),
Membership(EffectiveMembership),
}
impl fmt::Display for FSMMetaKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FSMMetaKey::LastApplied => {
write!(f, "last-applied")
}
FSMMetaKey::Initialized => {
write!(f, "initialized")
}
FSMMetaKey::LastMembership => {
write!(f, "last-membership")
}
}
}
}
impl SledOrderedSerde for FSMMetaKey {
fn ser(&self) -> Result<IVec, SledStorageError> {
let i = match self {
FSMMetaKey::LastApplied => 1,
FSMMetaKey::Initialized => 2,
FSMMetaKey::LastMembership => 3,
};
Ok(IVec::from(&[i]))
}
fn de<V: AsRef<[u8]>>(v: V) -> Result<Self, SledStorageError>
where
Self: Sized,
{
let slice = v.as_ref();
if slice[0] == 1 {
return Ok(FSMMetaKey::LastApplied);
} else if slice[0] == 2 {
return Ok(FSMMetaKey::Initialized);
} else if slice[0] == 3 {
return Ok(FSMMetaKey::LastMembership);
}
Err(SledStorageError::SledError(AnyError::error(
"invalid key IVec",
)))
}
}
|
#!/usr/bin/env node
import { convertNpmVersion } from "../lib";
if(process.argv.length !== 3) {
console.error(`Usage: npm-get-version <package>@<tag>~<N>`);
process.exit(1);
}
try {
const res = convertNpmVersion(process.argv[2]);
console.log(res);
} catch (error) {
console.error(`Error [${error.code}]: ${error.message}`);
process.exit(1);
}
|
import unittest
from src.homework.d_repetition.repetition import get_factorial
from src.homework.d_repetition.repetition import sum_odd_numbers
class Test_Config(unittest.TestCase):
def test_factorial(self):
self.assertEqual(get_factorial(5),120)
def test_sum_odd_numbers(self):
self.assertEqual(sum_odd_numbers(8), 16)
|
using System;
using System.Linq;
using System.Threading.Tasks;
using Gress;
using MaterialDesignThemes.Wpf;
using Stylet;
using Tyrrrz.Extensions;
using YoutubeDownloader.Internal.Extensions;
using YoutubeDownloader.Models;
using YoutubeDownloader.Services;
using YoutubeDownloader.ViewModels.Components;
using YoutubeDownloader.ViewModels.Dialogs;
using YoutubeDownloader.ViewModels.Framework;
using YoutubeExplode.Exceptions;
namespace YoutubeDownloader.ViewModels
{
public class RootViewModel : Screen
{
private readonly IViewModelFactory _viewModelFactory;
private readonly DialogManager _dialogManager;
private readonly SettingsService _settingsService;
private readonly UpdateService _updateService;
private readonly QueryService _queryService;
private readonly DownloadService _downloadService;
public ISnackbarMessageQueue Notifications { get; } = new SnackbarMessageQueue(TimeSpan.FromSeconds(5));
public IProgressManager ProgressManager { get; } = new ProgressManager();
public bool IsBusy { get; private set; }
public bool IsProgressIndeterminate { get; private set; }
public string? Query { get; set; }
public BindableCollection<DownloadViewModel> Downloads { get; } = new BindableCollection<DownloadViewModel>();
public RootViewModel(IViewModelFactory viewModelFactory, DialogManager dialogManager,
SettingsService settingsService, UpdateService updateService, QueryService queryService,
DownloadService downloadService)
{
_viewModelFactory = viewModelFactory;
_dialogManager = dialogManager;
_settingsService = settingsService;
_updateService = updateService;
_queryService = queryService;
_downloadService = downloadService;
// Title
DisplayName = $"{App.Name} v{App.VersionString}";
// Update busy state when progress manager changes
ProgressManager.Bind(o => o.IsActive,
(sender, args) => IsProgressIndeterminate =
ProgressManager.IsActive && ProgressManager.Progress.IsEither(0, 1)
);
ProgressManager.Bind(o => o.Progress,
(sender, args) => IsProgressIndeterminate =
ProgressManager.IsActive && ProgressManager.Progress.IsEither(0, 1)
);
}
private async Task CheckForUpdatesAsync()
{
try
{
// Check for updates
var updateVersion = await _updateService.CheckForUpdatesAsync();
if (updateVersion == null)
return;
// Notify user of an update and prepare it
Notifications.Enqueue($"Downloading update to {App.Name} v{updateVersion}...");
await _updateService.PrepareUpdateAsync(updateVersion);
// Prompt user to install update (otherwise install it when application exits)
Notifications.Enqueue(
"Update has been downloaded and will be installed when you exit",
"INSTALL NOW", () =>
{
_updateService.FinalizeUpdate(true);
RequestClose();
});
}
catch
{
// Failure to update shouldn't crash the application
Notifications.Enqueue("Failed to perform application update");
}
}
protected override async void OnViewLoaded()
{
base.OnViewLoaded();
_settingsService.Load();
if (_settingsService.IsDarkModeEnabled)
{
App.SetDarkTheme();
}
else
{
App.SetLightTheme();
}
await CheckForUpdatesAsync();
}
protected override void OnClose()
{
base.OnClose();
_settingsService.Save();
// Cancel all downloads
foreach (var download in Downloads)
download.Cancel();
_updateService.FinalizeUpdate(false);
}
public bool CanShowSettings => !IsBusy;
public async void ShowSettings()
{
var dialog = _viewModelFactory.CreateSettingsViewModel();
await _dialogManager.ShowDialogAsync(dialog);
}
private void EnqueueDownload(DownloadViewModel download)
{
// Cancel and remove downloads with the same file path
var existingDownloads = Downloads.Where(d => d.FilePath == download.FilePath).ToArray();
foreach (var existingDownload in existingDownloads)
{
existingDownload.Cancel();
Downloads.Remove(existingDownload);
}
// Bind progress manager
download.ProgressManager = ProgressManager;
download.Start();
Downloads.Insert(0, download);
}
public bool CanProcessQuery => !IsBusy && !string.IsNullOrWhiteSpace(Query);
public async void ProcessQuery()
{
// Small operation weight to not offset any existing download operations
var operation = ProgressManager.CreateOperation(0.01);
IsBusy = true;
try
{
var parsedQueries = _queryService.ParseMultilineQuery(Query!);
var executedQueries = await _queryService.ExecuteQueriesAsync(parsedQueries, operation);
var videos = executedQueries.SelectMany(q => q.Videos).Distinct(v => v.Id).ToArray();
var dialogTitle = executedQueries.Count == 1
? executedQueries.Single().Title
: "Multiple queries";
// No videos found
if (videos.Length <= 0)
{
var dialog = _viewModelFactory.CreateMessageBoxViewModel(
"Nothing found",
"Couldn't find any videos based on the query or URL you provided"
);
await _dialogManager.ShowDialogAsync(dialog);
}
// Single video
else if (videos.Length == 1)
{
var video = videos.Single();
var downloadOptions = await _downloadService.GetVideoDownloadOptionsAsync(video.Id);
var subtitleOptions = await _downloadService.GetSubtitleDownloadOptionsAsync(video.Id);
var dialog = _viewModelFactory.CreateDownloadSingleSetupViewModel(
dialogTitle,
video,
downloadOptions,
subtitleOptions
);
var download = await _dialogManager.ShowDialogAsync(dialog);
if (download == null) // generics + NRTs issue
return;
EnqueueDownload(download);
}
// Multiple videos
else
{
var dialog = _viewModelFactory.CreateDownloadMultipleSetupViewModel(
dialogTitle,
videos
);
// Preselect all videos if none of the videos come from a search query
if (executedQueries.All(q => q.Query.Kind != QueryKind.Search))
dialog.SelectedVideos = dialog.AvailableVideos;
var downloads = await _dialogManager.ShowDialogAsync(dialog);
if (downloads == null) // generics + NRTs issue
return;
foreach (var download in downloads)
EnqueueDownload(download);
}
}
catch (Exception ex)
{
var dialog = _viewModelFactory.CreateMessageBoxViewModel(
"Error",
// Short error message for expected errors, full for unexpected
ex is YoutubeExplodeException
? ex.Message
: ex.ToString()
);
await _dialogManager.ShowDialogAsync(dialog);
}
finally
{
operation.Dispose();
IsBusy = false;
}
}
public void RemoveDownload(DownloadViewModel download)
{
download.Cancel();
Downloads.Remove(download);
}
public void RemoveInactiveDownloads() =>
Downloads.RemoveWhere(d => !d.IsActive);
public void RemoveSuccessfulDownloads() =>
Downloads.RemoveWhere(d => d.IsSuccessful);
public void RestartFailedDownloads()
{
var failedDownloads = Downloads.Where(d => d.IsFailed).ToArray();
foreach (var failedDownload in failedDownloads)
failedDownload.Restart();
}
}
}
|
require 'debugger_xml/ide/control_command_processor'
module DebuggerXml
module Vim
class ControlCommandProcessor < Ide::ControlCommandProcessor
def initialize(*args)
super(*args)
@mutex = Mutex.new
end
def process_command(*args)
@mutex.synchronize do
super(*args)
@interface.send_response
end
end
end
end
end
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EndGame : MonoBehaviour {
[SerializeField]
Text endgametext;
private void Start()
{
}
public void endgamemsg(int lcikills, int lcakills,int scorelimit)
{
if (lcikills > lcakills && lcikills >= scorelimit)
{
endgametext.text = "ツンデレ・ロリス勝利. Bow before their cuteness";
}
else if (lcakills > lcikills && lcakills >= scorelimit)
{
endgametext.text = "ヤンダレロリス勝利. Run from their jealousy";
}
}
}
|
function focus() {
document.getElementById("readline").focus();
}
function jrun() {
var expr = document.getElementById("readline").value ;
var checked = document.getElementById("lambda").checked ;
document.getElementById("term").innerHTML +=
expr + "<br />";
document.getElementById("readline").value = "";
document.getElementById("term").innerHTML +=
run(checked, expr) + "phalang15> ";
focus();
}
|
# build gybs
cd Sources/gyb/
./generate_py_stub_models.py
./gyb.py --line-directive '' -o "types.swift" "types.swift.gyb"
./gyb.py --line-directive '' -o "description.swift" "description.swift.gyb"
./gyb.py --line-directive '' -o "wrappers.swift" "wrappers.swift.gyb"
./gyb.py --line-directive '' -o "builders.swift" "builders.swift.gyb"
./gyb.py --line-directive '' -o "syntaxtowrappers.swift" "syntaxtowrappers.swift.gyb"
./gyb.py --line-directive '' -o "wrapperremoverhelper.swift" "wrapperremoverhelper.swift.gyb"
./gyb.py --line-directive '' -o "typealiases.swift" "typealiases.swift.gyb"
# copy resulting swift files
cd ../../
cp "Sources/gyb/types.swift" "Sources/BinarySwiftAST/_generated_types.swift"
cp "Sources/gyb/description.swift" "Sources/BinarySwiftAST/_generated_description.swift"
cp "Sources/gyb/wrappers.swift" "Sources/BinarySwiftASTWrappers/_generated_wrappers.swift"
cp "Sources/gyb/typealiases.swift" "Sources/BinarySwiftASTWrappers/_generated_typealiases.swift"
cp "Sources/gyb/builders.swift" "Sources/WrapperBuilders/_generated_builders.swift"
cp "Sources/gyb/syntaxtowrappers.swift" "Sources/BinarySwiftASTConstructor/_generated_syntaxtowrappers.swift"
cp "Sources/gyb/wrapperremoverhelper.swift" "Sources/ASTWrapperRemover/_generated_wrapperremoverhelper.swift"
# delete originals
rm "Sources/gyb/types.swift"
rm "Sources/gyb/description.swift"
rm "Sources/gyb/wrappers.swift"
rm "Sources/gyb/typealiases.swift"
rm "Sources/gyb/builders.swift"
rm "Sources/gyb/syntaxtowrappers.swift"
rm "Sources/gyb/wrapperremoverhelper.swift"
|
import {HttpModule, Module} from '@nestjs/common';
import {SoterService} from './soter.service';
import {UploadHandler} from './useCase/uploadFile/uploadHandler';
import {ArchiveHandler} from './useCase/archiveFile/archiveHandler';
import {UnzipHandler} from './useCase/unzipFile/unzipHandler';
import {ConfigModule} from '../../config/config.module';
import {ConfigService} from '../../config/config.service';
import {ArchiveService} from './archive.service';
import {FileFetcher} from './fetchers/file.fetcher';
import {FileController} from './file.controller';
import {AddPostHandler} from './useCase/addPost/addPost.handler';
import {PostController} from './post.controller';
import {LikeController} from './like.controller';
import {AddLikeHandler} from './useCase/addLike/addLike.handler';
import {SubscribeController} from './subscribe.controller';
import {AddSubscribeHandler} from './useCase/addSubscribe/addSubscribe.handler';
import {BtfsFetcher} from './fetchers/btfs.fetcher';
import {MapService} from './map.service';
import {UserController} from './user.controller';
import {AddUserHandler} from './useCase/addUser/addUser.handler';
import {UnlikeController} from './unlike.controller';
import {RemoveLikeHandler} from './useCase/removeLike/removeLike.handler';
import {UnsubscribeController} from './unsubscribe.controller';
import {RemoveSubscribeHandler} from './useCase/removeSubscribe/removeSubscribe.handler';
import {ContractModule} from '../contracts/contract.module';
import {ContractFetcher} from './fetchers/contract.fetcher';
import {CommentController} from './comment.controller';
import {AddCommentHandler} from './useCase/addComment/addComment.handler';
import {TelegramModule} from 'nestjs-telegram';
import {SaveBtfsCron} from './cron/saveBtfs.cron';
import {IgniteNodeService} from './services/igniteNode.service';
import {TelegramDebugService} from './services/telegramDebug.service';
import {PlasmaSyncCron} from './cron/plasmaSync.cron';
import {SmartChainSyncCron} from './cron/binance/smartChainSync.cron';
import {ArweaveService} from '../arweave/arweave.service';
// tslint:disable-next-line:no-var-requires
const https = require('https');
@Module({
imports: [
ContractModule,
HttpModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
baseURL: configService.get('SOTER_HOST'),
httpsAgent: new https.Agent({
rejectUnauthorized: false,
}),
headers: {
'Content-Type': 'multipart/form-data; charset=UTF-8',
},
}),
inject: [ConfigService],
}),
TelegramModule.forRootAsync({
useFactory: async (configService: ConfigService) => {
return {
botKey: configService.get('TELEGRAM_BOT_KEY')
};
},
inject: [ConfigService]
})
],
controllers: [
UserController,
SubscribeController,
LikeController,
PostController,
FileController,
UnlikeController,
UnsubscribeController,
CommentController,
],
providers: [
MapService,
BtfsFetcher,
SaveBtfsCron,
AddSubscribeHandler,
AddLikeHandler,
AddPostHandler,
FileFetcher,
ArchiveService,
SoterService,
UploadHandler,
ArchiveHandler,
UnzipHandler,
AddUserHandler,
RemoveLikeHandler,
RemoveSubscribeHandler,
ContractFetcher,
AddCommentHandler,
IgniteNodeService,
TelegramDebugService,
PlasmaSyncCron,
SmartChainSyncCron,
ArweaveService
],
})
export class SoterModule {}
|
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { ScrollPanel } from './scrollpanel';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { Component } from '@angular/core';
@Component({
template: `
<div style="width: 300px;">
<p-scrollPanel [style]="{width: '100%', height: '200px'}" styleClass="custombar1">
<div style="padding:1em;line-height:1.5;width:600px;">
The story begins as Don Vito Corleone, the head of a New York Mafia family, oversees his daughter's wedding. His beloved
son Michael has just come home from the war, but does not intend to become part of his father's business.
Through Michael's life the nature of the family business becomes clear. The business of the family is just
like the head of the family, kind and benevolent to those who give respect, but given to ruthless violence
whenever anything stands against the good of the family. The story begins as Don Vito Corleone, the head
of a New York Mafia family, oversees his daughter's wedding. His beloved son Michael has just come home from
the war, but does not intend to become part of his father's business. Through Michael's life the nature of
the family business becomes clear. The business of the family is just like the head of the family, kind and
benevolent to those who give respect, but given to ruthless violence whenever anything stands against the
good of the family.
</div>
</p-scrollPanel>
</div>
`
})
class TestScrollPanelComponent {
}
describe('ScrollPanel', () => {
let scrollpanel: ScrollPanel;
let fixture: ComponentFixture<TestScrollPanelComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
NoopAnimationsModule
],
declarations: [
ScrollPanel,
TestScrollPanelComponent
]
});
fixture = TestBed.createComponent(TestScrollPanelComponent);
scrollpanel = fixture.debugElement.children[0].children[0].children[0].componentInstance;
});
it('should created by default', () => {
fixture.detectChanges();
const scrollPanelEl = fixture.debugElement.query(By.css('.p-scrollpanel'));
expect(scrollPanelEl.nativeElement).toBeTruthy();
});
it('should scroll when mousedown and move (y)', fakeAsync(() => {
fixture.detectChanges();
let scrollTopVal = scrollpanel.contentViewChild.nativeElement.scrollTop;
const barYEl = fixture.debugElement.query(By.css('.p-scrollpanel-bar-y'));
const mousedownEvent: any = document.createEvent('CustomEvent');
mousedownEvent.pageY = 201;
mousedownEvent.initEvent('mousedown', true, true);
const mouseMoveEvent: any = document.createEvent('CustomEvent');
mouseMoveEvent.pageY = 250;
mouseMoveEvent.initEvent('mousemove', true, true);
barYEl.nativeElement.dispatchEvent(mousedownEvent);
fixture.detectChanges();
expect(document.body.className).toContain("p-scrollpanel-grabbed");
document.dispatchEvent(mouseMoveEvent);
tick(150);
fixture.detectChanges();
expect(scrollTopVal).not.toEqual(scrollpanel.contentViewChild.nativeElement.scrollTop);
const mouseUpEvent: any = document.createEvent('CustomEvent');
mouseUpEvent.pageY = 201;
mouseUpEvent.initEvent('mouseup', true, true);
barYEl.nativeElement.dispatchEvent(mouseUpEvent);
}));
it('should scroll when mousedown and move (x)', fakeAsync(() => {
fixture.detectChanges();
let scrollLeftVal = scrollpanel.contentViewChild.nativeElement.scrollLeft;
const barXEl = fixture.debugElement.query(By.css('.p-scrollpanel-bar-x'));
const mousedownEvent: any = document.createEvent('CustomEvent');
mousedownEvent.pageX = 201;
mousedownEvent.initEvent('mousedown', true, true);
const mouseMoveEvent: any = document.createEvent('CustomEvent');
mouseMoveEvent.pageX = 250;
mouseMoveEvent.initEvent('mousemove', true, true);
barXEl.nativeElement.dispatchEvent(mousedownEvent);
fixture.detectChanges();
expect(document.body.className).toContain("p-scrollpanel-grabbed");
document.dispatchEvent(mouseMoveEvent);
tick(150);
fixture.detectChanges();
expect(scrollLeftVal).not.toEqual(scrollpanel.contentViewChild.nativeElement.scrollLeft);
const mouseUpEvent: any = document.createEvent('CustomEvent');
mouseUpEvent.pageY = 201;
mouseUpEvent.initEvent('mouseup', true, true);
barXEl.nativeElement.dispatchEvent(mouseUpEvent);
}));
it('should scroll with scrollTop', fakeAsync(() => {
fixture.detectChanges();
let scrollTopVal = scrollpanel.contentViewChild.nativeElement.scrollTop;
scrollpanel.scrollTop(150);
fixture.detectChanges();
expect(scrollTopVal).not.toEqual(scrollpanel.contentViewChild.nativeElement.scrollTop);
}));
});
|
#nullable disable
namespace Avalonia.Platform
{
/// <summary>
/// Defines the platform-specific interface for a <see cref="Avalonia.Media.Imaging.WriteableBitmap"/>.
/// </summary>
internal interface IWriteableBitmapImpl : IBitmapImpl
{
ILockedFramebuffer Lock();
}
}
|
<?php
namespace Drupal\commerce_price\Comparator;
use SebastianBergmann\Comparator\Comparator;
use SebastianBergmann\Comparator\ComparisonFailure;
/**
* Provides a PHPUnit comparator for numbers cast to strings.
*
* In PHPUnit 6, $this->assertEquals('2.0', '2.000') would pass because
* numerically the two strings were equal. This behavior was removed in
* PHPUnit 7, and the assert fails. This comparator restores the ability to
* compare two strings numerically.
*/
class NumberComparator extends Comparator {
/**
* {@inheritdoc}
*/
public function accepts($expected, $actual) {
return is_string($expected) && is_numeric($expected) && is_string($actual) && is_numeric($actual);
}
/**
* {@inheritdoc}
*/
public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = FALSE, $ignoreCase = FALSE) {
if ($expected != $actual) {
throw new ComparisonFailure(
$expected,
$actual,
'',
'',
FALSE,
sprintf('Failed asserting that "%s" matches expected "%s".', $actual, $expected)
);
}
}
}
|
---
published: true
layout: default
category: exhibit
title: 6/5 Wednesday
section: Week two
---
## Wednesday
<img src="https://i.imgur.com/WnvVq9Dl.jpg">
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<img src="https://i.imgur.com/YnS9n1tl.jpg">
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<img src="https://i.imgur.com/uMJnZAil.jpg">
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<img src="https://i.imgur.com/QVNbeNdl.jpg">
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<img src="https://i.imgur.com/HiE1Ngnl.jpg">
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
<img src="https://i.imgur.com/h4No3fNl.jpg">
<br><br>
<br><br>
<br><br>
<br><br>
<br><br>
Collaborations with Joseph Durana
<img src="https://i.imgur.com/JUTEVyLl.jpg">
<img src="https://i.imgur.com/nup4SFql.jpg">
<img src="https://i.imgur.com/vLjK6Gzl.jpg">
<img src="https://i.imgur.com/2kYXE3Ql.jpg">
<img src="https://i.imgur.com/Fsmq6TJl.jpg">
|
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from setuptools import setup, find_packages
setup(
name='prov_es',
version='0.2.2',
long_description='PROV-ES python library',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=['prov==1.3.1', 'future>=0.17.1']
)
|
import fs = require('fs');
import os = require('os');
import path = require('path');
interface FromTreeOutput {
/**
* Absolute path of the created temporary directory, containing the generated structure
*/
readonly directory: string;
/**
* Cleanup function that will remove the generated files once called
*/
readonly cleanup: () => void;
}
/**
* Collection of file-system utility methods
*/
export class FsUtils {
/**
* Generates a filesystem structure from a string,
* formatted like the output of a `tree` shell command
*
* @param tmpPrefix temp directory prefix, used by {@link fs.mkdtemp}
* @param tree
* @param content the content
*
* @returns an array containing the absolute path of the created directory,
* and a cleanup function that will remove the generated files on invocation
*/
public static fromTree(tmpPrefix: string, tree: string, content = 'content'): FromTreeOutput {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), tmpPrefix));
const directories: string[] = [];
const files: string[] = [];
const symlinks: Array<[string, string]> = [];
// we push an element at the end because we push the files/directories during the previous iteration
const lines = [...tree.replace(/^\n+/, '').trimRight().split('\n'), ''];
const initialIndentLevel = (lines[0].match(/^\s*/) || [''])[0].length;
lines.reduce<[string, number, boolean]>(([previousDir, previousIndentLevel, wasDirectory], line) => {
const indentCharacters = (line.match(FsUtils.INDENT_CHARACTERS_REGEX) || [''])[0];
const indentLevel = (indentCharacters.length - initialIndentLevel) / 4;
const fileName = line.slice(indentCharacters.length).replace(FsUtils.TRAILING_CHARACTERS_REGEX, '').trimRight();
const current = indentLevel <= previousIndentLevel ?
path.join(...previousDir.split(path.sep).slice(0, indentLevel - 1), fileName) :
path.join(previousDir, fileName);
if (previousDir) {
// Because of the structure of a tree output, we need the next line
// to tell whether the current one is a directory or not.
// If the indentation as increased (or it was forcefully marked as a directory by ending with "(D)")
// then we know the previous file is a directory
if (indentLevel > previousIndentLevel || wasDirectory) {
directories.push(previousDir);
} else if (FsUtils.SYMBOLIC_LINK_REGEX.test(previousDir)) {
const [link, target] = previousDir.split(FsUtils.SYMBOLIC_LINK_REGEX);
symlinks.push([link, target]);
} else {
files.push(previousDir);
}
}
return [current, indentLevel, FsUtils.IS_DIRECTORY_REGEX.test(line)];
}, ['', 0, false]);
// we create the directories first, as they're needed to store the files
for (const _directory of directories) {
fs.mkdirSync(path.join(directory, _directory));
}
// we create the files first, as they're needed to create the symlinks
for (const file of files) {
fs.writeFileSync(path.join(directory, file), content);
}
for (const [link, target] of symlinks) {
fs.symlinkSync(target, path.join(directory, link));
}
return {
directory,
cleanup: () => {
// reverse order of the creation, we need to empty the directories before rmdir
for (const [link] of symlinks) {
fs.unlinkSync(path.join(directory, link));
}
for (const file of files) {
fs.unlinkSync(path.join(directory, file));
}
for (const _directory of directories.reverse()) {
fs.rmdirSync(path.join(directory, _directory));
}
// finally, we delete the directory created by mkdtempSync
fs.rmdirSync(directory);
}
};
}
/**
* RegExp matching characters used to indent the tree, indicating the line depth
*/
private static readonly INDENT_CHARACTERS_REGEX = /^[\s├─│└]+/;
/**
* RegExp matching characters trailing a tree line
*/
private static readonly TRAILING_CHARACTERS_REGEX = /(\/|\(D\))$/i;
/**
* RegExp determining whether a given line is an explicit directory
*/
private static readonly IS_DIRECTORY_REGEX = /\(D\)\s*$/i;
/**
* RegExp determining whether a given line is a symblic link
*/
private static readonly SYMBOLIC_LINK_REGEX = /\s*[=-]>\s*/;
}
|
"""
Register a user interaction
"""
import json
import logging
import subprocess
import os
from scipy.io.wavfile import read
import numpy
import requests
from admin.notify_admin import NotifyAdmin
from admin.admin import Admin
from checks import CheckResident, CheckCondo
from db.schema import create_resident, resident_exists
from settings import NAME, PHONE, EMAIL, CPF, BLOCK, APARTMENT, PASSWORD
from settings import VOICE_REGISTER, REPEAT_VOICE
from settings import LOG_NAME, PATH, API_TOKEN
from telegram import KeyboardButton, ReplyKeyboardMarkup
from telegram.ext import ConversationHandler
from validator import ValidateForm
from resident.resident_auth import ResidentAuth
logger = logging.getLogger(LOG_NAME)
class RegisterResident:
"""
Register a resident
"""
def index(update, context):
"""
Start the conversation
"""
logger.info("Introducing registration session")
update = update.callback_query
chat_id = update.message.chat_id
if resident_exists(chat_id):
logger.info("Resident already registered")
update.message.reply_text('Você já está cadastrado!')
context.bot.delete_message(
chat_id=chat_id,
message_id=update.message.message_id,
)
return ConversationHandler.END
else:
context.bot.edit_message_text(
chat_id=chat_id,
message_id=update.message.message_id,
text="""
Preencha o formulário para efetuar o cadastro.
Digite /cancelar caso queira interromper o processo.
"""
)
update.message.reply_text('Nome:')
logger.info("Asking for name")
logger.debug(f"data: {context.chat_data}")
return NAME
def name(update, context):
"""
Get name of a resident
"""
name = update.message.text
if not ValidateForm.name(name, update):
return NAME
context.chat_data['name'] = name
logger.debug(f"'name': '{context.chat_data['name']}'")
contact_keyboard = KeyboardButton('Enviar meu número de telefone', request_contact=True)
custom_keyboard = [[contact_keyboard]]
reply_markup = ReplyKeyboardMarkup(
custom_keyboard,
one_time_keyboard=True,
resize_keyboard=True
)
update.message.reply_text('Telefone:', reply_markup=reply_markup)
logger.info("Asking for phone")
return PHONE
def phone(update, context):
"""
Get phone information
"""
phone = update.message.text
contact = update.effective_message.contact
if not ValidateForm.phone(phone, contact, update):
return PHONE
phone = ValidateForm.phone(phone, contact, update)
context.chat_data['phone'] = phone
logger.debug(f"'phone': '{context.chat_data['phone']}'")
update.message.reply_text('Email:')
logger.info("Asking for email")
return EMAIL
def email(update, context):
"""
Get email information
"""
email = update.message.text
if not ValidateForm.email(email, update):
return EMAIL
context.chat_data['email'] = email
logger.debug(f"'email': '{context.chat_data['email']}'")
check = CheckResident.email(email)
if 'errors' not in check.keys():
logger.error("Email already exists in database - asking again")
update.message.reply_text('Já existe um morador com este email, tente novamente:')
return EMAIL
logger.debug("Available email - proceed")
update.message.reply_text('CPF:')
logger.info("Asking for CPF")
return CPF
def cpf(update, context):
"""
Get cpf information
"""
cpf = update.message.text
if not ValidateForm.cpf(cpf, update):
return CPF
cpf = ValidateForm.cpf(cpf, update)
context.chat_data['cpf'] = cpf
logger.debug(f"'cpf': '{context.chat_data['cpf']}'")
check = CheckResident.cpf(cpf)
if 'errors' not in check.keys():
logger.error("CPF already exists in database - asking again")
update.message.reply_text('Já existe um morador com este CPF, tente novamente:')
return CPF
logger.debug("Available CPF - proceed")
update.message.reply_text('Bloco:')
logger.info("Asking for block number")
return BLOCK
def block(update, context):
"""
Get block information
"""
block = update.message.text
if not ValidateForm.block(block, update):
return BLOCK
context.chat_data['block'] = block
logger.debug(f"'block': '{context.chat_data['block']}'")
check = CheckCondo.block(block)
if 'errors' in check.keys():
logger.error("Block not found - asking again")
update.message.reply_text('Por favor, digite um bloco existente:')
return BLOCK
logger.debug("Existing block - proceed")
update.message.reply_text('Apartamento:')
logger.info("Asking for apartment number")
return APARTMENT
def apartment(update, context):
"""
Get apartment information
"""
apartment = update.message.text
block = context.chat_data['block']
if not ValidateForm.apartment(apartment, update):
return APARTMENT
context.chat_data['apartment'] = apartment
logger.debug(f"'apartment': '{context.chat_data['apartment']}'")
check = CheckCondo.apartment(block, apartment)
if 'errors' in check.keys():
logger.error("Apartment not found - asking again")
update.message.reply_text('Por favor, digite um apartamento existente:')
return APARTMENT
logger.debug("Existing apartment - proceed")
update.message.reply_text(
'Legal, agora grave um áudio dizendo "Vou trancar o curso".'
)
update.message.reply_text(
'Quando começar a gravar, espere meio segundinho antes de começar a falar, ok?'
)
return VOICE_REGISTER
def voice_register(update, context):
"""
Catch the phrase audio and ask for confirmation
"""
audio = update.message.voice
if not ValidateForm.audio_has_valid_duration(audio, update):
return VOICE_REGISTER
context.chat_data['audio_speaking_phrase'] = audio
# Repeat and confirm buttons
repeat_keyboard = KeyboardButton('Repetir')
confirm_keyboard = KeyboardButton('Confirmar')
keyboard = [[repeat_keyboard], [confirm_keyboard]]
choice = ReplyKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=True)
update.message.reply_text(
'Escute o seu áudio e confirme se está com boa qualidade',
reply_markup=choice
)
logger.info("Asking to confirm or repeat voice audio ...")
return REPEAT_VOICE
def repeat_voice(update, context):
"""
Repeate voice interaction
"""
choice = update.message.text
if choice == "Repetir":
logger.debug("Repeating voice audio ...")
update.message.reply_text('Por favor, grave novamente:')
return VOICE_REGISTER
update.message.reply_text('Certo, vou dar uma conferida no áudio')
logger.debug("\tAudio confirmed")
logger.debug('Downloading audio ...')
audio_file_path = context.chat_data['audio_speaking_phrase'].get_file().download()
wav_audio_file_path = audio_file_path.split('.')[0] + '.wav'
logger.debug('\tDone')
logger.debug('Converting into wav ...')
subprocess.run(['ffmpeg', '-i', audio_file_path, wav_audio_file_path], check=True)
logger.debug('\tDone')
logger.debug('Opening audio ...')
samplerate, data = read(wav_audio_file_path)
logger.debug('\tDone')
logger.debug('Putting into dictionary ...')
context.chat_data['audio_speaking_phrase'] = data.tolist()
logger.debug('\tDone')
logger.debug('Removindo audio files ...')
os.remove(audio_file_path)
os.remove(wav_audio_file_path)
logger.debug('\tDone')
if not ValidateForm.audio_has_good_volume(data.tolist(), samplerate, update):
return VOICE_REGISTER
update.message.reply_text(
'Além da autenticação de moradores por voz, é possível fazê-la por senha.'
)
update.message.reply_text('Por favor, informe a senha que deseja cadastrar:')
logger.info("Asking for password")
return PASSWORD
def password(update, context):
"""
Request password
"""
chat_id = update.message.chat_id
password = update.message.text
context.chat_data['password'] = password
logger.debug(f"'password': '{context.chat_data['password']}'")
response = RegisterResident.register_resident(context.chat_data)
if(response.status_code == 200 and 'errors' not in response.json().keys()):
logger.info("Resident registered in database")
update.message.reply_text("Cadastro feito!\nAguarde aprovação dos administradores.")
Admin.activate_resident(context.chat_data['email'])
token = ResidentAuth.generate_token(context.chat_data)
token = token.json()['data']['tokenAuth']['token']
Admin.deactivate_resident(context.chat_data['email'])
create_resident(
cpf=context.chat_data['cpf'],
block=context.chat_data['block'],
apartment=context.chat_data['apartment'],
chat_id=chat_id,
token=token
)
NotifyAdmin.send_message(context, context.chat_data)
else:
logger.error("Registration failed")
update.message.reply_text('Falha ao cadastrar no sistema!')
logger.debug(f"data: {context.chat_data}")
context.chat_data.clear()
return ConversationHandler.END
def end(update, context):
"""
Cancel interaction
"""
logger.info("Canceling registration")
update.message.reply_text('Cadastro cancelado!')
logger.debug(f"data: {context.chat_data}")
context.chat_data.clear()
return ConversationHandler.END
def register_resident(data):
"""
Register a resident
"""
logger.info("Registering resident")
query = """
mutation createResident(
$completeName: String!,
$email: String!,
$phone: String!,
$cpf: String!,
$apartment: String!,
$block: String!,
$audioSpeakingPhrase: [Float]!
$audioSpeakingName: [Float]!,
$password: String!
){
createResident(
completeName: $completeName,
email: $email,
cpf: $cpf,
phone: $phone,
apartment: $apartment,
block: $block,
audioSpeakingPhrase: $audioSpeakingPhrase,
audioSpeakingName: $audioSpeakingName,
password: $password
){
resident{
completeName
email
cpf
phone
apartment{
number
block{
number
}
}
}
}
}
"""
variables = {
'completeName': data['name'],
'email': data['email'],
'phone': data['phone'],
'cpf': data['cpf'],
'apartment': data['apartment'],
'block': data['block'],
'audioSpeakingPhrase': data['audio_speaking_phrase'],
'audioSpeakingName': data['audio_speaking_phrase'],
'password': data['password'],
}
headers = {
'Authorization': 'JWT %s' % API_TOKEN
}
response = requests.post(PATH, headers=headers, json={'query':query, 'variables':variables})
logger.debug(f"Response: {response.json()}")
return response
|
from os import environ
worker_class = "quart.worker.GunicornWorker"
bind = "0.0.0.0:5000"
reload = environ.get('QUART_ENV') == 'development'
|
# Helper function to detect if we're currently compiling
currently_compiling() = ccall(:jl_generating_output, Cint, ()) != 0
# Helper function to get the UUID of a module, throwing an error if it can't.
function get_uuid(m::Module)
uuid = Base.PkgId(m).uuid
if uuid === nothing
throw(ArgumentError("Module $(m) does not correspond to a loaded package!"))
end
return uuid
end
function find_first_project_with_uuid(uuid::UUID)
# Find first element in `Base.load_path()` that contains this UUID
# This code should look similar to the search in `Base.get_preferences()`
for env in Base.load_path()
project_toml = Base.env_project_file(env)
if !isa(project_toml, String)
continue
end
# Check to see if this project has a name mapping
pkg_name = Base.get_uuid_name(project_toml, uuid)
if pkg_name !== nothing
return (project_toml, pkg_name)
end
end
return (nothing, nothing)
end
|
# -*- coding: utf-8 -*-
"""
@date: 2020/10/30 下午3:41
@file: video_manager.py
@author: zj
@description:
"""
import cv2
from .live import Live
class VideoManager:
def __init__(self, cfg):
"""
Args:
cfg (CfgNode): configs. Details can be found in
tsn/config/slowfast.py
"""
assert (
cfg.VISUALIZATION.WEBCAM > -1 or cfg.VISUALIZATION.INPUT_VIDEO != ""
), "Must specify a data source as input."
self.source = (
cfg.VISUALIZATION.WEBCAM if cfg.VISUALIZATION.WEBCAM > -1 else cfg.VISUALIZATION.INPUT_VIDEO
)
self.display_width = cfg.VISUALIZATION.DISPLAY_WIDTH
self.display_height = cfg.VISUALIZATION.DISPLAY_HEIGHT
self.cap = cv2.VideoCapture(self.source)
if self.display_width > 0 and self.display_height > 0:
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.display_width)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.display_height)
else:
self.display_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
self.display_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
if not self.cap.isOpened():
raise IOError("Video {} cannot be opened".format(self.source))
self.output_file = None
if cfg.VISUALIZATION.OUTPUT_FPS == -1:
self.output_fps = self.cap.get(cv2.CAP_PROP_FPS)
else:
self.output_fps = cfg.VISUALIZATION.OUTPUT_FPS
if cfg.VISUALIZATION.OUTPUT_FILE != "":
self.output_file = self.get_output_file(
cfg.VISUALIZATION.OUTPUT_FILE, fps=self.output_fps
)
self.cap.release()
self.cap = None
self.id = -1
self.buffer = []
self.buffer_size = cfg.VISUALIZATION.BUFFER_SIZE
self.seq_length = cfg.DATASETS.FRAME_INTERVAL * cfg.DATASETS.NUM_CLIPS
self.live = self.init_live()
def __call__(self, task):
self.display(task)
def get_output_file(self, path, fps=30):
"""
Return a video writer object.
Args:
path (str): path to the output video file.
fps (int or float): frames per second.
"""
return cv2.VideoWriter(
filename=path,
fourcc=cv2.VideoWriter_fourcc(*"mp4v"),
fps=float(fps),
frameSize=(self.display_width, self.display_height),
isColor=True,
)
def init_live(self):
return None
"""初始化推流"""
live = Live(enable=True, way='rtsp', url='rtsp://localhost:554/zj_test',
size=(self.display_width, self.display_height), fps=self.output_fps)
live.run()
return live
def display(self, task):
"""
Either display a single frame (BGR image) to a window or write to
an output file if output path is provided.
Args:
task (TaskInfo object): task object that contain
the necessary information for prediction slowfast. (e.g. visualized frames.)
"""
for frame in task.frames[task.num_buffer_frames:]:
if self.live is not None:
self.live.read_frame(frame)
if self.output_file is None:
cv2.imshow("SlowFast", frame)
cv2.waitKey(20)
# time.sleep(1 / self.output_fps)
else:
self.output_file.write(frame)
def clean(self):
"""
Clean up open video files and windows.
"""
if self.cap:
self.cap.release()
if self.output_file is None:
cv2.destroyAllWindows()
else:
self.output_file.release()
|
# e-tickets
> A Vue.js project
## Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
```
## what I think is worth to note down
### where should image locate, "assets" or "static"? And what is the difference between them?
webpack will not process those sources in the static, it just simply copy to the distance.
And think about those in assets, they will be copy and rename.
### how the dist file structure is, and how to change it
old:
``` lang = file
dist
├── static
│ │── js
│ │ ├── main.css
│ │ ├── mainA.js
│ │ └── mainB.js
│ └── css
│ ├── a.css
│ └── b.css
│
└── index.html
```
change here : config/index.js line 54
``` lang = js
//assetsSubDirectory: 'static'
assetsSubDirectory: '',
```
new:
```
dist
│── js
│ ├── main.css
│ ├── mainA.js
│ └── mainB.js
├── css
│ ├── a.css
│ └── b.css
│
└── index.html
```
[6.26] update
newest:
``` lang = js
//assetsSubDirectory: 'static'
assetsSubDirectory: 'static/user',
```
``` lang = file
dist
├── static
│ │── js
│ │ ├── main.css
│ │ ├── mainA.js
│ │ └── mainB.js
│ └── css
│ ├── a.css
│ └── b.css
│
└── index.html
```
### in dev mode testing meet the origin problem
add this item into config/index.js
```lang = js
dev{
// other item ...
proxyTable: {
'/api': {
target: 'http://172.18.157.240:8000', // set the host and port for test,and dont forget the http
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
}
}
// other item ...
}
```
|
package test
import java.util.*
public open class WrongMethodName {
public open fun foo() : String? = ""
}
|
/*
* Copyright 2009 Google 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 com.google.android.apps.mytracks.util;
/**
* The singleton class representing the extended encoding of chart data.
*/
public class ChartsExtendedEncoder {
// ChartServer data encoding in extended mode
private static final String CHARTSERVER_EXTENDED_ENCODING_SEPARATOR = ",";
private static final String CHARTSERVER_EXTENDED_ENCODING =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
private static final int CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES =
CHARTSERVER_EXTENDED_ENCODING.length();
private static final String MISSING_POINT_EXTENDED_ENCODING = "__";
private ChartsExtendedEncoder() { }
public static String getEncodedValue(int scaled) {
int index1 = scaled / CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES;
if (index1 < 0 || index1 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) {
return MISSING_POINT_EXTENDED_ENCODING;
}
int index2 = scaled % CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES;
if (index2 < 0 || index2 >= CHARTSERVER_EXTENDED_SINGLE_CHARACTER_VALUES) {
return MISSING_POINT_EXTENDED_ENCODING;
}
return String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index1))
+ String.valueOf(CHARTSERVER_EXTENDED_ENCODING.charAt(index2));
}
public static String getSeparator() {
return CHARTSERVER_EXTENDED_ENCODING_SEPARATOR;
}
}
|
import { createSlice } from '@reduxjs/toolkit';
import { ethSendTransaction, getTransactionReceipt } from '../../api'
export const slice = createSlice({
name: 'contract',
initialState: {
contracts: {}
},
reducers: {
setContract: (state, action) => {
state.contracts[action.payload.address] = action.payload.contract
},
deleteContract: (state, action) => {
delete state.contracts[action.payload]
},
clearContracts: (state) => {
state.contracts = {}
}
}
})
export const { setContract, deleteContract, clearContracts } = slice.actions
export const sendTransaction = (txParams) => async (dispatch, getState) => {
let { accounts } = getState()
let { currentAccount, txMeta } = accounts
try {
let tx = Object.assign(txParams, txMeta, {from: currentAccount})
let txHash = await ethSendTransaction(tx)
let getContractReceiptTimer, timerN = 0
getContractReceiptTimer = setInterval(() => {
timerN ++
if (timerN > 10) {
clearInterval(getContractReceiptTimer)
throw new Error('Get transaction time out!')
}
getTransactionReceipt(txHash).then(res => {
if (res) {
clearInterval(getContractReceiptTimer)
if (res.status === '0x0') {
throw new Error(res.vmerr)
}
}
})
}, 500)
} catch (error) {
}
}
export default slice.reducer
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Command.Export.Perform
( ExportOptions
, options
, perform
) where
import Data.Monoid
import Options.Applicative
import System.Exit
import Text.Comma
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified System.FilePath as F
import Load
import Story
import Util
-- | Options of the "export-csv" command.
data ExportOptions = ExportOptions
{ exportNoHeader :: Bool
, exportTimestamp :: Bool
, exportFile :: FilePath }
deriving (Show)
-- | Switch to trigger exclusion of a CSV header.
optionNoHeader :: Parser Bool -- ^ parser
optionNoHeader = switch
$ long "n"
<> long "no-header"
<> help "Header-less output table"
-- | Switch to trigger timestamps instead of formatted dates.
optionTimestamp :: Parser Bool -- ^ parser
optionTimestamp = switch
$ short 't'
<> long "timestamp"
<> help "Display time values as timestamps"
-- | Data file to export into CSV.
optionFile :: Parser FilePath -- ^ parser
optionFile = argument str (metavar "FILE")
-- | Command-line user interface.
options :: Parser ExportOptions -- ^ parser
options = ExportOptions <$> optionNoHeader <*> optionTimestamp <*> optionFile
-- | Create a CSV-formatted table of a story.
table :: ExportOptions -- ^ command-line options
-> Story -- ^ story
-> T.Text -- ^ CSV table
table opts story = uncomma $ bool rows (headers:rows) (exportNoHeader opts)
where
headers = ["time", "value"]
rows = map conv story
conv (time, val) = [showTime (exportTimestamp opts) time, textShow val]
-- | Pretty-print the content of a story file.
perform :: ExportOptions -- ^ options
-> IO () -- ^ command action
perform opts = storyLoad file >>= \case
Left msg -> errorPrint msg >> exitFailure
Right story -> T.writeFile newName (table opts story) >> exitSuccess
where
file = exportFile opts
newName = F.replaceExtension file "csv"
|
package com.zhuinden.navigationexamplekotlinview.utils.unused
import android.os.Parcelable
import com.zhuinden.simplestack.navigator.DefaultViewKey
interface ViewKey : DefaultViewKey, Parcelable {
override fun layout(): Int
}
|
import chalk from 'chalk';
import { resolve } from 'path';
import bundle from '../dist/bundle';
const green = chalk.reset.inverse.bold.green;
const red = chalk.reset.inverse.bold.red;
const fixturePath = resolve(__dirname, '../test/fixture');
process.chdir(fixturePath);
bundle()
.then(() => {
console.log(green(' Test fixture prepared. '));
})
.catch(err => {
console.error(`${red(' Error ')}`, err);
process.exit(1);
});
|
using Interceptor;
using Model;
using Sample.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Repository
{
public class Repository : IClientRepository
{
private IList<Client> _clients = new List<Client>();
public void Add(Client client)
{
_clients.Add(client);
}
public Client Get(int id)
{
return _clients.FirstOrDefault(s => s.Id == id);
}
public void Remove(int id)
{
_clients.Remove(Get(id));
}
public IEnumerable<Client> GetAll()
{
return _clients.AsEnumerable();
}
public void Teste(Client client)
{
Console.WriteLine("Erros");
Console.WriteLine(" " + InterceptorValidator.Errors.First());
}
}
}
|
package pef
fun String.toByteArray () : ByteArray
{
val charArray = toCharArray()
val arraySize = charArray.size
val byteArray = ByteArray( arraySize )
for (a in 0 until arraySize)
byteArray[a] = charArray[a].toByte()
return byteArray
}
fun ByteArray.toString () : String
{
val arraySize = size
val charArray = CharArray( arraySize )
for (a in 0 until arraySize)
{
val byte = this[a]
charArray[a] = if (byte < 128) byte.toChar() else 0.toChar()
}
return charArray.concatToString()
}
|
# frozen_string_literal: true
module RobotV2
class Board
attr_accessor :board
def initialize
@board = []
@prev_position_x = 0
@prev_position_y = 0
end
# Creates a 2D array/matrix based on arg of size
def create_board(size)
@board = Array.new(size) { Array.new(size, 'X') }
end
# Prints to the screen and display of the board
def draw_board
puts "\n"
puts @board.reverse.map { |x| x.join(' ') }
puts "\n"
end
# Finds the last position the Robot as X
def update_last_position
@board[@prev_position_x.to_i][@prev_position_y.to_i] = 'X'
end
# Denotes the current position of the Robot with R
def place_robot(position_x, position_y)
@prev_position_x = position_x
@prev_position_y = position_y
@board[position_x][position_y] = 'R'
end
def place_obstacle(position_x, position_y)
@board[position_x][position_y] = 'O'
end
# Displays the Board and current postion of Robot if conditions are met
def display_board(position_x, position_y)
if position_x.nil? || position_y.nil?
else
update_last_position
place_robot(position_x, position_y)
end
draw_board
end
end
end
|
#include "philo.h"
size_t ft_strlen(const char *s)
{
size_t i;
i = 0;
while (s[i])
i++;
return (i);
}
int ft_isdigit(int c)
{
if (c >= '0' && c <= '9')
return (1);
return (0);
}
int ft_isspace(char c)
{
if (c == '\t' || c == '\n' || c == '\v' || \
c == '\f' || c == '\r' || c == ' ')
return (1);
return (0);
}
int ft_atoi(const char *str)
{
int neg;
unsigned int res;
neg = 1;
res = 0;
while (ft_isspace(*str))
str++;
if (*str == '-' || *str == '+')
{
if (*str == '-')
neg = -1;
str++;
}
while (ft_isdigit(*str))
{
res = res * 10 + (*str - '0');
str++;
if ((res > 2147483647 && neg == 1) || (res > 2147483648 && neg == -1))
return (0);
}
return ((int)(res * neg));
}
int is_number(char *str)
{
int i;
i = 0;
if (str[i] == '0' && ft_strlen(str) > 1)
return (0);
while (str[i])
{
if (!ft_isdigit(str[i]))
return (0);
i++;
}
return (1);
}
|
use diesel_derive_enum::DbEnum;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, DbEnum)]
#[DieselType = "Account_availability"]
pub enum AccountAvailability {
Immediately,
Days,
Weeks,
Months,
Years,
Decades,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, DbEnum)]
#[DieselType = "Account_risk"]
pub enum AccountRisk {
None,
Slight,
Low,
Medium,
High,
Huge,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, DbEnum)]
#[DieselType = "Account_kind"]
pub enum AccountKind {
Cash,
Debit,
Credit,
Debt,
Stocks,
Virtual,
Other,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, DbEnum)]
#[DieselType = "Expense_event_type"]
pub enum ExpenseEventType {
Create,
Modify,
Delete,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, DbEnum)]
#[DieselType = "Expense_event_target"]
pub enum ExpenseEventTarget {
Expense,
Categories,
Receipts,
Transactions,
}
|
require 'spec_helper'
describe Dex2jar::Command do
let(:command) {described_class.new('', [])}
describe "execute" do
it 'executes with the right params' do
expect(command).to receive(:dex2jar_command).and_return('dex2jar.sh')
expect(command).to receive(:`).with('dex2jar.sh ').and_return("mmr")
command.execute
end
it 'executes dex2jar.bat on windows environment' do
expect(command).to receive(:windows_environment?).and_return(true)
expect(command.send(:dex2jar_command)).to include('bin/dex2jar-0.0.9.15/d2j-dex2jar.bat')
end
it 'executes dex2jar.sh on unix environment' do
expect(command).to receive(:windows_environment?).and_return(false)
expect(command.send(:dex2jar_command)).to include('bin/dex2jar-0.0.9.15/d2j-dex2jar.sh')
end
end
end
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Logging
{
public class LogConsoleListener : LogListener
{
public void sendMessage(string message, LogLevel logLevel, string subsystem)
{
Console.WriteLine(Log.formatMessage(message, subsystem));
}
}
}
|
use std::cell::RefCell;
mod parser;
#[derive(Debug)]
pub struct Config<'a> {
contents: RefCell<Vec<&'a str>>,
}
impl<'a> Config<'a> {
pub fn load(contents: Vec<&'a str>) -> Config {
Config {
contents: RefCell::new(contents),
}
}
pub fn get_config(&self) -> String {
self.contents
.borrow()
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
.join("\n")
}
pub fn list_contexts(&self) -> String {
self.get_contexts()
//unwrap
.unwrap()
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
.join("\n")
}
pub fn check_context(&self, context: &str) -> bool {
let contexts = self
.get_contexts()
//unwrap
.unwrap();
contexts.iter().find(|&c| *c == context).is_some()
}
pub fn get_current_context(&self) -> Result<&str, &'static str> {
let contents = self.contents.borrow();
let mut iter = contents.iter();
while let Some(line) = iter.next() {
if let Some(current_context) = parser::match_literal(line, "current-context: ") {
return Ok(current_context);
}
}
Err("current-context is not set")
}
pub fn set_current_context(&'a self, new_context: &'a str) -> Result<(), &'static str> {
let mut index = 0;
let mut contents = self.contents.borrow_mut();
let mut iter = contents.iter();
while let Some(line) = iter.next() {
if parser::match_literal(line, "current-context:").is_some() {
contents.push(new_context);
contents.swap_remove(index);
return Ok(());
}
index = index + 1;
}
contents.push(new_context);
Ok(())
}
pub fn unset_current_context(&'a self) -> Result<(), &'static str> {
let mut index = 0;
let mut contents = self.contents.borrow_mut();
let mut iter = contents.iter();
while let Some(line) = iter.next() {
if parser::match_literal(line, "current-context:").is_some() {
contents.remove(index);
return Ok(());
}
index = index + 1;
}
Ok(())
}
fn get_contexts(&self) -> Result<Vec<&str>, &'static str> {
let mut contexts = Vec::<&str>::new();
let contents = self.contents.borrow();
let mut input = contents.iter().peekable();
while let Some(line) = input.next() {
if parser::match_literal(line, "contexts:").is_some() {
// unwrap
while parser::is_in_mapping(input.peek().unwrap()).is_ok() {
if let Some(line) = input.next() {
if let Some(name) = parser::match_literal(line, " name: ") {
contexts.push(name);
}
}
}
break;
}
}
if contexts.len() == 0 {
return Err("Cannot get contexts!");
}
Ok(contexts)
}
}
|
package no.nav.helse
import com.fasterxml.jackson.module.kotlin.readValue
import io.ktor.http.*
import io.ktor.routing.*
import io.ktor.server.testing.*
import no.nav.common.KafkaEnvironment
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerConfig
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.serialization.StringSerializer
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.util.*
import kotlin.collections.set
import kotlin.test.assertEquals
import kotlin.test.assertTrue
internal class FeedApiNulldagTest {
private val testTopic = "yes"
private val topicInfos = listOf(
KafkaEnvironment.TopicInfo(testTopic, partitions = 1)
)
private val embeddedKafkaEnvironment = KafkaEnvironment(
autoStart = false,
noOfBrokers = 1,
topicInfos = topicInfos,
withSchemaRegistry = false,
withSecurity = false
)
lateinit var consumer: KafkaConsumer<String, Vedtak>
@Test
fun `får tilbake elementer fra feed`() {
embeddedKafkaEnvironment.start()
val testKafkaProperties = loadTestConfig().also {
it[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java
it[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java
}
val kafkaProducer = KafkaProducer<String, String>(testKafkaProperties)
consumer = KafkaConsumer(loadTestConfig().toSeekingConsumer())
withTestApplication({
installJacksonFeature()
routing {
feedApi(testTopic, consumer)
}
}) {
with(handleRequest(HttpMethod.Get, "/feed?sistLesteSekvensId=0")) {
val feed = objectMapper.readValue<Feed>(response.content!!)
assertTrue(feed.elementer.isEmpty(), "Feed skal være tom når topic er tom")
}
val (fom1, tom1) = LocalDate.of(2020, 3, 1) to LocalDate.of(2020, 3, 15)
kafkaProducer.send(ProducerRecord(testTopic, "0", vedtak(fom1, tom1)))
with(handleRequest(HttpMethod.Get, "/feed?sistLesteSekvensId=0")) {
val feed = objectMapper.readValue<Feed>(response.content!!)
assertTrue(feed.elementer.isEmpty(), "Feed skal være tom når topic bare har ett element")
}
val (fom2, tom2) = LocalDate.of(2020, 4, 1) to LocalDate.of(2020, 4, 15)
kafkaProducer.send(ProducerRecord(testTopic, "1", vedtak(fom2, tom2)))
with(handleRequest(HttpMethod.Get, "/feed?sistLesteSekvensId=0")) {
val feed = objectMapper.readValue<Feed>(response.content!!)
assertTrue(
feed.elementer.isNotEmpty(),
"Feed skal ha elementer når det er mer enn ett element på topic"
)
assertEquals(2, feed.elementer.size)
assertEquals(fom1.toString(), feed.elementer[0].innhold.utbetalingsreferanse)
assertEquals(fom2.toString(), feed.elementer[1].innhold.utbetalingsreferanse)
}
}
embeddedKafkaEnvironment.close()
}
private fun loadTestConfig(): Properties = Properties().also {
it["bootstrap.servers"] = embeddedKafkaEnvironment.brokersURL
}
}
private fun vedtak(fom: LocalDate, tom: LocalDate) = """
{
"type": "SykepengerUtbetalt_v1",
"opprettet": "2018-01-01T12:00:00",
"aktørId": "aktørId",
"fødselsnummer": "fnr",
"førsteStønadsdag": "$fom",
"sisteStønadsdag": "$tom",
"førsteFraværsdag": "$fom",
"forbrukteStønadsdager": 123
}
"""
|
(ns rlserver.generate.timer
(:require [rlserver.entity.entity :refer [create-entity]]))
(defn generate-animated-effect
([state pos animation timer]
(create-entity state
{:pos pos
:timer timer
:animated animation}))
([state pos animation]
(generate-animated-effect state pos animation 1)))
(defn generate-sprite-effect
([state pos sprite timer]
(create-entity state
{:pos pos
:timer timer
:sprite sprite}))
([state pos sprite]
(generate-sprite-effect state pos sprite 1)))
|
# Compiles protocol buffers files
BOSY_PROTO_PATH="../ml2/tools/bosy/bosy.proto"
LTL_PROTO_PATH="../ml2/tools/protos/ltl.proto"
NUXMV_PROTO_PATH="../ml2/tools/nuxmv/nuxmv.proto"
SPOT_PROTO_PATH="../ml2/tools/spot/spot.proto"
STRIX_PROTO_PATH="../ml2/tools/strix/strix.proto"
if [ $1 == "bosy" ]
then
PROTO_PATH=$BOSY_PROTO_PATH
elif [ $1 == "ltl" ]
then
PROTO_PATH=$LTL_PROTO_PATH
elif [ $1 == "nuxmv" ]
then
PROTO_PATH=$NUXMV_PROTO_PATH
elif [ $1 == "spot" ]
then
PROTO_PATH=$SPOT_PROTO_PATH
elif [ $1 == "strix" ]
then
PROTO_PATH=$STRIX_PROTO_PATH
else
echo "Unknown argument"
exit
fi
python -m grpc_tools.protoc --grpc_python_out=../ --python_out=../ --proto_path=../ $PROTO_PATH
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import deque
from io import StringIO
from math import ceil
import threading
import unittest
from hwt.simulator.simTestCase import SingleUnitSimTestCase
from hwtLib.examples.axi.debugbusmonitor import DebugBusMonitorExampleAxi
from hwtLib.tools.debug_bus_monitor_ctl import DebugBusMonitorCtl, words_to_int
from pyMathBitPrecise.bit_utils import ValidityError
from hwtSimApi.constants import CLK_PERIOD
from hwtSimApi.triggers import Timer, StopSimumulation
class DebugBusMonitorCtlSim(DebugBusMonitorCtl):
def __init__(self, tc):
DebugBusMonitorCtl.__init__(self, 0)
self.tc = tc
def read(self, addr, size):
axi = self.tc.u.s
word_size = axi.DATA_WIDTH // 8
words = []
for _ in range(ceil(size / word_size)):
assert not self.tc.sim_done
ar_req = axi.ar._ag.create_addr_req(addr)
axi.ar._ag.data.append(ar_req)
r_data = axi.r._ag.data
while not r_data:
assert not self.tc.sim_done
self.tc.r_data_available.acquire()
d = r_data.popleft()[0]
try:
d = int(d)
except ValidityError:
d = d.val & d.vld_mask
words.append(d)
addr += word_size
return words_to_int(words, word_size, size).to_bytes(size, "little")
def run_DebugBusMonitorCtlSim(tc, out):
db = DebugBusMonitorCtlSim(tc)
db.dump_txt(out)
tc.sim_done = True
class DebugBusMonitorExampleAxiTC(SingleUnitSimTestCase):
@classmethod
def getUnit(cls):
u = DebugBusMonitorExampleAxi()
u.DATA_WIDTH = 32
return u
def setUp(self):
SingleUnitSimTestCase.setUp(self)
self.sim_done = False
self.r_data_available = threading.Lock()
self.r_data_available.acquire()
def test_dump_txt(self):
u = self.u
buff = StringIO()
tc = self
class SpyDeque(deque):
def __init__(self, tc):
super(SpyDeque, self).__init__()
self.tc = tc
def append(self, x):
if self.tc.r_data_available.locked():
self.tc.r_data_available.release()
super(SpyDeque, self).append(x)
u.s.r._ag.data = SpyDeque(self)
def time_sync():
while True:
if u.s.r._ag.data and self.r_data_available.locked():
tc.r_data_available.release()
yield Timer(CLK_PERIOD)
if self.sim_done:
raise StopSimumulation()
self.procs.append(time_sync())
ctl_thread = threading.Thread(target=run_DebugBusMonitorCtlSim,
args=(self, buff,))
ctl_thread.start()
# actually takes less time as the simulation is stopped after ctl_thread end
self.runSim(8000 * CLK_PERIOD)
# handle the case where something went wrong and ctl thread is still running
self.sim_done = True
if self.r_data_available.locked():
self.r_data_available.release()
ctl_thread.join()
d = buff.getvalue()
self.assertEqual(d, """\
din0:
data: 0x0
vld: 0
rd: 1
din0_snapshot:
data: 0x0
vld: 0
rd: 0
dout0:
data: 0x0
vld: 0
rd: 1
dout0_snapshot:
data: 0x0
vld: 0
rd: 0
din1:
data: 0x0
vld: 0
rd: 1
din1_snapshot:
data: 0x0
vld: 0
rd: 0
dataIn:
data: 0x0
vld: 0
rd: 1
dataIn_snapshot:
data: 0x0
vld: 0
rd: 0
dataOut:
data: 0x0
vld: 0
rd: 1
dataOut_snapshot:
data: 0x0
vld: 0
rd: 0
dout1:
data: 0x0
vld: 0
rd: 1
dout1_snapshot:
data: 0x0
vld: 0
rd: 0
din2:
data: 0x0
vld: 0
rd: 1
din2_snapshot:
data: 0x0
vld: 0
rd: 0
dout2:
data: 0x0
vld: 0
rd: 1
dout2_snapshot:
data: 0x0
vld: 0
rd: 0
""")
if __name__ == "__main__":
suite = unittest.TestSuite()
# suite.addTest(DebugBusMonitorExampleAxiTC('test_write'))
suite.addTest(unittest.makeSuite(DebugBusMonitorExampleAxiTC))
runner = unittest.TextTestRunner(verbosity=3)
runner.run(suite)
|
package net.floodlightcontroller.arscheduler;
import java.util.Calendar;
import java.util.Date;
import org.slf4j.Logger;
/**
* Runs in the background, waiting to provision a successfully scheduled flow until the starting time.
* @author Dylan Davis and Jeremy Plante
*
*/
public class SchedulingThread implements Runnable
{
/**
* The thread's ID
*/
static int tID = 0;
int threadID;
/**
* Calendar used to wait for the start time
*/
Calendar scheduledCal;
/**
* The thread itself
*/
Thread theSchedulingThread;
/**
* The coordinating ARScheduler
*/
ARScheduler schedulingCoordinator;
/**
* The flow to be provisioned
*/
Flow flowToSchedule;
/**
* The logger
*/
private Logger logger;
/**
* Construct a SchedulingThread with references to an ARScheduler, a Flow, and the starting time
* Also takes in a logger for output.
* @param coordinator
* @param flow
* @param hour
* @param minute
* @param second
*/
public SchedulingThread(ARScheduler coordinator, Flow flow, int hour, int minute, int second, Logger log)
{
threadID = ++tID;
schedulingCoordinator = coordinator;
flowToSchedule = flow;
logger = log;
theSchedulingThread = new Thread(this);
Calendar initialCal = Calendar.getInstance();
Date scheduledDate = initialCal.getTime();
scheduledDate.setHours(hour);
scheduledDate.setMinutes(minute);
scheduledDate.setSeconds(second);
scheduledCal = Calendar.getInstance();
scheduledCal.setTime(scheduledDate);
theSchedulingThread.start(); // Start background thread
}
/**
* Run the scheduling thread, wait until the start time, then provision the flow
*/
@Override
public void run()
{
logger.info("Initializing new Scheduling Thread for Flow {}.", flowToSchedule.getID());
logger.info("Flow will be established at time {}",
String.valueOf(scheduledCal.get(Calendar.HOUR_OF_DAY)) + ":" +
String.valueOf(scheduledCal.get(Calendar.MINUTE)) + ":" +
String.valueOf(scheduledCal.get(Calendar.SECOND)));
Calendar currentCal = Calendar.getInstance();
while(currentCal.before(scheduledCal))
{
currentCal = Calendar.getInstance();
}
logger.info("Current time = {}",
String.valueOf(currentCal.get(Calendar.HOUR_OF_DAY)) + ":" +
String.valueOf(currentCal.get(Calendar.MINUTE)) + ":" +
String.valueOf(currentCal.get(Calendar.SECOND)));
logger.info("Scheduling Flow {}!", flowToSchedule.getID());
schedulingCoordinator.flowProvisioner.provisionFlowPath(schedulingCoordinator.theRM.getFlowFromRM(flowToSchedule),
schedulingCoordinator.getFloodlightTopology().getSwitchMap(),
schedulingCoordinator.getFloodlightTopology().getSwitchQueueMap());
logger.info("Flow {} Active!", flowToSchedule.getID());
}
}
|
grt-realtime
============
A simple app to expose the GRT's real-time transit information on Android phones.
|
#=
# Tests vector unknown capability with a simple Poisson-like problem.
=#
### If the Finch package has already been added, use this line #########
using Finch # Note: to add the package, first do: ]add "https://github.com/paralab/Finch.git"
### If not, use these four lines (working from the examples directory) ###
# if !@isdefined(Finch)
# include("../Finch.jl");
# using .Finch
# end
##########################################################################
init_finch("vector");
# Try making an optional log
useLog("vectorlog", level=3)
# Set up the configuration
domain(2)
functionSpace(order = 3)
# Specify the problem
mesh(QUADMESH, elsperdim=20, bids=3)
u = variable("u", type=VECTOR)
p = variable("p")
testSymbol("v", type=VECTOR)
testSymbol("w")
# boundary(u, 2, DIRICHLET, [0.1, 0.1])
# boundary(p, 2, DIRICHLET, 0.1)
boundary(u, 1, NEUMANN, ["-pi*sin(2*pi*y)", "-2*pi*sin(3*pi*y)"])
boundary(p, 1, NEUMANN, "-pi*sin(pi*y)")
boundary(u, 2, DIRICHLET, [0, 0])
boundary(p, 2, DIRICHLET, 0)
boundary(u, 3, DIRICHLET, [0, 0])
boundary(p, 3, DIRICHLET, 0)
# Write the weak form
coefficient("f", ["-25*pi*pi*sin(pi*x)*sin(2*pi*y)", "-65*pi*pi*sin(2*pi*x)*sin(3*pi*y)"], type=VECTOR)
coefficient("g", "-2*pi*pi*sin(pi*x)*sin(pi*y)")
coefficient("a", 5)
weakForm([u,p], ["-a*inner(grad(u), grad(v)) - dot(f,v)", "-dot(grad(p), grad(w)) - g*w"])
solve([u,p]);
# # exact solution is [sin(pi*x)*sin(2*pi*y), sin(2*pi*x)*sin(3*pi*y)]
# # check error
erroru = zeros(size(u.values));
maxerru = 0
maxerrp = 0
exactu1(x,y) = sin(pi*x)*sin(2*pi*y);
exactu2(x,y) = sin(2*pi*x)*sin(3*pi*y);
exactp(x,y) = sin(pi*x)*sin(pi*y);
for i=1:size(Finch.grid_data.allnodes,2)
x = Finch.grid_data.allnodes[1,i];
y = Finch.grid_data.allnodes[2,i];
exac = [exactu1(x,y), exactu2(x,y)];
for j=1:size(Finch.grid_data.allnodes,1)
erroru[j,i] = u.values[j,i] - exac[j];
global maxerru;
maxerru = max(abs(erroru[j,i]),maxerru);
end
global maxerrp;
maxerrp = max(abs(p.values[i] - exactp(x,y)),maxerrp);
end
println("u max error = "*string(maxerru));
println("p max error = "*string(maxerrp));
using Plots
pyplot();
display(plot(Finch.grid_data.allnodes[1,:], Finch.grid_data.allnodes[2,:], erroru[1,:], st=:surface))
# check
# log_dump_config();
# log_dump_prob();
output_values([u,p], "vector2d", format="vtk");
finalize_finch();
|
#include "DebugList.h"
#include "Application.h"
//----------------------------------------------------
//This class was made to centralise all debug toggles.
//Very poorly implemented :(
//It does do the job however and initialises values
//correctly.
//Note that the existence of the class could be nulled
//completly and moved into game manager rather than
//being a class within game manager as game manager
//handles is almost neccesary for any debug info.
//Cosider that in future or refactor.
//----------------------------------------------------
//Upon further reflection this has become almost a game
//manager.
//----------------------------------------------------
DebugList::DebugList()
{
for (int i = 0; i < DEBUG_ITEMS; i++)
item[i] = false;
}
DebugList::~DebugList()
{
}
void DebugList::Update()
{
aie::Input* input = aie::Input::GetInstance();
aie::Application* application = aie::Application::GetInstance();
if (input->WasKeyPressed(aie::INPUT_KEY_1))
{
if (item[0])
item[0] = false;
else
item[0] = true;
}
if (input->WasKeyPressed(aie::INPUT_KEY_2))
{
if (item[1])
item[1] = false;
else
item[1] = true;
}
if (input->WasKeyPressed(aie::INPUT_KEY_3))
{
if (item[2])
item[2] = false;
else
item[2] = true;
}
if (input->WasKeyPressed(aie::INPUT_KEY_4))
{
if (item[3])
item[3] = false;
else
item[3] = true;
}
if (input->WasKeyPressed(aie::INPUT_KEY_5))
{
if (item[4])
item[4] = false;
else
item[4] = true;
}
if (input->IsKeyDown(aie::INPUT_KEY_ESCAPE))
{
aie::Application* application = aie::Application::GetInstance();
application->Quit();
}
}
|
package Main;
import java.io.IOException;
import java.util.List;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class main extends Excel {
public WebDriver driver;
@Before
@Given("launch browser and navigate to application")
public void launchBrowser() {
System.out.println("Launching browser");
String Driverpath = "C:\\Users\\Govin\\Resolve6\\chromedriver_win32\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", Driverpath); // set ie driver and location
driver = new ChromeDriver(); // driver object
driver.manage().window().maximize();
// driver.get("https://www.resolve6training.ca/");
Excel ex = new Excel();
try {
String data = ex.excel_R();
System.out.println(data);
driver.get(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@When("I mouse on to IT training programs tab")
public void mouseon() {
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.xpath("//*[@id=\"menu-item-458\"]/a"))).build().perform();
}
@Then("print all the drop down options")
public void dropdownmenu() {
List<WebElement> elements= driver.findElements(By.xpath("//*[@id=\"menu-item-458\"]/ul"));
for(WebElement e: elements) {
System.out.println(e.getText());
}
}
}
|
-- Switch to the DBA database
USE DBA;
GO
-- Begin a conversation and send a request message
DECLARE @conversation_handle UNIQUEIDENTIFIER;
DECLARE @message_body XML;
BEGIN TRANSACTION;
BEGIN DIALOG @conversation_handle
FROM SERVICE [WhoIsActiveService]
TO SERVICE N'WhoIsActiveService'
ON CONTRACT [WhoIsActiveContract]
WITH ENCRYPTION = OFF;
SELECT @message_body = N'<WhoIsActiveMessage>'+CAST(GETDATE() AS VARCHAR(30))+'</WhoIsActiveMessage>';
SEND ON CONVERSATION @conversation_handle
MESSAGE TYPE [WhoIsActiveMessage]
(@message_body);
SELECT @message_body AS WhoIsActiveMessage;
COMMIT TRANSACTION;
GO
-- View the conversation we created
SELECT *
FROM sys.conversation_groups;
GO
-- View the message in the targets queue
SELECT CAST(message_body AS XML) AS message_body_xml
,CAST(message_body AS XML).value('(/WhoIsActiveMessage)[1]', 'varchar(125)' )
,*
FROM WhoIsActiveQueue;
GO
|
#!/bin/bash
duration() {
ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $1
}
log() {
date=$(date --rfc-3339=seconds)
path=$1
m3u8="$path"index.m3u8
duration=$(duration $path$file)
echo $date - [$file] [$duration]["$path"index.m3u8] >> /opt/log_data/report.log
}
inotifywait -r -m /opt/hls_data -e close_write -e moved_to |
while read path action file; do
if [[ "$file" =~ .*ts$ ]]; then
log $path $file
fi
done
|
import chai = require('chai');
const should = chai.should();
import { exec } from '../../../src/slimming/color/exec';
describe('颜色解析', () => {
it('keywords', () => {
exec('red').should.deep.equal({
r: 255,
g: 0,
b: 0,
a: 1,
origin: '#ff0000',
valid: true,
});
exec('yellow').should.deep.equal({
r: 255,
g: 255,
b: 0,
a: 1,
origin: '#ffff00',
valid: true,
});
});
it('hex', () => {
exec('#336699').should.deep.equal({
r: 51,
g: 102,
b: 153,
a: 1,
origin: '#336699',
valid: true,
});
exec('#369').should.deep.equal({
r: 51,
g: 102,
b: 153,
a: 1,
origin: '#369',
valid: true,
});
exec('#0006').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 0.4,
origin: '#0006',
valid: true,
});
exec('#0004').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 0.26666666666666666,
origin: '#0004',
valid: true,
});
exec('#000000fe').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 0.996078431372549,
origin: '#000000fe',
valid: true,
});
exec('#ff000080').should.deep.equal({
r: 255,
g: 0,
b: 0,
a: 0.5,
origin: '#ff000080',
valid: true,
});
exec('#ff00007f').should.deep.equal({
r: 255,
g: 0,
b: 0,
a: 0.4980392156862745,
origin: '#ff00007f',
valid: true,
});
exec('#ff000081').should.deep.equal({
r: 255,
g: 0,
b: 0,
a: 0.5058823529411764,
origin: '#ff000081',
valid: true,
});
exec('#ab').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: '#ab',
valid: false,
});
});
it('rgb & rgba', () => {
exec('rrgb(255,0,0)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: 'rrgb(255,0,0)',
valid: false,
});
exec('rgb(255,0,0)').should.deep.equal({
r: 255,
g: 0,
b: 0,
a: 1,
origin: 'rgb(255,0,0)',
valid: true,
});
exec('rgb(500,-1,0.99)').should.deep.equal({
r: 255,
g: 0,
b: 1,
a: 1,
origin: 'rgb(500,-1,0.99)',
valid: true,
});
exec('rgb(0,0%,0)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: 'rgb(0,0%,0)',
valid: false,
});
exec('rgb(0,0,0,10%)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 0.1,
origin: 'rgb(0,0,0,10%)',
valid: true,
});
exec('rgba(100%,50,50%,0.1)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: 'rgba(100%,50,50%,0.1)',
valid: false,
});
exec('rgba(100%,50%,50%,100)').should.deep.equal({
r: 255,
g: 128,
b: 128,
a: 1,
origin: 'rgba(100%,50%,50%,100)',
valid: true,
});
});
it('hsl & hsla', () => {
exec('hsl(0,0%,0%)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: 'hsl(0,0%,0%)',
valid: true,
});
exec('hsl(1%,0%,0%)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: 'hsl(1%,0%,0%)',
valid: false,
});
exec('hsl(1,0,0)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: 'hsl(1,0,0)',
valid: false,
});
exec('hsl(1circle,0,0)').should.deep.equal({
r: 0,
g: 0,
b: 0,
a: 1,
origin: 'hsl(1circle,0,0)',
valid: false,
});
exec('hsl(0deg,0%,100%)').should.deep.equal({
r: 255,
g: 255,
b: 255,
a: 1,
origin: 'hsl(0deg,0%,100%)',
valid: true,
});
exec('hsla(180deg,50%,50%,50%)').should.deep.equal({
r: 64,
g: 191,
b: 191,
a: 0.5,
origin: 'hsl(180,50%,50%,.5)',
valid: true,
});
exec('hsl(1.5rad,50%,50%,0.1)').should.deep.equal({
r: 136,
g: 191,
b: 64,
a: 0.1,
origin: 'hsl(86,50%,50%,.1)',
valid: true,
});
exec('hsla(1.32432turn,50%,50%)').should.deep.equal({
r: 71,
g: 191,
b: 64,
a: 1,
origin: 'hsla(1.32432turn,50%,50%)',
valid: true,
});
exec('hsl(500grad,10%,70%)').should.deep.equal({
r: 179,
g: 186,
b: 171,
a: 1,
origin: 'hsl(500grad,10%,70%)',
valid: true,
});
});
});
|
-module(rc_example).
-include_lib("riak_core/include/riak_core_vnode.hrl").
-export([ping/0,
ping/1,
ring_status/0,
put/2,
get/1,
delete/1,
keys/0,
values/0,
clear/0
]).
%% @doc Pings a random vnode to make sure communication is functional
ping()->
ping(os:timestamp()).
ping(Key) ->
sync_command(Key, ping).
ring_status() ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
riak_core_ring:pretty_print(Ring, [legend]).
put(Key, Value) ->
sync_command(Key, {put, Key, Value}).
get(Key) ->
sync_command(Key, {get, Key}).
delete(Key) ->
sync_command(Key, {delete, Key}).
keys() ->
coverage_command(keys).
values() ->
coverage_command(values).
clear() ->
{ok, []} = coverage_command(clear),
ok.
%% internal
hash_key(Key) ->
riak_core_util:chash_key({<<"rc_example">>, term_to_binary(Key)}).
sync_command(Key, Command) ->
DocIdx = hash_key(Key),
PrefList = riak_core_apl:get_apl(DocIdx, 1, rc_example),
[IndexNode] = PrefList,
riak_core_vnode_master:sync_spawn_command(IndexNode, Command, rc_example_vnode_master).
coverage_command(Command) ->
Timeout = 5000,
ReqId = erlang:phash2(erlang:monotonic_time()),
{ok, _} = rc_example_coverage_fsm_sup:start_fsm([ReqId, self(), Command, Timeout]),
receive
{ReqId, Val} -> Val
end.
|
package models
type paramDomain interface {
IsIn() bool
IsNotIn() bool
IsLike() bool
IsList() bool
IsLtGt() bool
IsOperator(operator string) bool
GetValueList() []string
GetValueItem() string
}
type paramIntGet interface {
getIn() (string, []interface{}, error)
getNotIn() (string, []interface{}, error)
getLike() (string, []interface{}, error)
getNotLike() (string, []interface{}, error)
getLikeWithValue(val string) (string, []interface{}, error)
getNotLikeWithValue(val string) (string, []interface{}, error)
getLtGtString() (string, []interface{}, error)
getLtGtFloat(val float64) (string, []interface{}, error)
getDefault() (string, []interface{}, error)
}
type ParamInt interface {
paramDomain
paramIntGet
}
|
#!/bin/bash
pylint app
pep8 app
#path = pwd
export PYTHONPATH=${PYTHONPATH}:/home/user/.../open-event-server
find . -name "*.pyc" -exec rm -rf {} \;
nosetests --with-coverage --cover-erase --cover-package=app --cover-html
|
package com.hellohasan.weatherappmvpdagger.features.weather_info_show.view
import com.hellohasan.weatherappmvpdagger.features.weather_info_show.model.data_class.City
import com.hellohasan.weatherappmvpdagger.features.weather_info_show.model.data_class.WeatherDataModel
interface MainActivityView {
fun handleProgressBarVisibility(visibility: Int)
fun onCityListFetchSuccess(cityList: MutableList<City>)
fun onCityListFetchFailure(errorMessage: String)
fun onWeatherInfoFetchSuccess(weatherDataModel: WeatherDataModel)
fun onWeatherInfoFetchFailure(errorMessage: String)
}
|
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* ---------------------------------------------------------------------------------------
*
* autonomoustransaction.h
*
*
*
* IDENTIFICATION
* src/include/autonomoustransaction.h
*
* ---------------------------------------------------------------------------------------
*/
#ifndef AUTONOMOUSTRANSACTION_H
#define AUTONOMOUSTRANSACTION_H
#include "c.h"
#include "datatypes.h"
#include "utils/palloc.h"
#include "libpq/libpq-fe.h"
#include "storage/spin.h"
enum PQResult {
RES_DEFAULT,
RES_COMMAND_OK,
RES_SINGLE_TUPLE,
RES_TUPLES_OK,
RES_ERROR
};
enum PQFormat {
PQ_FORMAT_TEXT,
PQ_FORMAT_BINARY
};
struct PQ_ParamInfo {
int nparams;
Oid* paramtypes;
char** paramvalues;
int* paramlengths;
int* paramformats;
};
class ATManager {
public:
ATManager() : m_sessioncnt(0)
{
SpinLockInit(&m_lock);
}
bool AddSession(void);
void RemoveSession(void);
private:
slock_t m_lock;
uint32 m_sessioncnt;
};
extern ATManager g_atManager;
struct ATResult {
bool withtuple;
PQResult result;
ATResult() : withtuple(false), result(RES_DEFAULT) {}
ATResult(bool btuple, PQResult pqres) : withtuple(btuple), result(pqres) {}
};
class AutonomousSession : public BaseObject {
public:
AutonomousSession(ATManager* manager) : m_conn(NULL), m_manager(&g_atManager), m_res(NULL) {}
/* disallow copy */
AutonomousSession(const AutonomousSession&);
AutonomousSession& operator=(const AutonomousSession&);
public:
void Init(ATManager* manager)
{
m_conn = NULL;
m_manager = manager;
m_res = NULL;
m_refcount = 0;
}
ATResult ExecSimpleQuery(const char* query);
ATResult ExecQueryWithParams(const char* query, PQ_ParamInfo* pinfo);
// attach with a plpgsql block, call this before using AutonomousSession object.
void Attach(void);
// detach with a plpgsql block, call this before quiting block.
void Detach(void);
void CloseSession(void);
protected:
/* create a new session using libpq */
void CreateSession(void);
void CreateSession(const char* conninfo);
private:
PGconn* m_conn;
ATManager* m_manager;
PGresult* m_res;
uint32 m_refcount;
};
ATResult HandlePGResult(PGconn* conn, PGresult* pgresult);
enum PLpgSQL_exectype {
STMT_SQL,
STMT_PERFORM,
STMT_DYNAMIC,
STMT_UNKNOW
};
struct PLpgSQL_execstate;
struct PLpgSQL_stmt_block;
struct PLpgSQL_expr;
bool IsAutonomousTransaction(const PLpgSQL_execstate* estate, const PLpgSQL_stmt_block* block);
bool IsValidAutonomousTransaction(const PLpgSQL_execstate* estate, const PLpgSQL_stmt_block* block);
bool IsValidAutonomousTransactionQuery(PLpgSQL_exectype exectype, const PLpgSQL_expr* stmtexpr, bool isinto);
void AttachToAutonomousSession(PLpgSQL_execstate* estate, const PLpgSQL_stmt_block* block);
void DetachToAutonomousSession(const PLpgSQL_execstate* estate);
void InitPQParamInfo(PQ_ParamInfo* pinfo, int n);
void FreePQParamInfo(PQ_ParamInfo* pinfo);
#endif /* AUTONOMOUSTRANSACTION_H */
|
using UnityEngine;
public class CharacterMainMenu : MonoBehaviour
{
#region variables
private Animator animator;
#endregion
#region unity_methods
private void Start ()
{
animator = GetComponent<Animator>();
animator.SetBool("isSitting", true);
}
#endregion
#region public_methods
#endregion
#region private_methods
#endregion
}
|
import template from './errorRetryToastTemplate.html';
angular
.module('missionhubApp')
.directive('errorRetryToastTemplate', function () {
return {
template: template,
};
});
|
package main
import (
"log"
)
func main() {
log.Print("starting vaultier ...")
// get and validate config
cfg := getConfig()
// get secrets specification
var specs = getSpecs(cfg)
// select current config
var specsSelection = getSelection(specs, cfg)
// collect secrets from Vault
final := collectSecrets(specsSelection, cfg.VaultAddr, cfg.VaultToken, false)
// prepare helm or .env structure
finalJSON := generateManifest(cfg, final)
// create json file
writeFile(cfg, finalJSON)
}
|
import { storiesOf } from "@storybook/react";
import React, { useState } from "react";
import { action } from "@storybook/addon-actions";
import { TextField, TextFieldType } from "./";
/**
* Simple state manager to track and update checked properties
*/
function TextFieldStateHandler(props: {
children: (
value: string,
onChange: React.ChangeEventHandler<HTMLInputElement>
) => JSX.Element;
}): JSX.Element {
const [checked, setChecked]: [
string,
React.Dispatch<React.SetStateAction<string>>
] = useState("");
function handleChange(e: React.ChangeEvent<HTMLInputElement>): void {
setChecked(e.target.value);
action("onChange")(e);
}
return props.children(checked, handleChange);
}
storiesOf("Text field", module)
.add("Unhandled", () => <TextField onChange={action("onChange")} />)
.add("Handled", () => {
function render(
value: string,
onChange: React.ChangeEventHandler<HTMLInputElement>
): JSX.Element {
return <TextField value={value} onChange={onChange} />;
}
return <TextFieldStateHandler>{render}</TextFieldStateHandler>;
})
.add("Placeholder", () => (
<TextField placeholder={"Placeholder"} onChange={action("onChange")} />
))
.add("Email", () => (
<TextField
placeholder={"Email"}
type={TextFieldType.email}
onChange={action("onChange")}
/>
))
.add("Number", () => (
<TextField
placeholder={"Number"}
type={TextFieldType.number}
onChange={action("onChange")}
/>
))
.add("Password", () => (
<TextField
placeholder={"Password"}
type={TextFieldType.password}
onChange={action("onChange")}
/>
))
.add("Search", () => (
<TextField
placeholder={"Search"}
type={TextFieldType.search}
onChange={action("onChange")}
/>
))
.add("Tel", () => (
<TextField
placeholder={"Tel"}
type={TextFieldType.tel}
onChange={action("onChange")}
/>
))
.add("Url", () => (
<TextField
placeholder={"Url"}
type={TextFieldType.url}
onChange={action("onChange")}
/>
));
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe WoerkClient::Models::Shift do
let(:shift) { described_class.new({ foo: 'bar' }) }
it 'has a resource path' do
expect(described_class::RESOURCE_PATH).to be
end
describe '#save' do
context 'when shift has ID' do
before do
shift.params['id'] = '123'
end
it 'calls the client with PUT' do
allow(WoerkClient::Client).to receive(:put)
shift.save
expect(WoerkClient::Client).to have_received(:put)
end
end
context 'when shift is new' do
it 'calls the client with POST' do
allow(WoerkClient::Client).to receive(:post)
shift.save
expect(WoerkClient::Client).to have_received(:post)
end
end
end
end
|
# ericpires.com.br
My personal website, built with Hugo and deployed with Netlify.
## Installation
```sh
sudo apt-get install hugo # or brew install hugo
git clone --recurse-submodules https://github.com/epiceric/ericpires.com.br
cd ericpires.com.br
```
## Add a post
Create a draft in `content/posts/my-new-post.md`, edit, and publish.
```sh
hugo new posts/my-new-post.md # Create a draft
# Change `draft: true` to `draft: false`
```
## Serve locally
```sh
hugo server
```
You can also use the `-D` flag to show drafts as posts.
## Build
```sh
hugo
```
Serve files from the `public/` folder. You can also use the `-D` flag to transform drafts into posts.
|
INCLUDE 'VICMAIN_FOR'
SUBROUTINE MAIN44
C
C 23 SEPT 93 ...REA... INITIAL RELEASE
C 11 APRIL 02 ...REA... add SB, NB parameters
C 16 APRIL 02 ...REA... add DECIMAL parameter
C 7 MAY 03 ...REA... PRECISE keyword added
C
REAL*8 BUF(10)
CHARACTER*140 PR, fstrng
CHARACTER*3 ORG
LOGICAL XVPTST
C open input
CALL XVUNIT(INUNIT,'INP',1,ISTAT,' ')
CALL XVOPEN(INUNIT,ISTAT,'OPEN_ACT','SA','IO_ACT','SA',
+ 'U_FORMAT','DOUB',' ')
CALL XVSIZE(ISL,ISS,NL,NS,NLIN,NSIN)
CALL XVBANDS(ISB,NB,NBIN)
C set width parameters
IF (XVPTST('WIDE')) THEN
INCS = 10
ELSE
INCS = 6
END IF
C set precision
IF (XVPTST('PRECISE')) THEN
IWIDE = 20
INCS = 6
ELSE
IWIDE = 11
END IF
CALL XVPARM('DECIMAL',IDEC,NUM,IDEF,0)
C set ends of loops
IEL = ISL+NL-1
IES = ISS+NS-1
IEB = ISB+NB-1
C get file organization
CALL XVGET(INUNIT,ISTAT,'ORG',ORG,' ')
IF (ORG .EQ. 'BIP') THEN
CALL XVMESSAGE('REALLIST does not support BIP format',' ')
CALL ABEND
ELSE
DO IB=ISB,IEB
CALL XVMESSAGE(' ',' ')
IF (NBIN .NE. 1) THEN
WRITE (PR,400) IB
400 FORMAT('Band',I3)
CALL XVMESSAGE(PR,' ')
END IF
C
DO I=ISS,IES,INCS
IF (I .NE. ISS) CALL XVMESSAGE(' ',' ')
NSS = MIN(IES-I+1,INCS)
c WRITE (PR,500) (J,J=I,I+NSS-1)
c 500 FORMAT(' Line',I<IWIDE>,9I<IWIDE+1>)
c above is not std.Fortran, replace with:
fstrng = ' '
write(fstrng,500) iwide,iwide+1
500 format('('' Line'',I',i2,',9I',i2,')')
write(pr,fstrng) (j,j=i,i+nss-1)
CALL XVMESSAGE(PR,' ')
C loop thru all lines
DO J=ISL,IEL
CALL XVREAD(INUNIT,BUF,ISTAT,'LINE',J,'SAMP',I,
+ 'NSAMPS',NSS,'BAND',IB,' ')
c WRITE (PR,600) J,(BUF(K),K=1,NSS)
c 600 FORMAT(I6,10(1X,F<IWIDE>.<IDEC>))
fstrng = ' '
write(fstrng,600) iwide,idec
600 format('(I6,10(1X,F',i2,'.',i2,'))')
write(pr,fstrng) j,(buf(k),k=1,nss)
CALL XVMESSAGE(PR,' ')
END DO
END DO
END DO
END IF
C
RETURN
END
|
module VCAP::CloudController
module Diego
class Runner
class CannotCommunicateWithDiegoError < StandardError; end
def initialize(app, messenger, protocol, default_health_check_timeout)
@app = app
@messenger = messenger
@protocol = protocol
@default_health_check_timeout = default_health_check_timeout
end
def scale
raise VCAP::Errors::ApiError.new_from_details('RunnerError', 'App not started') unless @app.started?
with_logging('scale') { @messenger.send_desire_request(@app, @default_health_check_timeout) }
end
def start(_={})
with_logging('start') { @messenger.send_desire_request(@app, @default_health_check_timeout) }
end
def update_routes
raise VCAP::Errors::ApiError.new_from_details('RunnerError', 'App not started') unless @app.started?
@messenger.send_desire_request(@app, @default_health_check_timeout)
end
def desire_app_message
@protocol.desire_app_message(@app, @default_health_check_timeout)
end
def stop
with_logging('stop_app') { @messenger.send_stop_app_request(@app) }
end
def stop_index(index)
with_logging('stop_index') { @messenger.send_stop_index_request(@app, index) }
end
def with_logging(action=nil)
yield
rescue StandardError => e
return raise e unless diego_not_responding_error?(e)
logger.error "Cannot communicate with diego - tried to send #{action}"
raise CannotCommunicateWithDiegoError.new(e.message)
end
private
def diego_not_responding_error?(e)
/getaddrinfo/ =~ e.message
end
def logger
@logger ||= Steno.logger('cc.diego.runner')
end
end
end
end
|
#!/bin/bash
IMAGE_NAME=""
CONTAINER_NAME=""
USERNAME=""
GPUS=""
GENERATE_HOST_NAME=true
HELP_MESSAGE="
Usage: aica-docker interactive <image> [-n <name>] [-u <user>]
Run a docker container as an interactive shell.
Options:
-i, --image <name> Specify the name of the docker image.
(required)
-n, --name <name> Specify the name of generated container.
By default, this is deduced from
the image name, replacing all
'/' and ':' with '-' and appending
'-runtime'. For example, the image
aica-technology/ros2-ws:foxy would yield
aica-technology-ros2-ws-foxy-runtime
-u, --user <user> Specify the name of the login user.
(optional)
--no-hostname Suppress the automatic generation of a
hostname for the container. By default,
the container hostname is set to be
the same as the container name.
--gpus <gpu_options> Add GPU access for applications that
require hardware acceleration (e.g. Gazebo)
For the list of gpu_options parameters see:
>>> https://docs.docker.com/config/containers/resource_constraints
-h, --help Show this help message.
Any additional arguments passed to this script are forwarded to
the 'docker run' command.
"
RUN_FLAGS=()
FWD_ARGS=()
while [ "$#" -gt 0 ]; do
case "$1" in
-i | --image)
IMAGE_NAME=$2
shift 2
;;
-n | --name)
CONTAINER_NAME=$2
shift 2
;;
--no-hostname)
GENERATE_HOST_NAME=false
shift 1
;;
-u | --user)
USERNAME=$2
shift 2
;;
--gpus)
GPUS=$2
shift 2
;;
-h | --help)
echo "${HELP_MESSAGE}"
exit 0
;;
*)
if [ -z "${IMAGE_NAME}" ]; then
IMAGE_NAME=$1
else
FWD_ARGS+=("$1")
fi
shift 1
;;
esac
done
if [ -z "${IMAGE_NAME}" ]; then
echo "No image name provided!"
echo "${HELP_MESSAGE}"
exit 1
fi
if [ -z "${CONTAINER_NAME}" ]; then
CONTAINER_NAME="${IMAGE_NAME//[\/.]/-}"
CONTAINER_NAME="${CONTAINER_NAME/:/-}-runtime"
fi
if [ -n "${USERNAME}" ]; then
RUN_FLAGS+=(-u "${USERNAME}")
fi
if [ $GENERATE_HOST_NAME == true ]; then
RUN_FLAGS+=(--hostname "${CONTAINER_NAME}")
fi
if [ -n "${GPUS}" ]; then
RUN_FLAGS+=(--gpus "${GPUS}")
RUN_FLAGS+=(--env DISPLAY="${DISPLAY}")
RUN_FLAGS+=(--env NVIDIA_VISIBLE_DEVICES="${NVIDIA_VISIBLE_DEVICES:-all}")
RUN_FLAGS+=(--env NVIDIA_DRIVER_CAPABILITIES="${NVIDIA_DRIVER_CAPABILITIES:+$NVIDIA_DRIVER_CAPABILITIES,}graphics")
fi
if [[ "${OSTYPE}" == "darwin"* ]]; then
RUN_FLAGS+=(-e DISPLAY=host.docker.internal:0)
else
xhost +
RUN_FLAGS+=(-e DISPLAY="${DISPLAY}")
RUN_FLAGS+=(-e XAUTHORITY="${XAUTHORITY}")
RUN_FLAGS+=(-v /tmp/.X11-unix:/tmp/.X11-unix:rw)
RUN_FLAGS+=(--device=/dev/dri:/dev/dri)
fi
if [ ${#FWD_ARGS[@]} -gt 0 ]; then
echo "Forwarding additional arguments to docker run command:"
echo "${FWD_ARGS[@]}"
fi
docker run -it --rm \
"${RUN_FLAGS[@]}" \
--name "${CONTAINER_NAME}" \
"${FWD_ARGS[@]}" \
"${IMAGE_NAME}" /bin/bash
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MassiveDynamicProxyGenerator
{
/// <summary>
/// Interface for interceptor.
/// </summary>
/// <remarks>
/// See http://simpleinjector.readthedocs.org/en/latest/advanced.html#interception
/// </remarks>
public interface IInterceptor
{
/// <summary>
/// Intercept call of method.
/// </summary>
/// <param name="invocation">Invocation informations.</param>
void Intercept(IInvocation invocation);
}
}
|
/*----------------------------------------------------------------------
Name : dbo.fnDisplayEthnicity
Description : returns ethnicity removing Select All etc and defining those as
unspecified
History:
--------
Date Version Author Comment
25-Nov-2008 1.0 Femma Ashraf first version
---------------------------------------------------------------------- */
Create function [dbo].[fnDisplayEthnicity](@ethnicity varchar(100)) returns varchar(100)
as
BEGIN
declare @ethnicityReturn varchar(100)
IF (@ethnicity = 'Please Select' OR @ethnicity = 'Select a group first' )
set @ethnicityReturn = 'Unspecified'
else set @ethnicityReturn = @ethnicity
return @ethnicityReturn
END
|
module.exports = {
siteMetadata: {
supportingTicketManagers: ['freshdesk', 'zendesk'],
},
plugins: [`gatsby-plugin-sass`],
};
|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtOperation
import arcs.core.util.ArcsStrictMode
import arcs.core.util.Scheduler
import arcs.core.util.TaggedLog
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
private const val CLOSE_TIMEOUT = 15000L
/** Base class for [StorageProxy] implementations that provides standard message queue operations. */
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
abstract class StorageProxyImplBase<Data : CrdtData, Op : CrdtOperation, T>(
private val scheduler: Scheduler
) {
val dispatcher: CoroutineDispatcher
get() = scheduler.asCoroutineDispatcher()
// This will be initialized by the [create] method below.
protected lateinit var store: StorageEndpoint<Data, Op, T>
protected val outgoingMessagesChannel =
Channel<Pair<ProxyMessage<Data, Op, T>, CompletableDeferred<Boolean>>>(Channel.UNLIMITED)
private val outgoingMessagesInFlight = atomic(0)
private val busySendingMessagesChannel = ConflatedBroadcastChannel(false)
private val log = TaggedLog { "StorageProxyBaseImpl" }
// Send messages generated by applyOp to the Store in the order in which they were received
// by:
//
// 1. Calling store.onProxyMessage() with the message for each message.
// 2. Buffering those calls so they happen in parallel/pipelined-with calling store.idle()
// 3. Once the store is self-identifying as idle, complete the deferred which was generated
// at the same time as the message (and was returned to the caller)
protected val outgoingMessagesJob = outgoingMessagesChannel.consumeAsFlow()
.map { (message, deferredToComplete) ->
log.verbose { "Sending operations to store" }
store.onProxyMessage(message)
log.verbose { "Operations sent to store" }
deferredToComplete
}
.buffer(Channel.UNLIMITED)
.onEach {
// TODO(jasonwyatt): Make the deferred lazy, so that we only idle when the client
// requests it, we could probably just use the busySendingMessagesChannel thinger.
val success = withTimeoutOrNull(5000) { store.idle() }
if (success == null) {
log.info {
"Timeout exceeded (5 seconds) while waiting for store to become idle."
}
}
it.complete(true)
val queueLength = outgoingMessagesInFlight.getAndDecrement()
log.debug { "Store went idle with outgoing queue length: $queueLength" }
if (queueLength == 1) {
busySendingMessagesChannel.send(false)
}
}
.onCompletion {
busySendingMessagesChannel.send(false)
closeInternal()
}
.launchIn(scheduler.scope)
/** Implements additional implementation specific cleanup logic. */
protected abstract fun closeInternal()
suspend fun awaitOutgoingMessageQueueDrain() {
busySendingMessagesChannel.asFlow().debounce(50).filter { !it }.first()
}
suspend fun waitForIdle() {
scheduler.waitForIdle()
awaitOutgoingMessageQueueDrain()
}
suspend fun isIdle(): Boolean {
return scheduler.isIdle() && !busySendingMessagesChannel.asFlow().first()
}
/** Returns true when the proxy has successfully closed. */
abstract fun isClosed(): Boolean
suspend fun close() {
if (isClosed()) return
scheduler.waitForIdle()
// First, shut down the outgoing messages channel and give it a chance to drain.
// If it takes to long, cancel the job.
try {
withTimeout(CLOSE_TIMEOUT) {
outgoingMessagesChannel.close()
outgoingMessagesJob.join()
}
} catch (e: TimeoutCancellationException) {
log.warning { "outgoingMessagesChannel drain timeout" }
if (outgoingMessagesJob.isActive) {
outgoingMessagesJob.cancel()
}
}
// Now, close the store backing this proxy.
// Again, if it takes too long, cancel the job.
val storeCloseJob = scheduler.scope.launch {
store.close()
}
try {
withTimeout(CLOSE_TIMEOUT) {
storeCloseJob.join()
}
} catch (e: TimeoutCancellationException) {
log.warning { "store close timeout" }
if (storeCloseJob.isActive) {
storeCloseJob.cancel()
}
}
}
fun sendMessageToStore(
message: ProxyMessage<Data, Op, T>,
deferred: CompletableDeferred<Boolean> = CompletableDeferred()
) {
val queueNum = outgoingMessagesInFlight.getAndIncrement()
if (queueNum == 0) {
busySendingMessagesChannel.offer(true)
}
do {
val sent = outgoingMessagesChannel.offer(message to deferred)
} while (!sent)
log.verbose {
"Queueing successful for message (pos: $queueNum) for sending to the store: $message"
}
}
protected fun checkInDispatcher() = check(
!ArcsStrictMode.strictHandles || scheduler.isCurrentDispatcher()
) {
"Operations can only be performed using the Scheduler's Dispatcher"
}
}
|
module VariablesSpecs
class ParAsgn
attr_accessor :x
def initialize
@x = 0
end
def inc
@x += 1
end
def to_ary
[1,2,3,4]
end
end
class OpAsgn
attr_accessor :a, :b, :side_effect
def do_side_effect
self.side_effect = true
return @a
end
def do_more_side_effects
@a += 5
self
end
def do_bool_side_effects
@b += 1
self
end
end
class Hashalike
def [](k) k end
def []=(k, v) [k, v] end
end
def self.reverse_foo(a, b)
return b, a
end
class ArrayLike
def initialize(array)
@array = array
end
def to_a
@array
end
end
class ArraySubclass < Array
end
class PrivateMethods
private
def to_ary
[1, 2]
end
def to_a
[3, 4]
end
end
class ToAryNil
def to_ary
end
end
class Chain
def self.without_parenthesis a
a
end
end
def self.false
false
end
end
|
#ifndef PES_H
#define PES_H
#include <Windows.h>
#include <Lmcons.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <slpublic.h>
#include <strsafe.h>
#include <mbstring.h>
#include <winternl.h>
#include <ntstatus.h>
#pragma comment(lib, "ntdll.lib")
#define PES_NT_ROOT L"\\NTFS\\"
#define PES_BUFFER_SIZE 16384
#define FileProcessIdsUsingFileInformation 0x2F
typedef struct _FILE_PROCESS_IDS_USING_FILE_INFORMATION
{
ULONG NumberOfProcessIdsInList;
ULONG_PTR ProcessIdList[1];
} FILE_PROCESS_IDS_USING_FILE_INFORMATION, *PFILE_PROCESS_IDS_USING_FILE_INFORMATION;
typedef NTSTATUS(NTAPI* _NtQueryInformationFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, DWORD, FILE_INFORMATION_CLASS);
#endif
|
jvm常见命令
一、jps:输出jvm中运行的进程状态信息 -l jar全限名
二、jstack:查看某个java进程内的线程栈信息
1、top 找到cpu最高的进程 jps确认
2、ps -mp pid -0 THREAD tid time 找到最耗时的线程
3、printf “%x\n” tid 线程号转成16进制
4、jstack pid | 隔热片 tid(16进制) 定位代码
三、jmap:(memory map)查看堆内存使用情况
1、-heap pid 堆内存使用情况,gc算法,堆配置
2、-dump 到文件
四、jstat:jvm统计监测工具
jstat -gc pid 250 4
五、jhap(heap Analysis Tool)
|
require "test_helper"
class ExternalTypeTest < ActiveSupport::TestCase
include WithVCR
test "uses 5 minute cache by default" do
ext = ExternalType.new("foo")
assert_instance_of(ExternalType::ClientWithCache, ext.client)
assert_equal(Rails.cache, ext.client.cache)
assert_equal(1.hour, ext.client.options[:expires_in])
end
test "#valid?" do
github_api = external_type("https://api.github.com/repos/rails/rails")
github_html = external_type("https://github.com/")
non_existent = external_type("https://catima-xref.herokuapp.com/does-not-exist")
with_vcr_cassette do
assert(vss.valid?)
refute(github_api.valid?)
refute(github_html.valid?)
refute(non_existent.valid?)
end
end
test "#name" do
with_vcr_cassette do
assert_equal("keyword", vss.name)
assert_equal("keyword", vss.name(:en))
assert_equal("Schlagwort", vss.name(:de))
assert_equal("mot-clé", vss.name(:fr))
end
end
test "#locales" do
with_vcr_cassette do
assert_equal(%w(de en fr), vss.locales)
end
end
test "#find_item" do
item = with_vcr_cassette do
vss.find_item("25-pretty-id") # should be interpreted as 25
end
assert_equal(25, item.id)
assert_equal("Wasserfälle", item.name(:de))
assert_equal("Waterfalls", item.name(:en))
assert_equal("chutes d'eau", item.name(:fr))
end
test "#find_item raises for non-existent ID" do
assert_raises(ExternalType::Client::NotFound) do
with_vcr_cassette do
vss.find_item("99999999")
end
end
end
test "#all_items" do
items = with_vcr_cassette do
vss.all_items
end
assert_instance_of(Array, items)
refute_empty(items)
merch = items.find { |i| i.name(:en) == "Merchandise" }
refute_nil(merch.id)
assert_equal("Ware", merch.name(:de))
assert_equal("marchandises", merch.name(:fr))
end
private
def vss
external_type("https://catima-xref.herokuapp.com/api/v1")
end
def external_type(url)
ExternalType.new(url, :client => ExternalType::Client.new)
end
end
|
"""
Graded vectors are used to represent continuous quantities by interpolating between two endpoints.
This ensures that proximity in terms of cosine similarity corresponds to similar quantities.
Vectors for items in a given position are created by binding the vector for the item with the vector for
the position.
This is used in particular for representing the orthography of written words.
The technique was introduced by Wahle, Cohen, Schvaneveldt, Widdows. For more information see:
Orthogonality and Orthography: Introducing Measured Distance into Semantic Space.
Trevor Cohen, Dominic Widdows, Manuel Wahle.
Proceedings of the Seventh International Conference on Quantum Interaction, Leicester, UK, 2013.
"""
import numpy as np
from . import vector_utils as vu
class GradedVectorFactory:
"""
GradedVectorFactory creates vectors for proportions by interpolation between between given endpoints.
"""
def __init__(self, dimension: int, field=np.float):
self.dimension = dimension
self.alpha_vec = vu.normalize(vu.create_dense_random_vector(dimension, seed=1, field=field))
self.omega_vec = vu.normalize(vu.create_dense_random_vector(dimension, seed=2, field=field))
def get_vector_for_proportion(self, proportion: float):
"""
Gets the vector interpolated by a given proportion between the vector factory's alpha and omega vectors.
:param proportion: Usually between 0 and 1, though if outside those ranges the result will be an extrapolation.
:return: Normalized vector between alpha and omega vectors.
"""
return vu.normalize(np.multiply(self.alpha_vec, 1 - proportion) + np.multiply(self.omega_vec, proportion))
class OrthographicVectorFactory:
"""
OrthographicVectorFactory looks after creating and storing and matching orthographic word vectors.
These vectors represent words as a sum of vectors that bind each character with its relative position in the word.
"""
def __init__(self, dimension, field=np.float):
self.dimension = dimension
self.field = field
self.gvf = GradedVectorFactory(dimension, field=field)
self.character_vectors = {}
self.word_vectors = {}
def get_word_vector(self, word: str):
"""Gets the vector for the given word, creating and storing it if not already present."""
if word in self.word_vectors:
return self.word_vectors[word]
else:
output_vector = self.make_and_store_word_vector(word)
return output_vector
def make_and_store_word_vector(self, word: str):
"""Makes a vector for the given word, adds it to the word_vectors dictionary, and returns the new vector."""
output_vector = self.make_word_vector(word)
self.word_vectors[word] = output_vector
return output_vector
def make_word_vector(self, word: str):
"""Makes a vector for the given word and returns the new vector."""
output_vector = np.zeros(self.dimension, dtype=self.field)
for pos in range(len(word)):
letter = word[pos]
hex_key = int(letter.encode().hex(), 16)
if hex_key not in self.character_vectors:
self.character_vectors[hex_key] = vu.create_dense_random_vector(
self.dimension, seed=hex_key, field=self.field)
output_vector += vu.bind(
self.gvf.get_vector_for_proportion((pos + 0.5) / (len(word))),
self.character_vectors[hex_key],
field=self.field)
return output_vector
def get_k_nearest_neighbors(self, query_word: str, k: int):
query_vector = self.make_word_vector(query_word)
return vu.get_k_neighbors_from_pairs(self.word_vectors.items(), query_vector, k)
|
#!/bin/sh
#
# Author: Graham Williams
# Date: 20170111
#
# This is not done by notedown but it is what is on the end of a
# sample notebook so add it here and the document kernel is recognised
# as R.
perl -pi -e 's|"metadata": \{\},| "metadata": {\
"anaconda-cloud": {},\
"kernelspec": {\
"display_name": "R",\
"language": "R",\
"name": "ir"\
},\
"language_info": {\
"codemirror_mode": "r",\
"file_extension": ".r",\
"mimetype": "text/x-r-source",\
"name": "R",\
"pygments_lexer": "r",\
"version": "3.2.2"\
}\
},|' $1
|
require 'beeramid'
describe Beeramid do
describe '#initialize' do
context 'with no parameters' do
b = Beeramid.new
it 'should return five for price' do
expect(b.price).to eql(5.0)
end
it 'should return fifty for amount' do
expect(b.amount).to eql(50.0)
end
end
context 'with integer options' do
b=Beeramid.new(amount: 10, price: 2)
it 'should return float for price' do
expect(b.price).to eql(2.0)
end
it 'should return float for amount' do
expect(b.amount).to eql(10.0)
end
end
end
describe '#buy_beer' do
context 'with $20 at $5/can' do
b = Beeramid.new(amount: 20)
it 'should buy four cans' do
expect(b.buy_beer).to eql(4)
end
end
context 'with $13 at $5/can' do
b = Beeramid.new(amount: 13)
it 'should buy two cans' do
expect(b.buy_beer).to eql(2)
end
end
context 'with $12.75 at $1/can' do
b = Beeramid.new(amount: 12.75, price: 1)
it 'should buy 12 cans' do
expect(b.buy_beer).to eql(12)
end
end
context 'with $60 at $5.62/can' do
b = Beeramid.new(amount: 60, price: 5.63)
it 'should buy 10 cans' do
expect(b.buy_beer).to eql(10)
end
end
end
describe '#calculate' do
context 'with negative amount' do
b = Beeramid.new(amount: -1)
it 'returns zero' do
expect(b.calculate).to eql(0)
end
end
context 'with zero amount' do
b = Beeramid.new(amount: 0)
it 'returns zero' do
expect(b.calculate).to eql(0)
end
end
context 'with negative price' do
b = Beeramid.new(price: -1)
it 'returns nil' do
expect(b.calculate).to be_nil
end
end
context 'with zero price' do
b = Beeramid.new(price: 0)
it 'returns nil' do
expect(b.calculate).to be_nil
end
end
context 'with amount less than price' do
b = Beeramid.new(amount: 1, price: 5)
it 'returns zero' do
expect(b.calculate).to eql(0)
end
end
context 'with one can' do
b = Beeramid.new(amount: 5)
it 'should make one level' do
expect(b.calculate).to eql(1)
end
end
context 'with three cans' do
b = Beeramid.new(amount: 15)
it 'should make two levels' do
expect(b.calculate).to eql(2)
end
end
context 'with six cans' do
b = Beeramid.new(amount: 30)
it 'should make three levels' do
expect(b.calculate).to eql(3)
end
end
context 'with ten cans' do
b = Beeramid.new
it 'should make four levels' do
expect(b.calculate).to eql(4)
end
end
context 'with seven cans' do
b = Beeramid.new(amount: 35)
it 'should make three levels' do
expect(b.calculate).to eql(3)
end
end
context 'with eight cans' do
b = Beeramid.new(amount: 40)
it 'should make three levels' do
expect(b.calculate).to eql(3)
end
end
context 'with one hundred cans' do
b = Beeramid.new(price: 1, amount: 100)
it 'should make thirteen levels' do
expect(b.calculate).to eql(13)
end
end
end
end
|
package com.bluebox.smtp.storage;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bluebox.smtp.InboxAddress;
/*
* This iterator allows transparent stepping through all items in the storage using paging.
*/
public class MessageIterator implements Iterator<BlueboxMessage> {
private static final Logger log = LoggerFactory.getLogger(MessageIterator.class);
private static int MAX = 100;
private List<BlueboxMessage> list;
private Iterator<BlueboxMessage> iterator;
private InboxAddress address;
private BlueboxMessage.State state;
private int start=0-MAX;
private long totalCount, position;
private int overflowCount;
private StorageIf storage;
public MessageIterator() throws Exception {
this(null,BlueboxMessage.State.ANY);
}
public MessageIterator(InboxAddress address, BlueboxMessage.State state) throws Exception {
this(StorageFactory.getInstance(), address, state);
}
public MessageIterator(StorageIf storage, InboxAddress address, BlueboxMessage.State state) throws Exception {
this.storage = storage;
this.address = address;
this.state = state;
totalCount = storage.getMailCount(address, state);
overflowCount = 0;
position = 0;
nextPage();
}
/*
* Return percentage of where this iterator is in the overall set of results.
*/
public int getProgress() {
return (int)(((position+1)*100)/(totalCount+1));
}
private boolean nextPage() throws Exception {
start+=MAX;
list = storage.listMail(address, state, start, MAX, BlueboxMessage.RECEIVED, true);
log.debug("Getting page of {} results starting at {} (found {})",MAX,start,list.size());
iterator = list.iterator();
return list.size()>0;
}
@Override
public boolean hasNext() {
// little check to see we never get into infinite loop
if ((overflowCount++)>totalCount)
return false;
if (!iterator.hasNext()) {
// check if another page exists
try {
return nextPage();
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
else {
return true;
}
}
@Override
public BlueboxMessage next() {
position++;
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Omegasis.NightOwl.Framework
{
public class NightOwlAPI
{
/// <summary>
/// Adds an event that triggers after the player has been warped to their pre-collapse position.
/// </summary>
/// <param name="ID">The id of the event.</param>
/// <param name="Action">The code that triggers.</param>
public void addPostWarpEvent(string ID,Func<bool> Action)
{
NightOwl.PostWarpCharacter.Add(ID, Action);
}
/// <summary>
/// Removes an event that triggers when the player has been warped to their pre-collapse position.
/// </summary>
/// <param name="ID"></param>
public void removePostWarpEvent(string ID)
{
if (NightOwl.PostWarpCharacter.ContainsKey(ID))
{
NightOwl.PostWarpCharacter.Remove(ID);
}
}
/// <summary>
/// Adds an event that triggers when the player has stayed up all night until 6:00 A.M.
/// </summary>
/// <param name="ID">The id of the event.</param>
/// <param name="Action">The code that triggers.</param>
public void addPlayerUpLateEvent(string ID, Func<bool> Action)
{
NightOwl.OnPlayerStayingUpLate.Add(ID, Action);
}
/// <summary>
/// Removes an event that triggers when the player has stayed up all night.
/// </summary>
/// <param name="ID"></param>
public void removePlayerUpLateEvent(string ID)
{
if (NightOwl.OnPlayerStayingUpLate.ContainsKey(ID))
{
NightOwl.OnPlayerStayingUpLate.Remove(ID);
}
}
}
}
|
using System.Reflection;
using NUnit.Framework;
using tobixdev.github.io.CsvCheetah.Mapping;
namespace tobixdev.github.io.CsvCheetah.Tests.Mapping.Conversion.PrimitiveConverter
{
public abstract class IntConverterTestBase
{
protected abstract object Convert(string value);
protected abstract string ExpectedTypeName { get; }
[Test]
public void Convert_WithValidValue_ReturnsParsedValue()
{
var result = Convert("123");
Assert.That(result, Is.EqualTo(123));
}
[Test]
public void Convert_WithInvalidValue_ThrowsMappingException()
{
void Act() => Convert("123abc");
var exception = Assert.Throws<MappingException>(Act);
Assert.That(exception.Message, Is.EqualTo($"Cannot convert '123abc' to {ExpectedTypeName}."));
}
}
}
|
package config
import (
"encoding/json"
"io/ioutil"
)
// Persistence represents the collection of datasources defined by the developer in persistence.json
type Persistence struct {
Datasources []Datasource
}
// Datasource represents the metadata of a connection pool
type Datasource struct {
Name string `json:"name"`
Driver string `json:"driver"`
URL string `json:"url"`
Schema string `json:"schema"`
}
// GetPersistenceConfig generates the persistence struct from persistence.json
func GetPersistenceConfig(persistenceConfigFile string) Persistence {
var persistence Persistence
raw, err := ioutil.ReadFile(persistenceConfigFile)
if err == nil {
json.Unmarshal(raw, &persistence)
} else {
persistence.Datasources = make([]Datasource, 0)
}
return persistence
}
|
# What did Yahweh say he would call to mind and establish?
Yahweh said he would call to mind his covenant with Jerusalem and establish an everlasting covenant with it.
|
package zero
import (
"context"
"fmt"
"io"
"os"
"time"
"github.com/micro/go-micro/v2/logger"
"github.com/rs/zerolog"
)
var (
out io.Writer = os.Stderr
color = false
exit = os.Exit
)
type zeroLogger struct {
nativelogger zerolog.Logger
}
func (l *zeroLogger) Fields(fields ...logger.Field) logger.Logger {
data := make(map[string]interface{}, len(fields))
for _, f := range fields {
data[f.Key] = f.GetValue()
}
return &zeroLogger{l.nativelogger.With().Fields(data).Logger()}
}
func (l *zeroLogger) Init(opts ...logger.Option) error {
options := &Options{logger.Options{Context: context.Background()}}
for _, o := range opts {
o(&options.Options)
}
// Prepare Writer
if useColor, ok := options.Context.Value(useColorKey{}).(bool); ok {
color = useColor
}
if o, ok := options.Context.Value(outKey{}).(io.Writer); ok {
out = o
}
if pretty, ok := options.Context.Value(prettyKey{}).(bool); ok && pretty {
out = zerolog.NewConsoleWriter(
func(w *zerolog.ConsoleWriter) {
w.TimeFormat = time.RFC3339
w.Out = out
w.NoColor = !color
},
)
}
l.nativelogger = l.nativelogger.Output(out)
if level, ok := options.Context.Value(levelKey{}).(logger.Level); ok {
//zerolog.SetGlobalLevel(loggerToZerologLevel(level))
l.nativelogger = l.nativelogger.Level(loggerToZerologLevel(level))
} else {
l.nativelogger = l.nativelogger.Level(zerolog.InfoLevel)
}
if caller, ok := options.Context.Value(reportCallerKey{}).(bool); ok && caller {
l.nativelogger = l.nativelogger.With().Caller().Logger()
}
if levelFieldName, ok := options.Context.Value(levelFieldKey{}).(string); ok {
zerolog.LevelFieldName = levelFieldName
}
if hooks, ok := options.Context.Value(hooksKey{}).([]zerolog.Hook); ok {
for _, hook := range hooks {
l.nativelogger = l.nativelogger.Hook(hook)
}
}
if exitFunc, ok := options.Context.Value(exitKey{}).(func(int)); ok {
exit = exitFunc
}
return nil
}
func (l *zeroLogger) SetLevel(level logger.Level) {
//zerolog.SetGlobalLevel(loggerToZerologLevel(level))
l.nativelogger = l.nativelogger.Level(loggerToZerologLevel(level))
}
func (l *zeroLogger) Level() logger.Level {
return ZerologToLoggerLevel(l.nativelogger.GetLevel())
}
func (l *zeroLogger) Log(level logger.Level, args ...interface{}) {
msg := fmt.Sprintf("%s", args)
l.nativelogger.WithLevel(loggerToZerologLevel(level)).Msg(msg)
// Invoke os.Exit because unlike zerolog.Logger.Fatal zerolog.Logger.WithLevel won't stop the execution.
if level == logger.FatalLevel {
exit(1)
}
}
func (l *zeroLogger) Logf(level logger.Level, format string, args ...interface{}) {
l.nativelogger.WithLevel(loggerToZerologLevel(level)).Msgf(format, args...)
// Invoke os.Exit because unlike zerolog.Logger.Fatal zerolog.Logger.WithLevel won't stop the execution.
if level == logger.FatalLevel {
exit(1)
}
}
func (l *zeroLogger) String() string {
return "zerolog"
}
// NewLogger builds a new logger based on options
func NewLogger(opts ...logger.Option) logger.Logger {
l := &zeroLogger{}
_ = l.Init(opts...)
return l
}
func loggerToZerologLevel(level logger.Level) zerolog.Level {
switch level {
case logger.TraceLevel:
return zerolog.TraceLevel
case logger.DebugLevel:
return zerolog.DebugLevel
case logger.InfoLevel:
return zerolog.InfoLevel
case logger.WarnLevel:
return zerolog.WarnLevel
case logger.ErrorLevel:
return zerolog.ErrorLevel
case logger.PanicLevel:
return zerolog.PanicLevel
case logger.FatalLevel:
return zerolog.FatalLevel
default:
return zerolog.InfoLevel
}
}
func ZerologToLoggerLevel(level zerolog.Level) logger.Level {
switch level {
case zerolog.TraceLevel:
return logger.TraceLevel
case zerolog.DebugLevel:
return logger.DebugLevel
case zerolog.InfoLevel:
return logger.InfoLevel
case zerolog.WarnLevel:
return logger.WarnLevel
case zerolog.ErrorLevel:
return logger.ErrorLevel
case zerolog.PanicLevel:
return logger.PanicLevel
case zerolog.FatalLevel:
return logger.FatalLevel
default:
return logger.InfoLevel
}
}
|
{-# LANGUAGE GADTs, ExplicitNamespaces, TypeOperators, DataKinds #-}
module T10806 where
import GHC.TypeLits (Nat, type (<=))
data Q a where
Q :: (a <= b, b <= c) => proxy a -> proxy b -> Q c
triggersLoop :: Q b -> Q b -> Bool
triggersLoop (Q _ _) (Q _ _) = print 'x' 'y'
|
{
"Windows Console Station (VCL)"
- Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com)
@exclude
}
unit rtcVWinStationCLI;
interface
{$INCLUDE rtcDefs.inc}
USES
Windows,
SysUtils,
rtcLog;
TYPE
{ winsta.dll }
TWinStationConnect = FUNCTION(hServer: THANDLE; SessionID: ULONG;
TargetSessionID: ULONG; pPassword: PWideChar; bWait: Boolean)
: Boolean; stdcall;
{ kernel32.dll }
TWTSGetActiveConsoleSessionId = FUNCTION: DWORD; stdcall;
TProcessIdToSessionId = FUNCTION(dwProcessID: DWORD; VAR pSessionId: DWORD)
: BOOL; stdcall;
{ user32.dll }
TLockWorkStation = FUNCTION: BOOL; stdcall;
VAR
WinStationConnect: TWinStationConnect = NIL;
WTSGetActiveConsoleSessionId: TWTSGetActiveConsoleSessionId = NIL;
ProcessIdToSessionId: TProcessIdToSessionId = NIL;
LockWorkStation: TLockWorkStation = NIL;
LibsLoaded: Integer = 0;
gWinSta: HMODULE;
gKernel32: HMODULE;
gUser32: HMODULE;
FUNCTION inConsoleSession: Boolean;
PROCEDURE SetConsoleSession(pSessionId: DWORD = $FFFFFFFF);
IMPLEMENTATION
FUNCTION GetProcedureAddress(VAR P: Pointer; CONST ModuleName, ProcName: String;
VAR pModule: HMODULE): Boolean;
VAR
ModuleHandle: HMODULE;
BEGIN
IF NOT Assigned(P) THEN
BEGIN
ModuleHandle := GetModuleHandle(PChar(ModuleName));
IF ModuleHandle = 0 THEN
ModuleHandle := LoadLibrary(PChar(ModuleName));
IF ModuleHandle <> 0 THEN
P := Pointer(GetProcAddress(ModuleHandle, PChar(ProcName)));
Result := Assigned(P);
END
ELSE
Result := True;
END;
FUNCTION InitProcLibs: Boolean;
BEGIN
IF LibsLoaded > 0 THEN
Result := True
ELSE IF LibsLoaded < 0 THEN
Result := False
ELSE
BEGIN
LibsLoaded := -1;
IF GetProcedureAddress(@WinStationConnect, 'winsta.dll',
'WinStationConnectW', gWinSta) AND
GetProcedureAddress(@WTSGetActiveConsoleSessionId, 'kernel32.dll',
'WTSGetActiveConsoleSessionId', gKernel32) AND
GetProcedureAddress(@ProcessIdToSessionId, 'kernel32.dll',
'ProcessIdToSessionId', gKernel32) AND
GetProcedureAddress(@LockWorkStation, 'user32.dll', 'LockWorkStation',
gUser32) THEN
LibsLoaded := 1;
Result := LibsLoaded = 1;
END;
// {$IFDEF ExtendLog}XLog(Format('rtcTSCli.InitProclibs = %s', [BoolToStr(Result, True)]), LogAddon); {$ENDIF}
END;
PROCEDURE DeInitProcLibs;
BEGIN
IF LibsLoaded = 1 THEN
BEGIN
FreeLibrary(gWinSta);
FreeLibrary(gKernel32);
FreeLibrary(gUser32);
END;
END;
FUNCTION ProcessSessionId: DWORD;
BEGIN
Result := 0;
IF (LibsLoaded = 1) THEN
BEGIN
IF NOT ProcessIdToSessionId(GetCurrentProcessId(), Result) THEN
Result := $FFFFFFFF
END;
// {$ifdef ExtendLog}XLog(Format('ProcessSessionId = %d', [result]), LogAddon);{$endif}
END;
FUNCTION ConsoleSessionId: DWORD;
BEGIN
IF (LibsLoaded = 1) THEN
Result := WTSGetActiveConsoleSessionId
ELSE
Result := 0;
// {$ifdef ExtendLog}XLog(Format('ConsoleSessionId = %d', [result]), LogAddon);{$endif}
END;
FUNCTION inConsoleSession: Boolean;
BEGIN
Result := ConsoleSessionId = ProcessSessionId;
// {$ifdef ExtendLog}XLog(Format('inConsoleSession = %s', [booltostr(result, true)]), LogAddon);{$endif}
END;
PROCEDURE SetConsoleSession(pSessionId: DWORD = $FFFFFFFF);
BEGIN
// {$IFDEF ExtendLog}XLog(Format('SetConsoleSession(%d)', [pSessionId]), LogAddon); {$ENDIF}
IF (LibsLoaded = 1) THEN
BEGIN
IF (pSessionId = $FFFFFFFF) THEN
pSessionId := ProcessSessionId;
// {$IFDEF ExtendLog}XLog(Format('WinStationConnect(%d, %d)', [pSessionId, ConsoleSessionId]), LogAddon); {$ENDIF}
IF WinStationConnect(0, pSessionId, ConsoleSessionId, '', False) THEN
{$IFDEF FORCELOGOUT}
LockWorkStation;
{$ELSE FORCELOGOUT}
;
{$ENDIF FORCELOGOUT}
END;
END;
INITIALIZATION
InitProcLibs;
FINALIZATION
DeInitProcLibs;
END.
|
package com.github.anastr.myscore.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.anastr.data.hilt.DefaultDispatcher
import com.github.anastr.domain.entities.db.Year
import com.github.anastr.domain.entities.db.YearWithSemester
import com.github.anastr.domain.repositories.PassDegreeRepo
import com.github.anastr.domain.repositories.YearRepo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
@ExperimentalCoroutinesApi
@HiltViewModel
class YearViewModel @Inject constructor(
passDegreeRepo: PassDegreeRepo,
private val yearRepository: YearRepo,
@DefaultDispatcher defaultDispatcher: CoroutineDispatcher,
) : ViewModel() {
private val passDegree: SharedFlow<Int> =
passDegreeRepo.getPassDegree()
// Do preference job on a worker thread.
.flowOn(defaultDispatcher)
// Share the same instance of passDegree Flow between yearsFlow and finalDegreeFlow.
.shareIn(
scope = viewModelScope,
// Stop this flow immediately when there are no subscribers,
// and let the down StateFlows control the time to stop it.
started = SharingStarted.WhileSubscribed(),
replay = 1,
)
val yearsFlow: StateFlow<State<List<YearWithSemester>>> = passDegree
.flatMapLatest { yearRepository.getYearsOrdered(it) }
.map { State.Success(it) }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = State.Loading
)
val finalDegreeFlow: StateFlow<Float> = passDegree
.flatMapLatest { yearRepository.getFinalDegree(it) }
.map { it ?: 0f }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = 0f
)
fun updateYears(vararg years: Year) =
viewModelScope.launch { yearRepository.updateYears(*years) }
fun deleteYear(year: Year) = viewModelScope.launch { yearRepository.deleteYear(year) }
}
|
package ru.tech.papricoin.domain.use_case.favorite_coins.check_favorite_coin
import ru.tech.papricoin.domain.repository.PapriCoinRepository
import javax.inject.Inject
class CheckFavoriteCoinUseCase @Inject constructor(
private val repository: PapriCoinRepository
) {
suspend operator fun invoke(id: String): Boolean {
return repository.checkFavoriteCoin(id)
}
}
|
package com.badoo.reaktive.sample.android
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.badoo.reaktive.samplemppmodule.binder.KittenBinder
import com.badoo.reaktive.samplemppmodule.KittenStoreBuilderImpl
class MainActivity : AppCompatActivity() {
private lateinit var kittenBinder: KittenBinder
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
kittenBinder = KittenBinder(KittenStoreBuilderImpl())
kittenBinder.onViewCreated(KittenViewImpl(findViewById(android.R.id.content)))
}
override fun onStart() {
super.onStart()
kittenBinder.onStart()
}
override fun onStop() {
kittenBinder.onStop()
super.onStop()
}
override fun onDestroy() {
kittenBinder.onDestroy()
super.onDestroy()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.