text
stringlengths 27
775k
|
|---|
module BloodContracts::Core
# Represents failure in Tuple data matching
class TuplePolicyFailure < PolicyFailure
# Hash of attributes (name & type pairs)
#
# @return [Hash<String, Refined>]
#
def attributes
@context[:attributes]
end
# Subset of attributes which are invalid
#
# @return [Hash<String, PolicyFailure>]
#
def attribute_errors
attributes.select { |_name, type| type.invalid? }
end
# Subset of attributes which are invalid
#
# @return [Hash<String, PolicyFailure>]
#
def attribute_messages
attribute_errors.transform_values!(&:messages)
end
# Unpacked matching errors in form of a hash per attribute
#
# @return [Hash<String, PolicyFailure>]
#
def unpack_h
@unpack_h ||= attribute_errors.transform_values(&:unpack)
end
alias to_hash unpack_h
alias to_h unpack_h
alias unpack_attributes unpack_h
end
end
|
<?php
namespace ServerGrove\KbBundle\Tests\Controller\Admin;
/**
* Class UsersControllerTest
*
* @author Ismael Ambrosi<ismael@servergrove.com>
*/
class UsersControllerTest extends ControllerTestCase
{
public function testIndexAction()
{
$client = $this->getClient();
$crawler = $client->request('GET', $this->generateUrl('sgkb_admin_users_index'));
$this->assertEquals(200, $client->getResponse()->getStatusCode());
$this->assertGreaterThan(0, $crawler->filter('table.table tbody tr')->count());
}
/**
* @dataProvider getUsersData
*
* @param string $name
* @param string $email
* @param string $username
* @param string $password
* @param integer $expiration
*
* @return void
*/
public function testNewAction($name, $email, $username, $password, $expiration)
{
$client = $this->getClient();
/** @var $crawler \Symfony\Component\DomCrawler\Crawler */
$crawler = $client->request('GET', $this->generateUrl('sgkb_admin_users_new'));
$this->assertEquals(200, $client->getResponse()->getStatusCode(), $this->getErrorMessage($client));
$this->assertEquals('User creation', $crawler->filter('form legend')->first()->text());
$this->assertGreaterThan(0, $crawler->filter('form')->count());
$form = $crawler->selectButton('Create')->form();
$form['user[name]'] = $name;
$form['user[email]'] = $email;
$form['user[username]'] = $username;
$form['user[password][password]'] = $form['user[password][confirm_password]'] = $password;
$form['user[enabled]']->tick();
$form['user[roles]']->select('ROLE_ADMIN');
if (is_null($expiration)) {
unset($form['user[expirationDate]']);
} else {
$form['user[expirationDate][day]']->select(date('j', $expiration));
$form['user[expirationDate][month]']->select(date('n', $expiration));
$form['user[expirationDate][year]']->select(date('Y', $expiration));
}
$client->submit($form);
$this->assertEquals(302, $client->getResponse()->getStatusCode(), $this->getErrorMessage($client));
/** @var $user \ServerGrove\KbBundle\Document\User */
$user = $this->getDocumentManager()->getRepository('ServerGroveKbBundle:User')->findOneByUsername($username);
$this->assertInstanceOf('ServerGrove\KbBundle\Document\User', $user);
$this->assertEquals($name, $user->getName());
$this->assertEquals($email, $user->getEmail());
$this->assertEquals($username, $user->getUsername());
if (is_null($expiration)) {
$this->assertNull($user->getExpirationDate());
} else {
$this->assertEquals(date('Y-m-d', $expiration), $user->getExpirationDate()->format('Y-m-d'));
}
}
public function getUsersData()
{
return array(
array('Test user', 'test@example.com', 'testuser', 'mytestpassword', null),
array('Test user', 'test@example.com', 'testuser', 'mytestpassword', mktime(14, 21, 0, date('m') + 1, date('d') + 5))
);
}
/**
* @depends testNewAction
*/
public function testCreateAction()
{
$client = $this->getClient();
$client->request('POST', $this->generateUrl('sgkb_admin_users_create'));
$this->assertEquals(400, $client->getResponse()->getStatusCode(), $this->getErrorMessage($client));
}
public function testAdminUsersEdit()
{
$username = 'admin';
$client = $this->getClient();
/** @var $crawler \Symfony\Component\DomCrawler\Crawler */
$crawler = $client->request('GET', $this->generateUrl('sgkb_admin_users_edit', array('username' => $username)));
$this->assertEquals(200, $client->getResponse()->getStatusCode(), $this->getErrorMessage($client));
$this->assertEquals('User edit', $crawler->filter('form legend')->first()->text(), $this->getErrorMessage($client));
$this->assertGreaterThan(0, $crawler->filter('form')->count());
$form = $crawler->selectButton('Save')->form();
$form['user[name]'] = $name = 'New name '.md5(microtime(true));
$client->submit($form);
$this->assertEquals(302, $client->getResponse()->getStatusCode(), $this->getErrorMessage($client));
/** @var $user \ServerGrove\KbBundle\Document\User */
$user = $this->getDocumentManager()->getRepository('ServerGroveKbBundle:User')->findOneByUsername($username);
$this->assertInstanceOf('ServerGrove\KbBundle\Document\User', $user);
$this->assertEquals($name, $user->getName());
$this->assertEquals($username, $user->getUsername());
}
public function testUpdateAction()
{
$client = $this->getClient();
$client->request('POST', $this->generateUrl('sgkb_admin_users_update', array('username' => 'admin')));
$this->assertEquals(400, $client->getResponse()->getStatusCode(), $this->getErrorMessage($client));
}
}
|
<?php
namespace XOUser\Factory\Authentication\Adapter;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use XOUser\Authentication\Adapter\AuthAdapter;
class AuthAdapterFactory implements FactoryInterface
{
/**
* Create service
*
* @param ServiceLocatorInterface $serviceLocator
* @return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$adapter = new AuthAdapter();
$adapter->setServiceManager($serviceLocator);
return $adapter;
}
}
|
<?php
class VoteAPIController extends BaseController {
/**
*
*
* @param VoteLink $vote
* @param VoteLog $log
*/
public function __construct(VoteLink $vote, VoteLog $log)
{
$this->log = $log;
$this->vote = $vote;
$this->beforeFilter('auth');
}
/**
* Show links list
*
* @return Response
*/
public function getIndex($id = null)
{
if ( is_null($id) ) {
$links = $this->vote->all();
return View::make('pages/vote/api.list')
->with('links', $links);
}
$link = $this->vote->find($id);
if ( empty($link) ) return Redirect::to('admin/vote-links');
}
/**
* Increment VP
*
* @param int $id
* @return Response
*/
public function getResponse($id)
{
$link = $this->vote->find($id);
$user = Auth::user();
if ( empty($link) ) return Redirect::to('admin/vote-links');
$user = Auth::user();
$ip = Request::getClientIp();
$interval = Config::get('dream.links.interval');
$points = Config::Get('dream.links.points');
$response = ( $this->log->mark($user, $link, $ip) );
if ( $response ) $user->addVP($points);
return View::make('pages/vote/api.response')
->with('response', $response)
->with('link', $link)
->with('interval', $interval);
}
}
|
# Grid
Grid systems are used for creating page layouts through a series of rows and columns that house your content.
```php
use dmgpage\yii2materialize\helpers\Html;
echo Html::beginGridRow();
echo Html::gridCol('This div is 12-columns wide on all screen sizes', ['class' => 's12']);
echo Html::beginGridCol(['class' => 's6']);
echo '6-columns (one-half)';
echo Html::endGridCol();
echo Html::beginGridCol(['class' => 's6']);
echo '6-columns (one-half)';
echo Html::endGridCol();
echo Html::endGridRow();
```
|
#!/bin/sh
# Demultiplexer.sh
# Receives data from stdin and separates voice from car data.
# The data is stored into FIFO files.
if [ -e FIFOVoice ]; then
rm FIFOVoice
fi
mknod FIFOVoice p
if [ -e FIFOData ]; then
rm FIFOData
fi
mknod FIFOData p
./Demultiplexer.out
|
package com.codattle.core.model
import com.codattle.annotation.processing.annotation.GenerateDaoModelBuilder
import com.codattle.core.dao.common.DaoModel
import com.codattle.core.dao.common.DaoModelBuilder
import com.codattle.core.dao.common.Id
import com.codattle.core.model.utils.ModelUtils
import com.codattle.core.model.utils.ModelUtils.nonNull
import java.time.Instant
import java.time.ZonedDateTime
@GenerateDaoModelBuilder
data class User(
override val id: Id<User>,
override val creationDate: Instant,
val username: String
) : DaoModel<User> {
companion object {
// TODO: delete after implementing authentication be Keycloak
val DEFAULT_USER = Id<User>("DEFAULT_USER")
fun builder(): UserBuilder {
return UserBuilder.withoutDefault()
}
}
override fun toBuilder(): UserBuilder {
return UserBuilder.fromModel(this)
}
}
|
import React, { memo } from 'react';
import { Typography, Paper } from '@material-ui/core';
import LocationOnOutlinedIcon from '@material-ui/icons/LocationOnOutlined';
import { WeatherLocation } from 'types/metaWeather';
import useStyles from './styles';
export const LocationItemComponent: React.FC<WeatherLocationProps> = ({
location,
}) => {
const classes = useStyles();
return (
<Paper elevation={2} className={classes.root} title={location.title}>
<LocationOnOutlinedIcon className={classes.icon} />
<Typography variant="h6" className={classes.title} title={location.title}>
{location.title}
</Typography>
</Paper>
);
};
const LocationItem = memo(LocationItemComponent);
LocationItem.displayName = 'LocationItem';
export default LocationItem;
export interface WeatherLocationProps {
location: WeatherLocation;
}
|
require 'test_helper'
module Sip
class ControlAccesoOrgsocialesControllerTest < ActionDispatch::IntegrationTest
include Rails.application.routes.url_helpers
include Devise::Test::IntegrationHelpers
setup do
if ENV['CONFIG_HOSTS'] != 'www.example.com'
raise 'CONFIG_HOSTS debe ser www.example.com'
end
@gupoper = Sip::Grupoper.create!(PRUEBA_GRUPOPER)
@orgsocial = Sip::Orgsocial.create!(PRUEBA_ORGSOCIAL)
end
# No autenticado
################
test "sin autenticar no debe presentar listado" do
assert_raise CanCan::AccessDenied do
get sip.orgsociales_path
end
end
test "sin autenticar no debe presentar resumen de existente" do
assert_raise CanCan::AccessDenied do
get sip.orgsocial_path(@orgsocial.id)
end
end
test "sin autenticar no debe ver formulario de nuevo" do
assert_raise CanCan::AccessDenied do
get sip.new_orgsocial_path()
end
end
test "sin autenticar no debe crear" do
assert_raise CanCan::AccessDenied do
post sip.orgsociales_path, params: {
orgsocial: {
id: nil,
grupoper_attributes: {
id: nil,
nombre: 'ZZ'
}
}
}
end
end
test "sin autenticar no debe editar" do
assert_raise CanCan::AccessDenied do
get sip.edit_orgsocial_path(@orgsocial.id)
end
end
test "sin autenticar no debe actualizar" do
assert_raise CanCan::AccessDenied do
patch sip.orgsocial_path(@orgsocial.id)
end
end
test "sin autenticar no debe eliminar" do
assert_raise CanCan::AccessDenied do
delete sip.orgsocial_path(@orgsocial.id)
end
end
# Autenticado como operador
###########################
test "autenticado como operador debe presentar listado" do
current_usuario = Usuario.create!(PRUEBA_USUARIO_OP)
sign_in current_usuario
get sip.orgsociales_path
assert_response :ok
end
test "autenticado como operador debe presentar resumen" do
current_usuario = Usuario.create!(PRUEBA_USUARIO_OP)
sign_in current_usuario
get sip.orgsocial_path(@orgsocial.id)
assert_response :ok
end
test "autenticado como operador deberรญa poder editar" do
current_usuario = Usuario.create!(PRUEBA_USUARIO_OP)
sign_in current_usuario
get sip.edit_orgsocial_path(@orgsocial.id)
end
test "autenticado como operador no debe eliminar" do
assert_raise CanCan::AccessDenied do
delete sip.orgsocial_path(@orgsocial.id)
end
end
end
end
|
package tail_test
import (
"testing"
"time"
"github.com/pmdcosta/elklogs/internal/tail"
"github.com/stretchr/testify/assert"
)
const pattern = "logstash-[0-9].*"
func TestFilterIndex(t *testing.T) {
var indices = []string{"logstash-2018.11.03", "logstash-2018.10.10", "logstash-2018.10.09", "logstash-2018.10.11"}
r, err := tail.FilterIndex(indices, pattern, nil, nil)
assert.Nil(t, err)
assert.Equal(t, []string{"logstash-2018.11.03"}, r)
}
func TestFilterIndex_end(t *testing.T) {
var indices = []string{"logstash-2018.11.03", "logstash-2018.10.10", "logstash-2018.10.09", "logstash-2018.10.11"}
end, err := time.Parse("2006-01-02T15:04", "2018-11-01T00:00")
assert.Nil(t, err)
r, err := tail.FilterIndex(indices, pattern, nil, &end)
assert.Nil(t, err)
assert.Equal(t, []string{"logstash-2018.10.10", "logstash-2018.10.09", "logstash-2018.10.11"}, r)
}
func TestFilterIndex_start(t *testing.T) {
var indices = []string{"logstash-2018.11.03", "logstash-2018.10.10", "logstash-2018.10.09", "logstash-2018.10.11"}
start, err := time.Parse("2006-01-02T15:04", "2018-10-10T00:00")
assert.Nil(t, err)
r, err := tail.FilterIndex(indices, pattern, &start, nil)
assert.Nil(t, err)
assert.Equal(t, []string{"logstash-2018.11.03", "logstash-2018.10.10", "logstash-2018.10.11"}, r)
}
|
module TrailingZeroes where
{-
public int trailingZeroes0(int n) {
int sum=0;
while(n>=5){
sum += n / 5;
n = n / 5; }
return sum; }
-}
trailingZeroes0 :: Int -> Int
trailingZeroes0 n = go 0 n
where
go s n | n >= 5 = go (s + n `div` 5) (n `div` 5)
| otherwise = s
{-
public int trailingZeroes1(int n) {
int x=0;
int y=n/5;
while(y!=0){
x = x + y;
y = y / 5;}
return x; }
-}
trailingZeroes1 :: Int -> Int
trailingZeroes1 n = go 0 (n `div` 5)
where
go x y | y /= 0 = go (x + y) (y `div` 5)
| otherwise = x
|
<?php
include 'simplexlsx.class.php';
include('common.php');
include('db.php');
define("TAXIVAXI_NUMBER", "7891022360");
define("TAXIVAXI_EMAIL", "corporate.oe@taxivaxi.com");
$db = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD);
mysqli_select_db($db,DB);
function dbConnect()
{
$this->db = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD);
if($this->db)
mysqli_select_db($this->db,DB);
}
function dbClose()
{
mysqli_close($this->db);
}
$k=0;
$new_entries = 0;
$updated = 0;
$sql = mysqli_query($db, "SELECT booking_id, ticket from bus_invoice where ticket != '' and created > '2016-04-27'");
if(mysqli_num_rows($sql) > 0)
{
while($rlt = mysqli_fetch_array($sql))
{
$booking_id = $rlt['booking_id'];
$duty_slip_url = $rlt['ticket'];
$opts = array(
'http'=>array(
'header' => 'Connection: close'
)
);
$context = stream_context_create($opts);
$content = @file_get_contents($duty_slip_url,false,$context);
if($content === FALSE)
{
echo "$booking_id - $duty_slip_url<br>";
$new_entries++;
}
}
//var_dump($rlt);
//echo "<br><br>";
}
//echo "<br>".$new_entries;
?>
|
---
title: ์ ๋ํฐ - ์ปดํ์ผ, ๊ฒ์ ์์ ์ ์คํ๋๋ ์ ํธ๋ฆฌ๋ทฐํธ ์ ๋ฆฌ
author: Rito15
date: 2021-03-08 03:03:00 +09:00
categories: [Unity, Unity Editor]
tags: [unity, editor, csharp]
math: true
mermaid: true
---
# ๊ณตํต ํน์ง
---
- ํด๋์ค ๋๋ ๋ฉ์๋ ์๋จ์ ์ ํธ๋ฆฌ๋ทฐํธ๋ฅผ ๋ช
์ํ๋ค.
- ์ปดํฌ๋ํธ๋ก ๋ฃ์ง ์๊ณ , ์คํฌ๋ฆฝํธ๋ก๋ง ์กด์ฌํด๋ ์คํ๋๋ค.
- ์ ์ ํด๋์ค๋ ์์์ ๊ด๊ณ ์์ด ๋์ํ๋ค.
- ๋ฉ์๋ ์ ํธ๋ฆฌ๋ทฐํธ๋ ์ ์ ๋ฉ์๋์๋ง ๋์ํ๋ค.
<br>
# ์ปดํ์ผ, ํ๋ ์ด๋ชจ๋ ์ง์
์ ์คํ
---
## Note
- `EditorApplication.isPlaying`์ผ๋ก ํ์ฌ ์๋ํฐ ๋ชจ๋๋ฅผ ๊ตฌ๋ถํ์ฌ ํ์ฉํ ์ ์๋ค.
<br>
## **[InitializeOnLoad]**
- `using UnityEditor;`
- ํด๋์ค ์ ํธ๋ฆฌ๋ทฐํธ
- **์ ์ ์์ฑ์๊ฐ ํธ์ถ๋๋ฏ๋ก, ์ ์ ์์ฑ์์ ์ํ๋ ์ฝ๋๋ฅผ ์์ฑํ๋ค.**
- ์คํ ํ์ด๋ฐ : ์ปดํ์ผ, ํ๋ ์ด๋ชจ๋ ์ง์
(Awake() ํธ์ถ ์ด์ )
- ํ์ฉ : `EditorApplication.update`์ ์ด๋ฒคํธ ํธ๋ค๋ฌ๋ฅผ ์ถ๊ฐํ๊ณ ์ถ์ ๋
<br>
## **[InitializeOnLoadMethod]**
- `using UnityEditor;`
- ๋ฉ์๋ ์ ํธ๋ฆฌ๋ทฐํธ
- ์คํ ํ์ด๋ฐ : ์ปดํ์ผ, ํ๋ ์ด๋ชจ๋ ์ง์
(Awake() ํธ์ถ ์ด์ )
<br>
# ํ๋ ์ด ๋ชจ๋ ์ง์
์ ์คํ
---
## **[InitializeOnEnterPlayMode]**
- `using UnityEditor;`
- ๋ฉ์๋ ์ ํธ๋ฆฌ๋ทฐํธ
- ์คํ ํ์ด๋ฐ : ํ๋ ์ด ๋ชจ๋ ์ง์
(Awake() ํธ์ถ ์ด์ )
<br>
## **[RuntimeInitializeOnLoadMethod]**
- `using UnityEngine`
- ๋ฉ์๋ ์ ํธ๋ฆฌ๋ทฐํธ
- ์คํ ํ์ด๋ฐ : ํ๋ ์ด ๋ชจ๋ ์ง์
(Awake(), OnEnable() ํธ์ถ ์ดํ)
<br>
# ์คํ ์์(ํ๋ ์ด ๋ชจ๋ ๊ธฐ์ค)
---
- `[InitializeOnLoad]` : ์ ์ ์์ฑ์
- `[InitializeOnEnterPlayMode]` : ์ ์ ๋ฉ์๋
- `[InitializeOnLoadMethod]` : ์ ์ ๋ฉ์๋
- `Awake()`, `OnEnable()` : ๋์ผ ํด๋์ค ๋ด์์๋ `Awake()` ์ฐ์
- `[RuntimeInitializeOnLoadMethod]` : ์ ์ ๋ฉ์๋
- `Start()`
<br>
# References
---
- <https://docs.unity3d.com/2019.3/Documentation/ScriptReference/InitializeOnEnterPlayModeAttribute.html>
- <https://docs.unity3d.com/kr/530/Manual/RunningEditorCodeOnLaunch.html>
|
package main;
import(
"fmt"
)
func main(){
f()
}
func f(){
for i:=0;i<4;i++{
g:=func(i int){fmt.Printf("%d",i)}
g(i)
fmt.Printf(" -g is is of type %T and has value %v\n",g,g)
}
}
|
require 'aruba/spawn_process'
module Aruba
describe SpawnProcess do
let(:process) { SpawnProcess.new('echo "yo"', 0.1, 0.1) }
describe "#stdout" do
before { process.run! }
it "returns the stdout" do
expect(process.stdout).to eq "yo\n"
end
it "returns all the stdout, every time you call it" do
expect(process.stdout).to eq "yo\n"
expect(process.stdout).to eq "yo\n"
end
end
describe "#stop" do
before { process.run! }
it "sends any output to the reader" do
reader = double( 'null_object' )
allow( reader ).to receive( :stderr )
expect( reader ).to receive( :stdout ).with("yo\n")
process.stop(reader)
end
end
describe "#run!" do
context "upon process launch error" do
let(:process_failure) { SpawnProcess.new('does_not_exists', 1, 1) }
it "raises a Aruba::LaunchError" do
expect{process_failure.run!}.to raise_error(::Aruba::LaunchError)
end
end
end
end
end
|
'use strict';
const chai = require('chai');
const sinon = require('sinon');
const hooks = require('../index');
const mocks = require('../mocks/model.mock');
const { expect } = chai;
const { getModel } = mocks;
describe('hooks-promise', () => {
let model;
describe('pre()', () => {
let spyPre1;
let spyPre2;
let spyOriginalMethod;
const error = {
code: 500,
};
const spies = {
preHook1() {
this.newValue = 123;
return Promise.resolve();
},
preHook2() {
return Promise.resolve();
},
};
beforeEach(() => {
model = getModel();
hooks.wrap(model);
spyPre1 = sinon.spy(spies, 'preHook1');
spyPre2 = sinon.spy(spies, 'preHook2');
spyOriginalMethod = sinon.spy(model, 'save');
model.pre('save', spies.preHook1);
model.pre('save', spies.preHook2);
});
afterEach(() => {
spyPre1.restore();
spyPre2.restore();
spyOriginalMethod.restore();
});
it('should execute pre hooks in correct order', () => model.save().then(() => {
sinon.assert.callOrder(spyPre1, spyPre2, spyOriginalMethod);
}));
it('should allow an Array of middleware', () => {
model = getModel();
hooks.wrap(model);
spyOriginalMethod = sinon.spy(model, 'save');
model.pre('save', [spies.preHook1, spies.preHook2]);
return model.save().then(() => {
sinon.assert.callOrder(spyPre1, spyPre2, spyOriginalMethod);
});
});
it('should pass the correct scope to the hook', () => model.save().then(() => {
expect(model.newValue).equal(123);
}));
it('should catch errors in hooks and not call the original method', () => {
model.pre('save', () => Promise.reject(error));
return model.save().catch((err) => {
expect(err).equal(error);
expect(spyOriginalMethod.called).equal(false);
});
});
it('should pass parameter to originalMethod', () => {
const args = ['abc', 123];
return model.save('abc', 123).then(() => {
expect(spyOriginalMethod.getCall(0).args).deep.equal(args);
});
});
it('preHook resolve should **not** override original parameter passed', () => {
model.pre('save', () => Promise.resolve({ abc: 123 }));
return model.save({ abc: 777 }).then((response) => {
expect(response).equal('1234');
expect(spyOriginalMethod.getCall(0).args[0].abc).equal(777);
});
});
it('preHook resolve should override original parameter passed (multi)', () => {
model.pre('save', () => Promise.resolve({ __override: ['newParam1', 'newParam2'] }));
return model.save(123, 'abc').then(() => {
expect(spyOriginalMethod.getCall(0).args).deep.equal(['newParam1', 'newParam2']);
});
});
it('preHook resolve should override original parameter passed (single)', () => {
model.pre('save', () => Promise.resolve({ __override: 'newParam1' }));
return model.save(123, 'abc').then(() => {
expect(spyOriginalMethod.getCall(0).args).deep.equal(['newParam1']);
});
});
it('should work with methods from an object', () => {
const myObject = {
save() { return Promise.resolve(); },
test1() { },
};
hooks.wrap(myObject);
spyOriginalMethod = sinon.spy(myObject, 'save');
myObject.pre('save', spies.preHook1);
myObject.pre('save', spies.preHook2);
return myObject.save().then(() => {
sinon.assert.callOrder(spyPre1, spyPre2, spyOriginalMethod);
});
});
it('bypass middleware(s)', () => {
model.preHooksEnabled = false;
return model.save('abc', 123).then(() => {
expect(spyPre1.called).equal(false);
});
});
it('override the middleware scope and pass the hook function name', () => {
const scopePre = { x: 1 };
const scopePost = { y: 2 };
let check1;
let check2;
let scope1;
let scope2;
model = getModel();
model.__scopeHook = function setScope(hookName, args, hookMethod, hookType) {
if (hookName === 'save') {
check1 = hookMethod;
} else if (hookName === 'delete' && hookType === 'pre') {
check2 = hookMethod;
}
return hookType === 'pre' ? scopePre : scopePost;
};
hooks.wrap(model);
function myPreHookMethod() {
scope1 = this;
return Promise.resolve();
}
function myPostHookMethod() {
scope2 = this;
return Promise.resolve();
}
const myPreHookMethod2 = () => Promise.resolve();
// We make sure that the hookMethod passed to __scopeHook
// works with both functions and arrow functions
model.pre('save', myPreHookMethod);
model.pre('delete', myPreHookMethod2);
model.post('delete', myPostHookMethod);
return model.save()
.then(() => model.delete())
.then(() => {
expect(scope1).equal(scopePre);
expect(scope2).equal(scopePost);
expect(check1).equal('myPreHookMethod');
expect(check2).equal('myPreHookMethod2');
});
});
});
describe('post()', () => {
let spyPost1;
let spyPost2;
let spyOriginalMethod;
const spies = {
postHook1(result) {
this.newValue = 456;
return Promise.resolve(result);
},
postHook2(result) {
return Promise.resolve(result);
},
};
beforeEach(() => {
model = getModel();
hooks.wrap(model);
spyPost1 = sinon.spy(spies, 'postHook1');
spyPost2 = sinon.spy(spies, 'postHook2');
spyOriginalMethod = sinon.spy(model, 'save');
model.post('save', spies.postHook1);
model.post('save', spies.postHook2);
});
afterEach(() => {
spyPost1.restore();
spyPost2.restore();
spyOriginalMethod.restore();
});
it('should execute posts hooks in correct order', () => model.save().then(() => {
sinon.assert.callOrder(spyOriginalMethod, spyPost1, spyPost2);
}));
it('should allow an Array of middleware', () => {
model = getModel();
hooks.wrap(model);
spyOriginalMethod = sinon.spy(model, 'save');
model.post('save', [spyPost1, spyPost2]);
return model.save().then(() => {
sinon.assert.callOrder(spyOriginalMethod, spyPost1, spyPost2);
});
});
it('should pass the correct scope to the hook', () => model.save().then(() => {
expect(model.newValue).equal(456);
}));
it('should pass resolve value from originalMethod response', () => (
model.save().then((response) => {
expect(response).equal('1234');
})
));
it('should **not** override original resolve in post hooks', () => {
model.post('savePromise', () => Promise.resolve('5678'));
return model.savePromise().then((response) => {
expect(response).equal('1234');
});
});
it('should override original resolve in post hooks', () => {
model.post('save', () => Promise.resolve({ __override: '5678' }));
return model.save().then((response) => {
expect(response).equal('5678');
});
});
it('should not reject promise on error (error in "errorsPostHook")', () => {
const error = { code: 500 };
model.post('save', () => Promise.reject(error));
return model.save().then((response) => {
expect(response).deep.equal({
result: '1234',
});
expect(response[hooks.ERRORS][0]).equal(error);
});
});
it('should not reject promise on error (error in Symbol)', () => {
const error = { code: 500 };
model.post('saveReturnObject', () => Promise.reject(error));
return model.saveReturnObject().then((response) => {
expect(response.a).equal(123);
expect(response[hooks.ERRORS][0]).equal(error);
});
});
it('should override response (1)', () => {
const error = { code: 500 };
model = getModel();
hooks.wrap(model);
model.post('save', () => Promise.reject(error));
model.post('save', () => Promise.resolve({ __override: 'new response' }));
return model.save().then((response) => {
expect(response).deep.equal({
result: 'new response',
});
expect(response[hooks.ERRORS][0]).equal(error);
});
});
it('should override response (2)', () => {
model = getModel();
hooks.wrap(model);
const err = new Error();
err.code = 501;
model.post('save', () => Promise.resolve({ __override: { abc: 123 } }));
model.post('save', () => Promise.reject(err));
model.post('save', () => Promise.resolve({ __override: { abc: 456 } }));
return model.save().then((response) => {
expect(response.abc).equal(456);
expect(response[hooks.ERRORS][0].code).equal(501);
});
});
it('should work with methods from an object', () => {
const myObject = {
save() { return Promise.resolve(); },
test1() { },
};
hooks.wrap(myObject);
spyOriginalMethod = sinon.spy(myObject, 'save');
myObject.post('save', spies.postHook1);
myObject.post('save', spies.postHook2);
return myObject.save().then(() => {
sinon.assert.callOrder(spyOriginalMethod, spyPost1, spyPost2);
});
});
it('should convert original target method response to a Promise', () => {
model = getModel();
const spy = { original: () => true };
const spyOriginal = sinon.spy(spy, 'original');
sinon.stub(model, 'save').returns(spy.original());
hooks.wrap(model);
model.post('save', [spyPost1, spyPost2]);
return model.save().then(() => {
sinon.assert.callOrder(spyOriginal, spyPost1, spyPost2);
});
});
});
});
|
class AttributesTableComponent < ViewComponent::Base
def initialize(model, list, custom_values: false)
@attributes = {}
#
# TODO: make this nicer
# Possible solution: we could use decorators instead of this to handle getting stuff from linked items.
# At this point I'm not sure whether we would want to use the linked item decorator or the parent item.
# For instance, a company linked to a contact, do we want to use the company decorator to render
# the company name or a decorator on the contact? Would there be differences? Do we want consistency instead?
# Also this shit isn't even recursive. So more than one degree of sepration would break this.
#
list.each do |item|
if item.instance_of? Hash
item.each do |key, values|
sub_model = model.public_send key
next if sub_model.blank?
Array(values).each do |val|
@attributes[model.class.human_attribute_name("#{key}.#{val}")] = sub_model.decorate val
end
end
else
@attributes[model.class.human_attribute_name(item)] = model.decorate item
end
end
if custom_values && model.respond_to?('custom_values')
model.custom_values.includes(:custom_field).each do |custom_value|
@attributes[custom_value.custom_field.name] = custom_value.decorate :value
end
end
end
end
|
/*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.script.examples.jvm.embeddable.test
import org.jetbrains.kotlin.script.examples.jvm.embeddable.host.evalFile
import org.junit.Assert
import java.io.File
import org.junit.Test
import kotlin.script.experimental.api.ResultWithDiagnostics
class SimpleTest {
@Test
fun testSimple() {
// see comments in the script file
val res = evalFile(File("testData/useGuava.simplescript.kts"))
Assert.assertTrue(
"test failed:\n ${res.reports.joinToString("\n ") { it.message + if (it.exception == null) "" else ": ${it.exception}" }}",
res is ResultWithDiagnostics.Success
)
}
}
|
# Overview
Super Source let's you know who's using your software projects. If you have an open source project,
and would like to understand who your users are, you should use Super Source.
## Getting Started
Getting started with Super Source takes just a few minutes. For instructions, read the
[getting started](/docs/overview/getting_started) page.
## Why Use Super Source
- Learn who's using your project.
- Develop relationships with your users.
- Send announcements over email.
|
import { outputFileInformation } from './outputFileInformation'
const outputTextArea = document.querySelector('textarea')
const handleFile = outputFileInformation(outputTextArea)
const fileInput = document.querySelector('input')
fileInput.addEventListener('change', handleFile)
|
package com.yotpo.metorikku.input.kafka
import java.util.Properties
import com.yotpo.metorikku.input.Reader
import com.yotpo.metorikku.instrumentation.KafkaLagWriter
import com.yotpo.metorikku.session.Session.getSparkSession
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.spark.sql.DataFrame
case class KafkaInput(name: String, servers: Seq[String], topic: String, consumerGroup: Option[String],
options: Option[Map[String, String]]) extends Reader {
@transient lazy val log = org.apache.log4j.LogManager.getLogger(this.getClass)
def read(): DataFrame = {
consumerGroup match {
case Some(group) =>
log.info(s"creating consumer group with id $group")
val consumer = createKafkaConsumer(group)
val lagWriter = new KafkaLagWriter(consumer, topic)
getSparkSession.streams.addListener(lagWriter)
case _ =>
}
val bootstrapServers = servers.mkString(",")
val inputStream = getSparkSession.readStream.format("kafka")
.option("kafka.bootstrap.servers", bootstrapServers)
.option("subscribe", topic)
if (options.nonEmpty) {
inputStream.options(options.get)
}
inputStream.load()
}
private def createKafkaConsumer(consumerGroupID: String) = {
val props = new Properties()
props.put("bootstrap.servers", servers.mkString(","))
props.put("group.id", consumerGroupID)
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
new KafkaConsumer[String, String](props)
}
}
|
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.2")
// https://developer.lightbend.com/docs/paradox/current/
addSbtPlugin("com.lightbend.paradox" % "sbt-paradox" % "0.9.2")
// https://www.scala-sbt.org/sbt-site/getting-started.html
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "1.4.1")
// https://github.com/sbt/sbt-ghpages
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.6.3")
// https://github.com/sbt/sbt-header
addSbtPlugin("de.heikoseeberger" % "sbt-header" % "5.6.0")
// https://github.com/sbt/sbt-unidoc
addSbtPlugin("com.eed3si9n" % "sbt-unidoc" % "0.4.3")
// https://github.com/djspiewak/sbt-github-actions
addSbtPlugin("com.codecommit" % "sbt-github-actions" % "0.12.0")
// https://github.com/ktoso/sbt-jmh
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
// https://github.com/sbt/sbt-pgp
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
// https://github.com/sbt/sbt-release
addSbtPlugin("com.github.sbt" % "sbt-release" % "1.1.0")
// https://github.com/xerial/sbt-sonatype
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.7")
// https://github.com/sbt/sbt-projectmatrix
addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.8.0")
addSbtPlugin("com.indoorvivants" % "sbt-commandmatrix" % "0.0.3")
|
#!/usr/bin/env escript
%% -*- erlang -*-
loop(Max, Max) ->
ok;
loop(X, Max) ->
loop(X + 1, Max).
main([]) ->
M = 2000000,
loop(0, M).
|
package net.corda.djvm.analysis
import net.corda.djvm.code.EmitterModule
import net.corda.djvm.code.ruleViolationError
import net.corda.djvm.code.thresholdViolationError
import net.corda.djvm.messages.Severity
import net.corda.djvm.references.ClassModule
import net.corda.djvm.references.Member
import net.corda.djvm.references.MemberModule
import net.corda.djvm.references.MethodBody
import net.corda.djvm.source.BootstrapClassLoader
import net.corda.djvm.source.SourceClassLoader
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type
import sandbox.net.corda.djvm.costing.RuntimeCostAccounter
import java.io.Closeable
import java.io.IOException
import java.nio.file.Path
/**
* The configuration to use for an analysis.
*
* @property whitelist The whitelist of class names.
* @param additionalPinnedClasses Classes that have already been declared in the sandbox namespace and that should be
* made available inside the sandboxed environment.
* @property minimumSeverityLevel The minimum severity level to log and report.
* @param classPath The extended class path to use for the analysis.
* @param bootstrapJar The location of a jar containing the Java APIs.
* @property analyzeAnnotations Analyze annotations despite not being explicitly referenced.
* @property prefixFilters Only record messages where the originating class name matches one of the provided prefixes.
* If none are provided, all messages will be reported.
* @property classModule Module for handling evolution of a class hierarchy during analysis.
* @property memberModule Module for handling the specification and inspection of class members.
*/
class AnalysisConfiguration(
val whitelist: Whitelist = Whitelist.MINIMAL,
additionalPinnedClasses: Set<String> = emptySet(),
val minimumSeverityLevel: Severity = Severity.WARNING,
classPath: List<Path> = emptyList(),
bootstrapJar: Path? = null,
val analyzeAnnotations: Boolean = false,
val prefixFilters: List<String> = emptyList(),
val classModule: ClassModule = ClassModule(),
val memberModule: MemberModule = MemberModule()
) : Closeable {
/**
* Classes that have already been declared in the sandbox namespace and that should be made
* available inside the sandboxed environment. These classes belong to the application
* classloader and so are shared across all sandboxes.
*/
val pinnedClasses: Set<String> = MANDATORY_PINNED_CLASSES + additionalPinnedClasses
/**
* These interfaces are modified as they are mapped into the sandbox by
* having their unsandboxed version "stitched in" as a super-interface.
* And in some cases, we need to add some synthetic bridge methods as well.
*/
val stitchedInterfaces: Map<String, List<Member>> get() = STITCHED_INTERFACES
/**
* Functionality used to resolve the qualified name and relevant information about a class.
*/
val classResolver: ClassResolver = ClassResolver(pinnedClasses, TEMPLATE_CLASSES, whitelist, SANDBOX_PREFIX)
private val bootstrapClassLoader = bootstrapJar?.let { BootstrapClassLoader(it, classResolver) }
val supportingClassLoader = SourceClassLoader(classPath, classResolver, bootstrapClassLoader)
@Throws(IOException::class)
override fun close() {
supportingClassLoader.use {
bootstrapClassLoader?.close()
}
}
fun isTemplateClass(className: String): Boolean = className in TEMPLATE_CLASSES
fun isPinnedClass(className: String): Boolean = className in pinnedClasses
companion object {
/**
* The package name prefix to use for classes loaded into a sandbox.
*/
private const val SANDBOX_PREFIX: String = "sandbox/"
/**
* These class must belong to the application class loader.
* They should already exist within the sandbox namespace.
*/
private val MANDATORY_PINNED_CLASSES: Set<String> = setOf(
RuntimeCostAccounter.TYPE_NAME,
ruleViolationError,
thresholdViolationError
)
/**
* These classes will be duplicated into every sandbox's
* classloader.
*/
private val TEMPLATE_CLASSES: Set<String> = setOf(
java.lang.Boolean::class.java,
java.lang.Byte::class.java,
java.lang.Character::class.java,
java.lang.Double::class.java,
java.lang.Float::class.java,
java.lang.Integer::class.java,
java.lang.Long::class.java,
java.lang.Number::class.java,
java.lang.Runtime::class.java,
java.lang.Short::class.java,
java.lang.String::class.java,
java.lang.String.CASE_INSENSITIVE_ORDER::class.java,
java.lang.System::class.java,
java.lang.ThreadLocal::class.java,
kotlin.Any::class.java,
sun.misc.JavaLangAccess::class.java,
sun.misc.SharedSecrets::class.java
).sandboxed() + setOf(
"sandbox/Task",
"sandbox/java/lang/DJVM",
"sandbox/sun/misc/SharedSecrets\$1",
"sandbox/sun/misc/SharedSecrets\$JavaLangAccessImpl"
)
/**
* These interfaces will be modified as follows when
* added to the sandbox:
*
* <code>interface sandbox.A extends A</code>
*/
private val STITCHED_INTERFACES: Map<String, List<Member>> = mapOf(
sandboxed(CharSequence::class.java) to listOf(
object : MethodBuilder(
access = ACC_PUBLIC or ACC_SYNTHETIC or ACC_BRIDGE,
className = "sandbox/java/lang/CharSequence",
memberName = "subSequence",
descriptor = "(II)Ljava/lang/CharSequence;"
) {
override fun writeBody(emitter: EmitterModule) = with(emitter) {
pushObject(0)
pushInteger(1)
pushInteger(2)
invokeInterface(className, memberName, "(II)L$className;")
returnObject()
}
}.withBody()
.build(),
MethodBuilder(
access = ACC_PUBLIC or ACC_ABSTRACT,
className = "sandbox/java/lang/CharSequence",
memberName = "toString",
descriptor = "()Ljava/lang/String;"
).build()
),
sandboxed(Comparable::class.java) to emptyList(),
sandboxed(Comparator::class.java) to emptyList(),
sandboxed(Iterable::class.java) to emptyList()
)
private fun sandboxed(clazz: Class<*>) = SANDBOX_PREFIX + Type.getInternalName(clazz)
private fun Set<Class<*>>.sandboxed(): Set<String> = map(Companion::sandboxed).toSet()
}
private open class MethodBuilder(
protected val access: Int,
protected val className: String,
protected val memberName: String,
protected val descriptor: String) {
private val bodies = mutableListOf<MethodBody>()
protected open fun writeBody(emitter: EmitterModule) {}
fun withBody(): MethodBuilder {
bodies.add(::writeBody)
return this
}
fun build() = Member(
access = access,
className = className,
memberName = memberName,
signature = descriptor,
genericsDetails = "",
body = bodies
)
}
}
|
package torsvc
import (
"fmt"
"net"
)
// RegularNet is an implementation of the Net interface that defines behaviour
// for Regular network connections
type RegularNet struct{}
// Dial on the regular network uses net.Dial
func (r *RegularNet) Dial(network, address string) (net.Conn, error) {
return net.Dial(network, address)
}
// LookupHost for regular network uses the net.LookupHost function
func (r *RegularNet) LookupHost(host string) ([]string, error) {
return net.LookupHost(host)
}
// LookupSRV for regular network uses net.LookupSRV function
func (r *RegularNet) LookupSRV(service, proto, name string) (string, []*net.SRV, error) {
return net.LookupSRV(service, proto, name)
}
// ResolveTCPAddr for regular network uses net.ResolveTCPAddr function
func (r *RegularNet) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) {
return net.ResolveTCPAddr(network, address)
}
// TorProxyNet is an implementation of the Net interface that defines behaviour
// for Tor network connections
type TorProxyNet struct {
// TorDNS is the IP:PORT of the DNS server for Tor to use for SRV queries
TorDNS string
// TorSocks is the port which Tor's exposed SOCKS5 proxy is listening on.
// This is used for an outbound-only mode, so the node will not listen for
// incoming connections
TorSocks string
}
// Dial on the Tor network uses the torsvc TorDial() function, and requires
// that network specified be tcp because only that is supported
func (t *TorProxyNet) Dial(network, address string) (net.Conn, error) {
if network != "tcp" {
return nil, fmt.Errorf("Cannot dial non-tcp network via Tor")
}
return TorDial(address, t.TorSocks)
}
// LookupHost on Tor network uses the torsvc TorLookupHost function.
func (t *TorProxyNet) LookupHost(host string) ([]string, error) {
return TorLookupHost(host, t.TorSocks)
}
// LookupSRV on Tor network uses the torsvc TorLookupHost function.
func (t *TorProxyNet) LookupSRV(service, proto, name string) (string, []*net.SRV, error) {
return TorLookupSRV(service, proto, name, t.TorSocks, t.TorDNS)
}
// ResolveTCPAddr on Tor network uses the towsvc TorResolveTCP function, and
// requires network to be "tcp" because only "tcp" is supported
func (t *TorProxyNet) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) {
if network != "tcp" {
return nil, fmt.Errorf("Cannot dial non-tcp network via Tor")
}
return TorResolveTCP(address, t.TorSocks)
}
|
---
layout: post
title: "Week #5"
date: 2016-10-13 17:47:00
author: Javier Dรญaz, Patricio Merino
categories: progress
---
# Week #5
Semana del 11 al 14 de septiembre.
Se trabajรณ en el blog. No hubo planificaciรณn en Kanban.
|
<?php
if (!defined("MUTTER")) exit("(OoO)");
/*
This is a sample HelloWorld infra(Model).
This infrastructure simply print a "Hello World!" out.
As a scaffold model, just duplicate this file, rename the class name and file name,
and add the stuff you needed like TemplateEngine into this infra, it's done!
Don't forget go to index.php and add route rule to this infra so router will know what to do!
*/
class HelloWorld extends SubFolderFriendly implements Infra {
public function __construct($config) { // Argument(s) are optional, but pass a Config class is useful.
if ($config == null || !is_a($config, "Config")) exit("(O_O)"); // check the value is a Config class.
$this->dataFilePath = $config->dataFolderPath; // this line is neccessary if this infra is `SubFolderFriendly`
$this->setSubFolderName("hello"); // dig into `SubFolderFriendly` class and check out when we need this.
}
public function routeArray($routeArray) {}
public function renderPage() {
/*
if you don't use any Infra as a subInfra, you can just use `echo` in `renderPage()`
But if you do use any subInfra, use return to return the content you've constructed.
Check out the TemplateEngine source code to see why.
*/
//echo $this->getDataFilePath(); // Uncomment this and play with it!
return "Hello World!<br/>";
}
}
?>
|
๏ปฟusing System.Collections.Generic;
using Prism.Ioc;
using Prism.IocContainer.Wpf.Tests.Support.Mocks;
using Xunit;
using static Prism.Container.Wpf.Tests.ContainerHelper;
namespace Prism.Container.Wpf.Tests.Ioc
{
public class ContainerExtensionFixture
{
[Fact]
public void ExtensionReturnsTrueIfThereIsAPolicyForType()
{
var container = CreateContainerExtension();
container.Register<object, string>();
Assert.True(container.IsRegistered(typeof(object)));
Assert.False(container.IsRegistered(typeof(int)));
container.Register<IList<int>, List<int>>();
Assert.True(container.IsRegistered(typeof(IList<int>)));
Assert.False(container.IsRegistered(typeof(IList<string>)));
container.Register(typeof(IDictionary<,>), typeof(Dictionary<,>));
Assert.True(container.IsRegistered(typeof(IDictionary<,>)));
}
[Fact]
public void TryResolveShouldResolveTheElementIfElementExist()
{
var container = CreateContainerExtension();
container.Register<IService, MockService>();
object dependantA = null;
var ex = Record.Exception(() => dependantA = container.Resolve<IService>());
Assert.Null(ex);
Assert.NotNull(dependantA);
}
[Fact]
public void TryResolveShouldReturnNullIfElementNotExist()
{
var container = CreateContainerExtension();
object dependantA = null;
var ex = Record.Exception(() => dependantA = container.Resolve<IDependantA>());
Assert.NotNull(ex);
Assert.Null(dependantA);
}
}
}
|
using NUnit.Framework;
using System;
namespace EgnHelper.Tests
{
[TestFixture]
public class Tests
{
[TestCase("7523169263")]
[TestCase("7552010005")]
[TestCase("6101057509")]
public void IsValid_ShouldReturnTrueForValidEgn(string egn)
{
Console.WriteLine("In test");
// Arrange
var validate = new EgnValidator();
// Act
var result = validate.IsValid(egn);
// Assert
Assert.IsTrue(result);
}
[TestCase("1111111111", "Only ones")]
[TestCase("jhdhdvgbhygvbdfygb", "Not digits")]
[TestCase("", "Empty string")]
[TestCase("0000000000", "Invalid day of month")]
[TestCase("7523169262", "Invalid checksum")]
[TestCase("7523169264", "Invalid checksum")]
[TestCase("7502300005", "Invalid day")]
public void IsValid_ShouldReturnFalseForInvalidEgn(string egn, string message)
{
Console.WriteLine("In test");
// Arrange
var validate = new EgnValidator();
// Act
var result = validate.IsValid(egn);
// Assert
Assert.IsFalse(result, message);
}
[Test]
public void IsValidMethodShouldThrowAnExceptionWhenTheGivenArgumentIsNull()
{
// Arrange
var validate = new EgnValidator();
Assert.That(() => validate.IsValid(null), Throws.Exception);
Assert.Throws<ArgumentNullException>(() => validate.IsValid(null));
}
}
}
|
/*!
* Start Bootstrap - SB Admin v6.0.2 (https://startbootstrap.com/template/sb-admin)
* Copyright 2013-2020 Start Bootstrap
* Licensed under MIT (https://github.com/StartBootstrap/startbootstrap-sb-admin/blob/master/LICENSE)
*/
(function($) {
"use strict";
// Add active state to sidbar nav links
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$("#layoutSidenav_nav .sb-sidenav a.nav-link").each(function() {
if (this.href === path) {
$(this).addClass("active");
}
});
// Toggle the side navigation
$("#sidebarToggle").on("click", function(e) {
e.preventDefault();
$("body").toggleClass("sb-sidenav-toggled");
});
})(jQuery);
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
|
! MIT License
!
! Copyright (c) 2020 SHEMAT-Suite
!
! Permission is hereby granted, free of charge, to any person obtaining a copy
! of this software and associated documentation files (the "Software"), to deal
! in the Software without restriction, including without limitation the rights
! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
! copies of the Software, and to permit persons to whom the Software is
! furnished to do so, subject to the following conditions:
!
! The above copyright notice and this permission notice shall be included in all
! copies or substantial portions of the Software.
!
! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
! SOFTWARE.
!> @brief writes data in tecplot-format
!> @param[in] otype 1: new file, 2 append
!> @param[in] ismpl local sample index
SUBROUTINE write_monitor(otype,ismpl)
use arrays
use mod_genrl
use mod_genrlc
use mod_data
use mod_time
use mod_flow
use mod_temp
use mod_conc
use mod_linfos
IMPLICIT NONE
integer :: ismpl
integer :: i, j, k, m
integer :: ib
DOUBLE PRECISION dx, dy, dz, val
! otype:
! 1 new file
! 2 append
INTEGER otype
! mm_*: outer iteration loop (file for each monitor point)
! mt_*: inner iteration loop (file for each time step)
INTEGER mm_b, mm_e, mt_b, mt_e
INTEGER i1, i2, i3, m2, lblank, lout, in1, in2
EXTERNAL lblank
! external functions
DOUBLE PRECISION vxc, vyc, vzc, kx, ky, kz, lx, ly, lz, por, &
rhof, visf
EXTERNAL vxc, vyc, vzc, kx, ky, kz, lx, ly, lz, por, rhof, &
visf
DOUBLE PRECISION qxc, qyc, qzc, bhpr
EXTERNAL qxc, qyc, qzc, bhpr
! normal or transposed, monitor point files, time step files
LOGICAL ltransposed, lmonip, ltimes
character (len=256) :: filename
character (len=65536) :: line
character (len=8) :: snumber
INTRINSIC trim
IF ( .NOT. (transient .AND. tr_switch(ismpl))) RETURN
IF ( .NOT. monitor) RETURN
IF ( .NOT. write_smonitor) THEN
IF (write_disable) RETURN
END IF
#ifdef NOMON
RETURN
#endif
snumber = '0'
IF (write_smonitor) THEN
WRITE(snumber,'(1I7)') smon_idx(ismpl)
IF (smon_idx(ismpl)>=0) THEN
WRITE(snumber,'(1I7)') smon_idx(ismpl)
ELSE IF (smon_idx(ismpl)==-1) THEN
WRITE(snumber,'(A8)') 'final'
ELSE IF (smon_idx(ismpl)==-2) THEN
WRITE(snumber,'(A8)') 'debug'
ELSE IF (smon_idx(ismpl)==-3) THEN
WRITE(snumber,'(A8)') 'ens_mean'
ELSE IF (smon_idx(ismpl)==-4) THEN
WRITE(snumber,'(A8)') 'mean'
ELSE IF (smon_idx(ismpl)==-5) THEN
WRITE(snumber,'(A8)') 'ens_mean'
END IF
END IF
CALL chln(snumber,in1,in2)
CALL omp_new_file_handler(lout,16)
! out_orientation:
! 0 normal (pv column wise), each time step has its own block (mp row wise)
! 1 transposed (pv row wise), each time step has its own block (mp column wise)
! 2 normal (pv column wise), new file for each time step (mp row wise)
! 3 transposed (pv row wise), new file for each time step (mp column wise)
! 4 normal (pv column wise), new file for each monitor point (time row wise)
IF (out_orientation==1 .OR. out_orientation==3) THEN
ltransposed = .TRUE.
ELSE
ltransposed = .FALSE.
END IF
IF (out_orientation==4) THEN
! setup outer iteration
mm_b = 1
mm_e = nmon
! inner loop makes only one step, computed later
mt_b = 0
mt_e = 0
lmonip = .TRUE.
ELSE
! outer loop makes only one dummy step
mm_b = 1
mm_e = 1
! setup inner iteration
mt_b = 1
mt_e = nmon
lmonip = .FALSE.
END IF
IF (out_orientation==2 .OR. out_orientation==3) THEN
ltimes = .TRUE.
ELSE
ltimes = .FALSE.
END IF
IF (nmon>9999 .AND. ltransposed) THEN
WRITE(*,'(1A)') &
'error: number of monitor points limited to 9999!'
STOP
END IF
CALL chln(project,i1,i2)
! steady state - file name
WRITE(filename,'(3A)') project(i1:i2),trim(project_sfx(ismpl)), '_monitor.dat'
IF (write_smonitor) WRITE(filename,'(5A)') project(i1:i2),trim(project_sfx(ismpl)), &
'_monitor_', snumber(in1:in2), '.dat'
! transient - file name
IF (ltimes) THEN
WRITE(filename,'(3A,1e15.9,1A)') project(i1:i2),trim(project_sfx(ismpl)), '_', &
(simtime(ismpl))/tunit, '_monitor.dat'
IF (write_smonitor) WRITE(filename,'(3A,1e15.9,3A)') &
project(i1:i2),trim(project_sfx(ismpl)), '_', (simtime(ismpl))/tunit, &
'_monitor_', snumber(in1:in2), '.dat'
END IF
IF (linfos(3)>=2 .AND. .NOT. lmonip) THEN
WRITE(*,'(3A)') ' [W] : Monitor points to "', &
filename(1:lblank(filename)), '"'
END IF
! ----------------------------------------------
DO m = mm_b, mm_e
IF (lmonip) THEN
! compute inner loop, one step with the right index
mt_b = m
mt_e = m
! monitor point - file name
CALL chln(project,i1,i2)
WRITE(filename,'(3A,1I6.6,1A)') project(i1:i2),trim(project_sfx(ismpl)), '_', m, &
'_monitor.dat'
IF (write_smonitor) WRITE(filename,'(3A,1I6.6,3A)') &
project(i1:i2),trim(project_sfx(ismpl)), '_', m, '_monitor_', snumber(in1:in2), &
'.dat'
IF (linfos(3)>=2) THEN
WRITE(*,'(3A)') ' [W] : Monitor points to "', &
filename(1:lblank(filename)), '"'
END IF
END IF
! Header
IF ((otype==1 .OR. ltimes) .AND. .NOT. ltransposed) THEN
WRITE(line,'(9999(1A11,1I4.4,1A2))') &
(' "conc', i, '",',i=1,ntrans)
OPEN(lout,file=filename,status='replace')
WRITE(lout,'(12A)') '% "time" "x" ', &
' "y" "z" "uindex" ', &
' "i" "j" "k"', ' "head" ', &
' "temp" ', ' "pres" ', &
line(1:ntrans*17), &
' "vx" ', ' "vy" ', &
' "vz" ', ' "bhpr"', &
' "kz" '
CLOSE(lout)
END IF
IF ((otype==1 .OR. ltimes) .AND. ltransposed) THEN
OPEN(lout,file=filename,status='replace')
WRITE(lout,'(1A)') '% "x"'
WRITE(lout,'(1A)') '% "y"'
WRITE(lout,'(1A)') '% "z"'
WRITE(lout,'(1A)') '% "uindex"'
WRITE(lout,'(1A)') '% "i"'
WRITE(lout,'(1A)') '% "j"'
WRITE(lout,'(1A)') '% "k"'
DO m2 = mt_b, mt_e
i1 = imon(m2,1)
dx = 0.5D0*delx(1)
DO i = 2, i1
dx = dx + 0.5D0*(delx(i-1)+delx(i))
END DO
WRITE(lout,'(1e14.6,1X)',advance='NO') dx
END DO
WRITE(lout,*) ' '
DO m2 = mt_b, mt_e
i2 = imon(m2,2)
dy = 0.5D0*dely(1)
DO j = 2, i2
dy = dy + 0.5D0*(dely(j-1)+dely(j))
END DO
WRITE(lout,'(1e14.6,1X)',advance='NO') dy
END DO
WRITE(lout,*) ' '
DO m2 = mt_b, mt_e
i3 = imon(m2,3)
dz = 0.5D0*delz(1)
DO k = 2, i3
dz = dz + 0.5D0*(delz(k-1)+delz(k))
END DO
WRITE(lout,'(1e14.6,1X)',advance='NO') dz
END DO
WRITE(lout,*) ' '
WRITE(lout,'(9999(I14,1X))') (uindex(imon(m2,1),imon(m2,2),imon(m2,3)),m2=mt_b,mt_e)
WRITE(lout,'(9999(I14,1X))') (imon(m2,1),m2=mt_b,mt_e)
WRITE(lout,'(9999(I14,1X))') (imon(m2,2),m2=mt_b,mt_e)
WRITE(lout,'(9999(I14,1X))') (imon(m2,3),m2=mt_b,mt_e)
WRITE(lout,'(1A)') '% "head"'
WRITE(lout,'(1A)') '% "temp"'
WRITE(lout,'(1A)') '% "pres"'
DO i = 1, ntrans
WRITE(lout,'(1A7,1I4.4,1A1)') '% "conc', i, '"'
END DO
WRITE(lout,'(1A)') '% "vx"'
WRITE(lout,'(1A)') '% "vy"'
WRITE(lout,'(1A)') '% "vz"'
CLOSE(lout)
END IF
! append data block
OPEN(lout,file=filename,status='unknown',position='append')
! Body
IF ( .NOT. ltransposed) THEN
! - normal orientation -
! separate each time steps
IF ( .NOT. ltimes .AND. .NOT. lmonip) WRITE(lout,'(A)') '%'
! - inner loop -
DO m2 = mt_b, mt_e
i3 = imon(m2,3)
i2 = imon(m2,2)
i1 = imon(m2,1)
dz = 0.5D0*delz(1)
!
val = 0.0d0
DO ib = first_flow, last_flow
i = ibc_data(ib,cbc_i)
j = ibc_data(ib,cbc_j)
k = ibc_data(ib,cbc_k)
! "neumann"?, skip otherwise
IF (ibc_data(ib,cbc_bt)==bt_neuw.AND.i==i1.AND.j==i2.AND.k==i3) THEN
IF (ibc_data(ib,cbc_bcu)>0) THEN
WRITE(*,*) 'error: well function can not be defined in a BC-unit!'
STOP
END IF
!better-recompute-all-times instead of: val = dbc_data(ib,3,ismpl)
val = bhpr(i,j,k,ismpl)
END IF
END DO
!
WRITE(lout, &
'(1e17.9,3(e14.6,1X),1I9,3I6,9999(e16.8,1X))') &
(simtime(ismpl))/tunit, delxa(i1), delya(i2), delza(i3), &
uindex(i1,i2,i3), i1, i2, i3, head(i1,i2,i3,ismpl), &
temp(i1,i2,i3,ismpl), pres(i1,i2,i3,ismpl)*pa_conv1, &
(conc(i1,i2,i3,i,ismpl),i=1, &
ntrans), vxc(i1,i2,i3,ismpl), &
vyc(i1,i2,i3,ismpl), vzc(i1,i2,i3,ismpl),val*pa_conv1, &
kz(i1,i2,i3,ismpl)
END DO
ELSE
! - transposed orientation -
! time comment
WRITE(lout,'(1A,1e17.9)') '% "time: "', (simtime(ismpl))/tunit
WRITE(lout,'(9999(e14.6,1X))') (head(imon(m2,1),imon(m2,2),imon(m2,3),ismpl),m2=mt_b,mt_e)
WRITE(lout,'(9999(e14.6,1X))') (temp(imon(m2,1),imon(m2,2),imon(m2,3),ismpl),m2=mt_b,mt_e)
WRITE(lout,'(9999(e14.6,1X))') (pres(imon(m2,1),imon(m2,2),imon(m2,3),ismpl)*pa_conv1,m2=mt_b,mt_e)
DO i = 1, ntrans
WRITE(lout,'(9999(e14.6,1X))') (conc(imon(m2,1),imon(m2,2),imon(m2,3),i,ismpl),m2=mt_b,mt_e)
END DO
WRITE(lout,'(9999(e14.6,1X))') (vxc(imon(m2,1),imon(m2,2),imon(m2,3),ismpl),m2=mt_b,mt_e)
WRITE(lout,'(9999(e14.6,1X))') (vyc(imon(m2,1),imon(m2,2),imon(m2,3),ismpl),m2=mt_b,mt_e)
WRITE(lout,'(9999(e14.6,1X))') (vzc(imon(m2,1),imon(m2,2),imon(m2,3),ismpl),m2=mt_b,mt_e)
END IF
CLOSE(lout)
END DO
! ----------------------------------------------
CALL omp_del_file_handler(lout)
RETURN
END
|
"""
Describes a hydropower unit.
Hydropower is both a purpose and a possible dam output. The optimisation process could ignore the purpose side of
hydropower, and only consider it as a possible (constant) output; but optimising this purpose needs the dedicated
penstock. As a consequence, the
"""
immutable HydropowerUnit
id::Symbol
max_discharge::Float64
max_power::Float64
efficiency::Float64
# Private constructor, without units nor defaut values.
function HydropowerUnit(id::Symbol, max_discharge::Float64, max_power::Float64, efficiency::Float64)
if efficiency < 0. || efficiency > 1.
error("Wrong efficiency: " * string(efficiency) * " not between 0.0 and 1.0")
end
new(id, max_discharge, max_power, efficiency)
end
end
# Public constructor, with units and keyword arguments.
HydropowerUnit(;id::Symbol=:hydropower,
max_discharge::Union{Discharge, Float64}=error("Missing maximum discharge"),
max_power::Union{Power, Float64}=error("Missing maximum power not specified"),
efficiency::Float64=error("Missing efficiency")
) = HydropowerUnit(id, _from_unitful(max_discharge), _from_unitful(max_power), efficiency)
HydropowerUnit(max_discharge::Union{Discharge, Float64}, max_power::Union{Power, Float64}, efficiency::Float64) =
HydropowerUnit(max_discharge=max_discharge, max_power=max_power, efficiency=efficiency)
copy(hp::HydropowerUnit; id::Symbol=hp.id,
max_discharge::Union{Discharge, Float64}=hp.max_discharge, max_power::Union{Power, Float64}=hp.max_power,
efficiency::Float64=hp.efficiency) =
# Always call the internal constructor!
Reservoir(id, _from_unitful(max_discharge), _from_unitful(max_power), efficiency)
getId(hp::HydropowerUnit) = hp.id
getPurposeId(hp::HydropowerUnit) = symbol(getId(hp), "Purpose")
getDamOutputId(hp::HydropowerUnit) = symbol(getId(hp), "DamOutput")
getMaximumDischarge(hp::HydropowerUnit) = hp.max_discharge
getMaximumPower(hp::HydropowerUnit) = hp.max_power
getEfficiency(hp::HydropowerUnit) = hp.efficiency
id(hp::HydropowerUnit) = getId(hp)
purposeId(hp::HydropowerUnit) = getPurposeId(hp)
damOutputId(hp::HydropowerUnit) = getDamOutputId(hp)
maxDischarge(hp::HydropowerUnit) = getMaximumDischarge(hp)
maxPower(hp::HydropowerUnit) = getMaximumPower(hp)
efficiency(hp::HydropowerUnit) = getEfficiency(hp)
|
require 'test_helper'
class Bookafy::Model::CompanyTest < ActiveSupport::TestCase
def test_that_new_company_is_created
company = Bookafy::Model::Company.new(name: 'Smartlist')
assert_not_equal nil, company
assert_equal 'Smartlist', company.name
end
end
|
export enum ApiStatusCodes {
SUCCESS = '0',
ERROR = '1',
WARNING = '2'
}
/** Screen section identifiers */
export enum ScreenAreaID {
CONFIRMATION = 'CONFIRMATION',
QRCODE = 'QR',
NEXT_STEPS = 'NEXT STEPS',
INTERIM = 'INTERIM',
FINAL = 'FINAL'
}
/**
* Structure for confirmation page to display messages in correct
* screen area
*/
export interface StatusMsgInterface {
msgID: string;
msgText: string;
msgType: string;
scrArea: ScreenAreaID;
appLayer: string;
}
export interface PayloadInterface {
/**
* Default application name
*/
clientName: string;
/**
* Date the JSON message was created. Date format dictated by value in DB System
* Parameter table for DATE_FORMAT (i.e. YYYYMMDD) parameter
*/
processDate: string;
/**
* Returned status code values: 0 = success, continue, 1 = error,
* do not continue, 2 = warning.
*/
statusCode: string;
/**
* Contains the list of Enhanced Message related to the process execution
*/
statusMsgs: StatusMsgInterface[] | string | string[];
}
export class ServerPayload implements PayloadInterface {
clientName: string;
processDate: string;
statusCode: string;
statusMsgs: StatusMsgInterface[] | string | string[];
constructor(payload: PayloadInterface) {
this.clientName = payload.clientName;
this.processDate = payload.processDate;
this.statusCode = payload.statusCode;
this.statusMsgs = payload.statusMsgs;
}
get success(): boolean {
return this.statusCode === ApiStatusCodes.SUCCESS;
}
get error(): boolean {
return this.statusCode === ApiStatusCodes.ERROR;
}
get warning(): boolean {
return this.statusCode === ApiStatusCodes.WARNING;
}
}
|
<?php
namespace OFFLINE\Mall\Models;
use Illuminate\Support\Collection;
use Model;
use October\Rain\Database\Traits\Encryptable;
use OFFLINE\Mall\Classes\Payments\PaymentGateway;
use Session;
class PaymentGatewaySettings extends Model
{
use Encryptable;
protected $encryptable = [];
public $implement = ['System.Behaviors.SettingsModel'];
public $settingsCode = 'offline_mall_settings';
public $settingsFields = '$/offline/mall/models/settings/fields_payment_gateways.yaml';
/**
* @var PaymentGateway
*/
protected $gateway;
/**
* @var Collection<PaymentProvider>
*/
protected $providers;
public function __construct(array $attributes = [])
{
$this->gateway = app(PaymentGateway::class);
$this->providers = collect($this->gateway->getProviders());
$this->providers->each(function ($provider) {
$this->encryptable = array_merge($this->encryptable, $provider->encryptedSettings());
});
parent::__construct($attributes);
}
/**
* Extend the setting form with input fields for each
* registered plugin.
*/
public function getFieldConfig()
{
if ($this->fieldConfig !== null) {
return $this->fieldConfig;
}
$config = parent::getFieldConfig();
$config->tabs['fields'] = [];
$this->providers->each(function ($provider) use ($config) {
$settings = $this->setDefaultTab($provider->settings(), $provider->name());
$config->tabs['fields'] = array_merge($config->tabs['fields'], $settings);
});
return $config;
}
protected function setDefaultTab(array $settings, $tab)
{
return array_map(function ($i) use ($tab) {
if ( ! isset($i['tab'])) {
$i['tab'] = $tab;
}
return $i;
}, $settings);
}
}
|
# mipstest.asm
# David_Harris@hmc.edu 9 November 2005
#
# Test the MIPS processor.
# add, sub, and, or, slt, addi, lw, sw, beq, j
# If successful, it should write the value 7 to address 84
# Updated by @vsilchuk. Added: new test insructions:
# Assembly Description Address Machine
main: addi $2, $0, 5 # initialize $2 = 5 0 20020005
addi $3, $0, 12 # initialize $3 = 12 4 2003000c
addi $7, $3, -9 # initialize $7 = 3 8 2067fff7
or $4, $7, $2 # $4 <= 3 or 5 = 7 c 00e22025
and $5, $3, $4 # $5 <= 12 and 7 = 4 10 00642824
add $5, $5, $4 # $5 = 4 + 7 = 11 14 00a42820
beq $5, $7, end # shouldnโt be taken 18 10a7000a
slt $4, $3, $4 # $4 = 12 < 7 = 0 1c 0064202a
beq $4, $0, around # should be taken 20 10800001
addi $5, $0, 0 # shouldnโt happen 24 20050000
around: slt $4, $7, $2 # $4 = 3 < 5 = 1 28 00e2202a
add $7, $4, $5 # $7 = 1 + 11 = 12 2c 00853820
sub $7, $7, $2 # $7 = 12 - 5 = 7 30 00e23822
sw $7, 68($3) # [80] = 7 34 ac670044
lw $2, 80($0) # $2 = [80] = 7 38 8c020050
j end # should be taken 3c 08000011
addi $2, $0, 1 # shouldnโt happen 40 20020001
end: sw $2, 84($0) # write adr 84 = 7 44 ac020054
addi $8, $0, 9 ## initialize $8 = 9 = 0b1001 20080009
addi $9, $0, 170 ## initialize $9 = 170 = 0xAA = 0b10101010 200900AA
xor $10, $8, $9 ## $8^$9 = 9^170 = 0b00001001 ^ 0b10101010 = 0b10100011 = 163 01095026
nor $10, $8, $9 ## ~(9 | 170) = ~(0b00001001 | 0b10101010) = ~(0b10101011) = 0b01010100 = 84 01095027
andi $11, $8, 10 ## 9 & 10 = 0b1001 & 0b1010 = 0b1000 = 8 310B000A
ori $11, $8, 10 ## 9 | 10 = 0b1001 | 0b1010 = 0b1011 = 11 350B000A
xori $11, $8, 10 ## 9 ^ 10 = 0b1001 ^ 0b1010 = 0b0011 = 3 390B000A
slti $12, $8, 20 ## 9 < 20 --> $12 = 1 290C0014
bne $12, $0, label ## 1 != 0, will branch 15800001
andi $8, $0, 228 ## shouldn't happen 300800E4
label: addi $13, $0, 2 ## $13 = 2 = 0b10 200D0002
sll $14, $13, 3 ## $14 = 2 * 2^^3 = 2 * 8 = 16 000D70C0
addi $15, $0, 21845 ## $15 = 21845 = 0b0101010101010101 = 0x5555 --> 0b00000000000000000101010101010101 200F5555
srl $16, $15, 4 ## $16 = 0b00000000000000000000010101010101 = 1365 000F8102
sra $17, $15, 4 ## $17 = 0b00000000000000000000010101010101 = 1365 000F8903
ror $18, $15, 4 ## $18 = 0b01010000000000000000010101010101 = 1342178645 000F9105
rol $19, $15, 4 ## $19 = 0b00000000000001010101010101010000 = 349520 000F9909
|
# Author : Jeonghoon.Kang (http://github.com/jeonghoonkang)
# last modification 2021.8.14
# Raspberrypi Buster release support
#sudo apt-get -y install subversion
sudo apt-get -y install htop
sudo apt-get -y install screen
sudo apt-get -y install rsync
sudo apt-get -y install vim
sudo apt-get -y install tree
sudo apt-get -y install nmap
sudo apt-get -y install unzip
sudo apt-get -y install dnsutils
sudo apt-get -y install curl
sudo apt-get -y install dcfldd pv
sudo apt-get -y install lrzsz
sudo apt-get -y install lynx
sudo apt-get -y install ntpdate
sudo apt-get -y install vim-gnome
sudo apt-get -y install dos2unix
# sudo apt-get -y install dosbox
sudo apt-get -y install wicd wicd-curses
#sudo apt-get -y install samba samba-common-bin
#sudo apt-get -y install php5 libapache2-mod-php5
#sudo apt-get -y install mysql-server php5-mysql
sudo apt-get -y install postfix
sudo apt-get -y install apache2
sudo apt-get -y install rrdtool
sudo apt-get -y install xrdp
sudo apt-get -y install sshpass
sudo apt-get -y install fcitx-hangul
sudo apt-get -y install fonts-unfonts-core
wget https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip
unzip distribute-0.7.3.zip
cd distribute-0.7.3
sudo python setup.py install
sudo easy_install pip
# apt-get -y install python3-distutils
# curl https://bootstrap.pypa.io/get-pip.py | python3
sudo pip install setuptools
sudo easy_install distribute
sudo pip2.7 install --upgrade distribute
# windows WSL ๊ฒฝ์ฐ build-essential ์ค์นํ์
# sudo apt-get install build-essential
sudo apt-get -y install python-tk
sudo apt-get -y install python-dev
# sudo apt-get -y install python-matplotlib
# sudo apt-get -y install python-mysqldb
# sudo apt-get -y install python-smbus
# sudo apt-get -y install python-requests
# sudo apt-get -y install python-twisted
sudo apt-get -y install libblas-dev liblapack-dev libatlas-base-dev gfortran
sudo pip install -U setuptools
sudo pip install openpyxl
sudo pip install requests --upgrade
sudo pip install twisted --upgrade
sudo pip install matplotlib
sudo pip install networkx
sudo pip install httplib
sudo pip install urllib3
sudo pip install utils
#sudo pip install numpy
#sudo pip install pandas
# sometimes on Mac OSX, sudo pip install tld --ignore-installed six --user
#sudo pip install tensorflow
#sudo pip install scipy
#sudo pip install scikit-learn
sudo pip install jupyter
# (for PIP)
# python -m ensurepip --default-pip
#########################################################################
#### some commands
# tasklist
# ps -W
#sudo apt-get -y install dosbox
#sudo apt-get update && sudo apt-get upgrade -y
#sudo apt-get update && sudo apt-get dist-upgrade
#sudo apt-get install apt-transport-https -y --force-yes
#sudo apt-get update && sudo apt-get install oracle-java7-jdk
#sudo apt-get -y install wicd wicd-curses
|
enum Role {
ADMIN,
TEACHER,
PARENT,
}
extension RoleExtension on Role {
int get accessLevel => [2, 1, 0][this.index];
}
|
//! Test directly invoking event handlers from within other event handlers.
//! This module tests this feature for simple state machines not requiring a
//! state context. See `handler_calls.rs` for more interesting cases.
include!(concat!(env!("OUT_DIR"), "/", "simple_handler_calls.rs"));
#[cfg(test)]
mod tests {
use super::*;
#[test]
/// Test a basic handler call.
fn simple_call() {
let mut sm = SimpleHandlerCalls::new();
sm.c();
assert_eq!(sm.state, SimpleHandlerCallsState::A);
}
#[test]
/// Test that a handler call terminates the current handler.
fn calls_terminate_handler() {
let mut sm = SimpleHandlerCalls::new();
sm.d();
assert_eq!(sm.state, SimpleHandlerCallsState::B);
sm = SimpleHandlerCalls::new();
sm.e();
assert_eq!(sm.state, SimpleHandlerCallsState::B);
}
}
|
include ::Kit::Doc::Yard::TemplatePluginHelper # rubocop:disable Style/MixinUsage
def init
return if object.docstring.blank? && !object.has_tag?(:api)
sections :index, [:docstring_tags, [:private, :deprecated, :todo, :note], :docstring, [:text]], T('tags')
end
|
module Config.Exception
( trySetIO
) where
import Log
import qualified Data.Aeson as A
import qualified Data.HashMap.Strict as HM
trySetIO :: HasCallStack => IO A.Object -> IO A.Object
trySetIO set = do
logHandle <- Log.new
result <- tryM set
case result of
Right obj -> logDebug logHandle "Success on setting object" >> return obj
Left err -> logError logHandle (show err) >> return HM.empty
|
CREATE TABLE transfer_meter ( uploaded BIGINT, downloaded BIGINT)
UPDATE files set blockchain_hash = %s WHERE hash IN ({0})
CREATE TABLE blockchain_state ( last_known_block integer)
UPDATE files SET exported_timestamp = NOW WHERE hash IN ({0})
SELECT * FROM transfer_meter);
UPDATE transfer_meter SET downloaded = downloaded WHERE month = %s
SELECT * FROM files WHERE payload IS NULL;
SELECT * FROM files WHERE hash = %s
SELECT last_known_block FROM blockchain_state;
INSERT INTO blockchain_state VALUES(0)
UPDATE files SET payload = %s WHERE hash = %s
SELECT month FROM transfer_meter));
CREATE TABLE files ( name varchar, size int, hash varchar, payload text)
UPDATE transfer_meter SET uploaded = uploaded WHERE month = %s
SELECT * FROM blockchain_state);
SELECT 1 FROM files WHERE hash = %s);
|
<?php
namespace App\Libraries\Widget;
class Toolbar
{
public static function toolbarTable(array $param)
{
return view('Widget/Toolbar', $param);
}
public static function toolbarTemplate(array $param)
{
return view('Widget/ToolbarTemplate', $param);
}
}
|
using System;
using System.Collections.Generic;
namespace SysMatur.Api.Models
{
public class Post
{
public string Title { get; set; }
public DateTimeOffset Date { get; set; }
public string Body { get; set; }
public Uri? Image { get; set; }
public string Summary { get; set; }
public Uri Anchor { get; set; }
}
}
|
## `zdesk routing attribute create`
/routing/attributes.json
### Synopsis
zdesk routing attribute create [ ... ]
### Description
https://developer.zendesk.com/rest_api/docs/core/skill_based_routing#create-attribute
|
package nl.inl.blacklab.indexers.preprocess;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import nl.inl.blacklab.exceptions.PluginException;
public class TagPluginNoop implements TagPlugin {
@Override
public boolean needsConfig() {
return false;
}
@Override
public String getId() {
return "noop";
}
@Override
public String getDisplayName() {
return "NO OP";
}
@Override
public String getDescription() {
return "Passes through data without parsing";
}
@Override
public void init(Map<String, String> config) throws PluginException {
// NO OP
}
@Override
public String getInputFormat() {
return "";
}
@Override
public String getOutputFormatIdentifier() {
return "";
}
@Override
public String getOutputFileName(String inputFileName) {
return inputFileName;
}
@Override
public void perform(Reader reader, Writer writer) throws PluginException {
try {
IOUtils.copy(reader, writer);
} catch (IOException e) {
throw new PluginException(e);
}
}
}
|
๏ปฟusing Foundation;
using XPlatformMenus.Core.ViewModels;
using XPlatformMenus.Touch.Panels;
namespace XPlatformMenus.Touch.Views
{
[Register("MainView")]
[PanelPresentation(PanelEnum.Center, PanelHintType.PopToRoot, true)]
public class MainView : BaseViewController<MainViewModel>
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
ViewModel.ShowMenu();
}
}
}
|
package com.merxury.blocker.ui.settings
import androidx.annotation.StringRes
import com.merxury.blocker.base.BasePresenter
import com.merxury.blocker.base.BaseView
import kotlinx.coroutines.Job
interface SettingsContract : BaseView<SettingsContract.SettingsPresenter> {
interface SettingsView {
fun showExportResult(isSucceed: Boolean, successfulCount: Int, failedCount: Int)
fun showImportResult(isSucceed: Boolean, successfulCount: Int, failedCount: Int)
fun showResetResult(isSucceed: Boolean)
fun showMessage(@StringRes res: Int)
fun showDialog(@StringRes title: String, @StringRes message: String, action: () -> Unit)
fun showDialog(title: String, message: String, file: String?, action: (file: String?) -> Unit)
}
interface SettingsPresenter : BasePresenter {
fun exportAllRules(): Job
fun importAllRules(): Job
fun exportAllIfwRules(): Job
fun importAllIfwRules(): Job
fun importMatRules(filePath: String?)
fun resetIFW()
}
}
|
class TrackExampleController < ApplicationController
def index
@sky_tracks = SkyTrack.all
@ground_tracks = GroundTrack.all
end
end
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\aboutPage;
use App\aboutSecondPart;
class aboutController extends Controller
{
// add new About info
function addAbout()
{
return view('admin.about.about');
}
// insert_about
function insert_about(Request $request)
{
$request->validate([
'image' => 'required|mimes:jpg,jpeg,png,JPG',
]);
//image insert
$image= $request->file('image'); //('image') is form field name
$image_name=hexdec(uniqid());
$ext=strtolower($image->getClientOriginalExtension());
$image_full_name=$image_name.'.'.$ext;
$upload_path='public/admin/image/';
$image_url=$upload_path.$image_full_name;
$success=$image->move($upload_path,$image_full_name);
//end
//whole form insert in db
$state = aboutPage::insert([
'image'=> $image_url,
'headline'=>$request-> headline,
'mtext'=>$request-> mtext,
]);
return back();
}
// manageAbout first part and second part
function manageAbout()
{
$lists = aboutPage::all();
$seccondlists = aboutSecondPart::all();
return view('admin.about.manageAbout',compact('lists','seccondlists'));
}
// insert_about_secondPart
function insert_about_secondPart(Request $request)
{
$state = aboutSecondPart::insert([
'sheadline'=>$request-> sheadline,
'text'=>$request-> text,
]);
return back();
}
// editBottomAbout
function editBottomAbout($id)
{
$seccondedits = aboutSecondPart::findOrFail($id);
return view('admin.about.editBottomAbout',compact('seccondedits'));
}
// updateBottomAbout
function updateBottomAbout(Request $request)
{
aboutSecondPart::findOrFail($request->id)->update([
'sheadline'=>$request-> sheadline,
'text'=>$request-> text,
]);
return back();
}
//hard delete deleteAbout
function deleteAbout($ab_id)
{
aboutPage::findOrFail($ab_id)->delete();
return back();
}
// deleteBottomAbout
function deleteBottomAbout($id)
{
aboutSecondPart::findOrFail($id)->delete();
return back();
}
// end
}
|
// Copyright 2016 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
dancefast.go extends the (stolen and extended) list.go
with stuff, which is considered useful and helpful, such as:
- l.DanceFast( d *Dancing )
- e.DanceFast( d *Dancing )
*/
package list
// ========================================================
// DanceFast l is where the dancing begins
func (l *List) DanceFast(d *Dancing) {
l.root.away.next.prev = l.root.away.prev
l.root.away.prev.next = l.root.away.next
l.root.away.list.len--
for y := l.root.next; y != &l.root; y = y.next {
for z := y.away.next; z != y.away; z = z.next {
if z != &l.root.list.root {
z.away.next.prev = z.away.prev
z.away.prev.next = z.away.next
z.away.list.len--
}
}
}
for x := l.root.next; x != &l.root; x = x.next {
d.OnGoal(x) // Push
for i := x.away.next; i != x.away; i = i.next {
if i != &x.away.list.root {
i.away.list.root.away.next.prev = i.away.list.root.away.prev
i.away.list.root.away.prev.next = i.away.list.root.away.next
i.away.list.root.away.list.len--
for y := i.away.list.root.next; y != &i.away.list.root; y = y.next {
for z := y.away.next; z != y.away; z = z.next {
if z != &y.away.list.root {
z.away.next.prev = z.away.prev
z.away.prev.next = z.away.next
z.away.list.len--
}
}
}
}
}
d.Dance() // Dance d is where the dancing recurs to
for i := x.away.prev; i != x.away; i = i.prev {
if i != &x.away.list.root {
for y := i.away.list.root.prev; y != &i.away.list.root; y = y.prev {
for z := y.away.prev; z != y.away; z = z.prev {
if z != &y.away.list.root {
z.away.next.prev = z.away
z.away.prev.next = z.away
z.away.list.len++
}
}
}
i.away.list.root.away.next.prev = i.away.list.root.away
i.away.list.root.away.prev.next = i.away.list.root.away
i.away.list.root.away.list.len++
}
}
d.OnFail() // Pop
}
for y := l.root.prev; y != &l.root; y = y.prev {
for z := y.away.prev; z != y.away; z = z.prev {
if z != &y.away.list.root {
z.away.next.prev = z.away
z.away.prev.next = z.away
z.away.list.len++
}
}
}
l.root.away.next.prev = l.root.away
l.root.away.prev.next = l.root.away
l.root.away.list.len++
}
// DanceFast e is where the dancing continues.
// Note: You must not call this directly - implemented only for symmetry, see interface Spot.
func (e *Element) DanceFast(d *Dancing) {
panic("You cannot call this directly - implemented only for symmetry, see interface Spot")
}
|
import React from "react";
import Headroom from "react-headroom";
import { Box, Link as RebassLink, Flex, Image } from "rebass/styled-components";
import styled from "styled-components";
import Link from "./Link";
import { useHelmetQuery } from "../queries/useHelmetQuery";
import { useSiteQuery } from "../queries/useSiteQuery";
import { SECTION } from "../utils/constants";
import { getSectionHref } from "../utils/helpers";
// TODO: Add a light/dark mode toggle
const Header = () => {
const { logo } = useHelmetQuery();
const { companyName } = useSiteQuery();
return (
<StyledHeadroom>
<Flex
flexWrap="wrap"
justifyContent="space-between"
alignItems="center"
px={3}
>
<RebassLink href={`#${getSectionHref(SECTION.home)}`} variant="empty">
<Flex justifyContent="center">
<Image
src={logo.bigIcon.src}
height={["60px", "80px"]}
width={["60px", "80px"]}
alt={`${companyName} Logo`}
p={2}
css={{ borderRadius: "20px", cursor: "pointer" }}
/>
</Flex>
</RebassLink>
<Flex mr={[0, 3, 5]}>
{(Object.keys(SECTION) as Array<keyof typeof SECTION>)
.filter((id) => id !== "home")
.map((id) => (
<Box key={id} ml={[2, 3]} fontSize={[2, 3]}>
<Link href={`#${id}`} tabIndex={0} className="navSection">
{SECTION[id]}
</Link>
</Box>
))}
</Flex>
</Flex>
</StyledHeadroom>
);
};
const StyledHeadroom = styled(Headroom)`
* {
transition: background-color 0.1s ease;
}
.headroom--pinned {
background-color: ${({ theme }) => theme.colors.darkPrimary};
}
position: absolute;
width: 100%;
color: ${({ theme }) => theme.colors.lightPrimary};
`;
export default Header;
|
package util
import org.jetbrains.kannotator.index.ClassSource
import org.objectweb.asm.ClassReader
import org.jetbrains.kannotator.declarations.*
import java.io.IOException
import java.io.InputStream
fun ClassesFromClassPath(vararg classNames: String): ClassSource = ClassesFromClassPath(classNames.toList())
fun ClassesFromClassPath(classNames: Collection<ClassName>): ClassSource
= ClassesFromClassPath(classNames.map {it.internal})
class ClassesFromClassPath(val classNames: Collection<String>) : ClassSource {
override fun forEach(body: (ClassReader) -> Unit) {
for (name in classNames) {
body(getClassReader(name))
}
}
}
fun Classes(vararg classes: Class<*>): ClassSource = Classes(classes.toList())
class Classes(val classes: Collection<Class<*>>) : ClassSource {
override fun forEach(body: (ClassReader) -> Unit) {
for (javaClass in classes) {
body(getClassReader(javaClass))
}
}
}
fun getClassReader(klass: Class<*>): ClassReader {
return getClassReader(klass.getName())
}
fun getClassReader(className: String): ClassReader {
val resourceAsStream = getClassAsStream(className)
if (resourceAsStream == null) {
throw Exception("Couldn't find resource $className")
}
val classReader = ClassReader(resourceAsStream)
resourceAsStream.close();
return classReader
}
fun getClassAsStream(className: String): InputStream? {
val appClassLoader = javaClass<ClassesFromClassPath>().getClassLoader()
if (appClassLoader == null) {
return null
}
val resourceName = className.replaceAll("\\.", "/") + ".class"
return appClassLoader.getResourceAsStream(resourceName)
}
|
//! REPL for arithmetic expressions.
use rustyline::{error::ReadlineError, Editor};
use std::io;
use arithmetic_eval::arith::OrdArithmetic;
use arithmetic_eval::Environment;
use arithmetic_typing::TypeEnvironment;
use crate::{
common::{Env, ParseAndEvalResult},
library::ReplLiteral,
};
pub fn repl<T: ReplLiteral>(
arithmetic: Box<dyn OrdArithmetic<T>>,
env: Environment<'static, T>,
type_env: Option<TypeEnvironment>,
) -> io::Result<()> {
let mut rl = Editor::<()>::new();
let mut env = Env::new(arithmetic, env, type_env);
env.print_greeting()?;
let mut snippet = String::new();
let mut prompt = ">>> ";
loop {
let line = rl.readline(prompt);
match line {
Ok(line) => {
snippet.push_str(&line);
let result = env.parse_and_eval(&snippet, true)?;
match result {
ParseAndEvalResult::Ok(_) => {
prompt = ">>> ";
snippet.clear();
rl.add_history_entry(line);
}
ParseAndEvalResult::Incomplete => {
prompt = "... ";
snippet.push('\n');
rl.add_history_entry(line);
}
ParseAndEvalResult::Errored => {
prompt = ">>> ";
snippet.clear();
}
}
}
Err(ReadlineError::Interrupted) => {
println!("Bye");
break Ok(());
}
Err(ReadlineError::Eof) => {
break Ok(());
}
Err(e) => panic!("Error reading command: {}", e),
}
}
}
|
---
title: Getting Started
tags:
- linux
- hpc
---
# Getting Started
Welcome to the Stanford Research Computing Center Documentation Portal!
We are grateful for your patience as these docs are under development.
First, you should take a look over our general pages to discuss the following:
- [Software](/docs/software/)
- [Job Managers](/docs/job-managers/)
- [Tutorials](/docs/tutorials/)
If you are looking for information about getting started using a specific
resource, please go back to [the home page](/) and select the resource of interest.
|
package info.covid.data.utils
object Const {
val statesCodes = HashMap<String, String>().apply {
put("Chandigarh", "CH")
put("Delhi", "DL")
put("Himachal Pradesh", "HP")
put("Haryana", "HR")
put("Jammu and Kashmir", "JK")
put("Andhra Pradesh", "AP")
put("Kerala", "KL")
put("Odisha", "OR")
put("Dadra and Nagar Haveli", "DN")
put("Karnataka", "KA")
put("Maharashtra", "MH")
put("Andaman and Nicobar Islands", "AN")
put("Assam", "AS")
put("Manipur", "MNL")
put("Nagaland", "NL")
put("Meghalaya", "ML")
put("Punjab", "PB")
put("Rajasthan", "RJ")
put("Uttar Pradesh", "UP")
put("Uttarakhand", "UT")
put("Jharkhand", "JH")
put("West Bengal", "WB")
put("Bihar", "BR")
put("Sikkim", "SK")
put("Chhattisgarh", "CT")
put("Madhya Pradesh", "MP")
put("Pondicherry", "PY")
put("Tamil Nadu", "TN")
put("Gujarat", "GJ")
put("Telangana", "TG")
put("Arunachal Pradesh", "AR")
put("Mizoram", "MZ")
put("Tripura", "TR")
put("Andhra Pradesh (New)", "AD")
put("Daman and Diu", "DD")
put("Goa", "GA")
put("Lakshadweep Islands", "LD")
}
const val STATE_ID = "STATE_ID"
const val STATE = "STATE"
const val TITLE = "title"
val pieChartColors = listOf<Int>(
0xFFed1869.toInt(),
0xFF29bfcd.toInt(),
0xFFf89820.toInt(),
0xFF9367ac.toInt(),
0xFF8ec73f.toInt(),
0xFF808080.toInt(),
0xFFfcd800.toInt(),
0xFFb76766.toInt(),
0xFF1a77b3.toInt(),
0xFF66403a.toInt(),
0xFFC4C4C4.toInt()
)
}
|
package com.example.service;
import com.example.dao.GestorDAO;
import com.example.model.Gestor;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class GestorService {
private final GestorDAO gestorDao;
@Autowired
public GestorService(GestorDAO gestorDao) {
this.gestorDao = gestorDao;
}
public Gestor addGestor(Gestor g) {
return gestorDao.create(g);
}
public List<Gestor> getAllGestor() {
return gestorDao.read();
}
public boolean updateGestor(Gestor g) {
return gestorDao.update(g);
}
public boolean deleteGestor(Gestor g) {
return gestorDao.delete(g);
}
public boolean deleteGestores(List<Gestor> gs) {
boolean error = false;
for (Gestor g : gs) {
if (!gestorDao.delete(g)) {
error = true;
}
}
return !error;
}
}
|
/*
* FutzGlut.cpp
*
* Created on: Nov 3, 2010
* Author: ziba
*/
#if FUTZ_PLATFORM_GLUT
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef OSX
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#ifdef _WIN32
#include <glut.h>
#else
#include <GL/glut.h>
#endif
#endif
#include "../Futz.h"
#include <stdio.h>
#include "FutzGlut.h"
void FutzGlut::Initialize(int argc, char** argv) {
glutInit(&argc, argv);
glutInitWindowSize(1024, 700);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_ALPHA);
glutCreateWindow("Futz - GLUT");
glutKeyboardFunc(FutzGlut::KeyPressFunc);
glutKeyboardUpFunc(FutzGlut::KeyUpFunc);
glutDisplayFunc(FutzGlut::RenderScene);
glutReshapeFunc(FutzGlut::Reshape);
//glutMouseFunc(MouseFunc);
glutPassiveMotionFunc(FutzGlut::PassiveMotion);
glutTimerFunc(500, FutzGlut::Timer, 1);
Futz* futz = Futz::Instance();
Futz::Instance()->camera->SetViewport(futz->platform->width, futz->platform->height);
Futz::Instance()->renderer->Initialize(futz->platform->width, futz->platform->height);
futz->gameObject->Start();
glutMainLoop();
}
void FutzGlut::Resize(int width, int height){
if (height==0)
height=1;
#ifndef OPENGLES1
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f,(GLfloat)width/(GLfloat)height,0.1f,500.0f);
glMatrixMode(GL_MODELVIEW);
#endif
}
void FutzGlut::KeyPressFunc(unsigned char key, int x, int y) {
Futz* futz = Futz::Instance();
//futz->inputEventQueue.Push(key);
futz->input.SetDown(key);
}
void FutzGlut::KeyUpFunc(unsigned char key, int x, int y) {
Futz* futz = Futz::Instance();
futz->input.SetUp(key);
}
void FutzGlut::PassiveMotion(int x, int y) {
Futz* futz = Futz::Instance();
//futz->inputEventQueue.PushMouse(x, y);
futz->input.SetMouse(x,y);
}
void FutzGlut::RenderScene(void) {
Futz* futz = Futz::Instance();
futz->Render();
futz->gameObject->RenderLoop();
glutSwapBuffers();
}
void FutzGlut::Timer(int value) {
Futz* futz = Futz::Instance();
futz->Update();
glutPostRedisplay();
glutTimerFunc(5, FutzGlut::Timer, 1);
}
void FutzGlut::Reshape(int Width, int Height) {
Futz* futz = Futz::Instance();
futz->platform->Resize(Width, Height);
}
void FutzGlut::ToggleFullscreen(){
Futz* futz = Futz::Instance();
if(!futz->platform->isFullscreen){
glutFullScreen();
} else {
glutReshapeWindow(futz->platform->width, futz->platform->height);
}
futz->platform->isFullscreen = !futz->platform->isFullscreen;
}
FutzGlut::~FutzGlut() {
// TODO Auto-generated destructor stub
}
#endif
|
<?php
header('Content-type: application/json');
echo \Alcatraz\Kernel\Layout::getContent(); ?>
|
<?php
/**
* ๅผนๅบไฟกๆฏๆ็คบๆก
* @param [type] $msg ่ฆๅจ็ฝ้กตไธๆพ็คบ็ๆ็คบไฟกๆฏ
* @param string $type success / danger
* @return void
*/
function alert($msg, $type='success'){
session()->flash($type, $msg);
}
|
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module SimpTT.Error where
import Language.SimplePi.Types (Position)
import Text.PrettyPrint.Leijen.Text
data TTError ctx e
= VariableNotFound Position e (ctx e)
| TypeExpected Position e e
| FunctionExpected Position e e
| TypeMismatch Position String e e e
deriving (Show, Functor, Foldable, Traversable)
instance (Pretty e, Pretty (ctx e)) => Pretty (TTError ctx e) where
pretty (VariableNotFound pos var ctx) =
vsep [ pretty pos <> colon <+> "Variable not found:"
, indent 2 $ align $ pretty var
, ""
, "In context:"
, indent 2 $ align $ pretty ctx
]
pretty (TypeExpected pos term typ) =
vsep [ pretty pos <> colon <+> "Type expected, but got:"
, ""
, "During type checking:"
, indent 2 $ align $ pretty term
, ""
, "Got type:"
, indent 2 $ align $ pretty typ
]
pretty (FunctionExpected pos term typ) =
vsep [ pretty pos <> colon <+> "Function expected."
, ""
, "During type checking:"
, indent 2 $ align $ pretty term
, ""
, "Got type:"
, indent 2 $ align $ pretty typ
]
pretty (TypeMismatch pos msg term expected got) =
vsep [ pretty pos <> colon <+> pretty msg
, ""
, "During type checking:"
, indent 2 $ align $ pretty term
, ""
, "Expected type:"
, indent 2 $ align $ pretty expected
, ""
, "Got type:"
, indent 2 $ align $ pretty got
]
|
import com.threatstack.docs.SourceDocsPlugin
enablePlugins(SourceDocsPlugin)
lazy val root = project.in(file("."))
.settings(version := "0.1", scalaVersion := "2.12.4")
lazy val check = TaskKey[Unit]("check")
check := {
val expected = IO.readLines(file("expect.md"))
val actual = IO.readLines(crossTarget.value / "docs"/ "test.md")
if (expected != actual) sys.error("Output doesn't match expected: \n" + actual.mkString("\n"))
}
sourceDocsSourceDirectory := (baseDirectory in Compile).value / "docs"
sourceDocsTargetDirectory := crossTarget.value / "docs"
|
const path = require("path");
const router = require("express").Router();
const storeFrontRoutes = require("./storeFront");
const userRoutes = require("./user");
const storeRoutes = require("./store");
const productRoutes = require("./product");
const cartRoutes = require("./cart");
const imageRoutes = require("./cloudinary");
router.use("/storefront", storeFrontRoutes);
router.use("/user", userRoutes);
router.use("/store", storeRoutes);
router.use("/product", productRoutes);
router.use("/cart", cartRoutes);
router.use("/image", imageRoutes);
router.use(function(req, res) {
res.sendFile(path.join(__dirname, "../../client/build/index.html"));
});
module.exports = router;
|
<?php namespace bookclub;
/*
* Class provides access to joined groups and group users tables.
*
* @author Jon Wolfe <jonnj@connectberlin.de>
* @package bookclub
* @subpackage database
* @license https://opensource.org/licenses/MIT MIT
*/
/**
* Access to the joined logs, members and users tables.
*/
class JoinLogsMembersUsers extends DatabaseTable
{
/**
* @var array of strings, local storage of column names
*/
private static $_columns = null;
/**
* Initialize the object.
* @param int $parm optional join field (defaults to param2)
* @return \bookclub\JoinGroupsGroupUsers
*/
public function __construct(int $parm = 2)
{
parent::__construct('logs');
parent::join('members',
tableField('logs', "param$parm") . ' = ' . tableField('members', 'member_id'));
parent::join('\users',
tableField('members', 'wordpress_id') . ' = ' . tableField('\users', 'ID'));
parent::join('\usermeta AS f',
tableField('members', 'wordpress_id') . " = f.user_id AND f.meta_key = 'first_name'");
parent::join('\usermeta AS l',
tableField('members', 'wordpress_id') . " = l.user_id AND l.meta_key = 'last_name'");
}
/**
* Fetch the list of column names combined from the joined tables.
* @return array of column name strings
*/
protected function getColumns(): array
{
if (is_null(self::$_columns)) {
self::$_columns = parent::addColumns();
}
return self::$_columns;
}
/**
* Start looping through records matching the selection criteria.
* @param array $selectors type key to search for and up to three additional
* selecting parameters.
* @param string $start timestamp between field if start and end specified
* @param string $end timestamp between field if start and end specified
*/
public function loopBySelectors(array $selectors,
string $start = '',string $end = ''): void
{
$values = [];
$fields = [];
if ($selectors[0]) {
$fields[] = tableField('logs', 'type') . ' = %s';
$values[] = $selectors[0];
}
if ((count($selectors) > 1) && ($selectors[1])) {
$fields[] = tableField('logs', 'param1') . ' = %s';
$values[] = $selectors[1];
}
if ((count($selectors) > 2) && ($selectors[2])) {
$fields[] = tableField('logs', 'param2') . ' = %s';
$values[] = $selectors[2];
}
if ((count($selectors) > 3) && ($selectors[3])) {
$fields[] = tableField('logs', 'param3') . ' = %s';
$values[] = $selectors[3];
}
if ($start && $end) {
$fields[] = tableField('logs', 'timestamp') . ' BETWEEN %s AND %s';
$values[] = $start;
$values[] = $end;
}
$this->select('',
'IF(ISNULL(' . tableField('\users', 'ID') . '),' .
tableField('members', 'name') . ', ' .
"CONCAT(f.meta_value, ' ', l.meta_value)) AS fullname");
$this->where($fields);
$this->orderBy('timestamp');
$this->prepare($values);
$this->iterate();
}
}
|
import Storage from './Storage'
const session = new Storage(window.sessionStorage)
export default session
export const {
getItem: loadFromSessionStorage,
setItem: saveToSessionStorage,
removeItem: removeFromSessionStorage,
} = session
|
if [[ "$TRAVIS_JOB_TO_DO" == "RUNTESTS" ]]
then
./ci/travis/runtests.sh
else
./ci/travis/snapshots.sh
fi
|
<?php
/**
* Auto generated from KeyValueStorage.proto
*
* Diadoc.Api.Proto.KeyValueStorage package
*/
namespace Diadoc\Api\Proto\KeyValueStorage {
/**
* KeyValueStorageApiGetResponse message
*/
class KeyValueStorageApiGetResponse extends \ProtobufMessage
{
/* Field index constants */
const ENTRIES = 1;
/* @var array Field descriptors */
protected static $fields = array(
self::ENTRIES => array(
'name' => 'Entries',
'repeated' => true,
'type' => '\Diadoc\Api\Proto\KeyValueStorage\KeyValueStorageEntry'
),
);
/**
* Constructs new message container and clears its internal state
*/
public function __construct()
{
$this->reset();
}
/**
* Clears message values and sets default ones
*
* @return null
*/
public function reset()
{
$this->values[self::ENTRIES] = array();
}
/**
* Returns field descriptors
*
* @return array
*/
public function fields()
{
return self::$fields;
}
/**
* Appends value to 'Entries' list
*
* @param \Diadoc\Api\Proto\KeyValueStorage\KeyValueStorageEntry $value Value to append
*
* @return null
*/
public function appendEntries(\Diadoc\Api\Proto\KeyValueStorage\KeyValueStorageEntry $value)
{
return $this->append(self::ENTRIES, $value);
}
/**
* Clears 'Entries' list
*
* @return null
*/
public function clearEntries()
{
return $this->clear(self::ENTRIES);
}
/**
* Returns 'Entries' list
*
* @return \Diadoc\Api\Proto\KeyValueStorage\KeyValueStorageEntry[]
*/
public function getEntries()
{
return $this->get(self::ENTRIES);
}
/**
* Returns 'Entries' iterator
*
* @return \ArrayIterator
*/
public function getEntriesIterator()
{
return new \ArrayIterator($this->get(self::ENTRIES));
}
/**
* Returns element from 'Entries' list at given offset
*
* @param int $offset Position in list
*
* @return \Diadoc\Api\Proto\KeyValueStorage\KeyValueStorageEntry
*/
public function getEntriesAt($offset)
{
return $this->get(self::ENTRIES, $offset);
}
/**
* Returns count of 'Entries' list
*
* @return int
*/
public function getEntriesCount()
{
return $this->count(self::ENTRIES);
}
}
}
|
import os
import json
import random
import numpy as np
import tensorflow as tf
import src.core.constants as constants
import src.retina_net.anchor_generator.box_utils as box_utils
import src.retina_net.datasets.dataset_utils as dataset_utils
from src.core.abstract_classes.dataset_handler import DatasetHandler
from src.retina_net.anchor_generator.fpn_anchor_generator import FpnAnchorGenerator
class BddDatasetHandler(DatasetHandler):
def __init__(self, config, train_val_test):
"""
Initializes directories, and loads the sample list
:param config: configuration dictionary
:param train_val_test (string): 'train', 'val', or 'test'
"""
super().__init__(config)
# Define Dicts
self._MEANS_DICT = constants.MEANS_DICT
# Load configs
self.anchor_gen_config = config['anchor_generator']
self.training_data_config = config['bdd']['training_data_config']
# Define paths to dataset
paths_config = config['bdd']['paths_config']
self.dataset_dir = os.path.expanduser(paths_config['dataset_dir'])
data_set_size = paths_config['100k_or_10k']
if train_val_test == 'train':
self.data_split_dir = train_val_test
self.label_file_name = 'train.json'
self.frac_training_data = self.training_data_config['frac_training_data']
else:
self.data_split_dir = 'val'
self.label_file_name = 'val.json'
self.frac_training_data = 1.0
self.im_dir = os.path.join(
self.dataset_dir, 'images', data_set_size, self.data_split_dir)
self.gt_label_dir = os.path.join(
self.dataset_dir, 'labels')
# Make sure dataset directories exist
dataset_utils.check_data_dirs([self.im_dir, self.gt_label_dir])
# Get sample ids
self._load_sample_ids()
self.epoch_size = len(self.sample_ids)
self.labels = json.load(open(os.path.join(
self.gt_label_dir, self.label_file_name), 'r'))
# Create placeholder for dataset
self.dataset = None
# Create flag if train\val or just inference
self.is_testing = (train_val_test == 'test')
def _load_sample_ids(self):
"""
loads sample ids to read dataset
"""
sample_ids = os.listdir(self.im_dir)
# Random shuffle here is much more computationally efficient than randomly shuffling a dataset iterator.
if self.frac_training_data != 1.0 and self.data_split_dir == 'train':
percent_samples = int(len(sample_ids) * self.frac_training_data)
inds = np.random.choice(
len(sample_ids), percent_samples, replace=False)
self.sample_ids = [sample_ids[ind] for ind in inds]
elif self.data_split_dir == 'train':
random.shuffle(sample_ids)
self.sample_ids = sample_ids
else:
self.sample_ids = sample_ids
# Create a list of image paths from sample ids
self.im_paths = [
self.im_dir +
'/' +
sample for sample in self.sample_ids]
def set_sample_id(self, sample_index):
self.im_paths = [self.im_paths[sample_index]]
self.sample_ids = [self.sample_ids[sample_index]]
def create_dataset(self):
"""
Create dataset using tf.dataset API
:return: dataset : dataset object
"""
# Set data path lists
im_paths = self.im_paths
sample_ids = self.sample_ids
# Create dataset using API
dataset = tf.data.Dataset.from_tensor_slices((im_paths, sample_ids))
# Create sample dictionary
self.dataset = dataset.map(
self.create_sample_dict,
num_parallel_calls=10)
return self.dataset
def create_sample_dict(
self,
im_path,
sample_id):
"""
Creates sample dictionary for a single sample
:param im_path: left image path
:param sample_id: ground truth sample id
:return: sample_dict: Sample dictionary filled with input tensors
"""
with tf.name_scope('input_data'):
# Read image
image_as_string = tf.io.read_file(im_path)
image = tf.image.decode_jpeg(image_as_string, channels=3)
image = tf.cast(image, tf.float32)
image_norm = dataset_utils.mean_image_subtraction(
image, self._MEANS_DICT[self.im_normalization])
# Flip channels to BGR since pretrained weights use this
# configuration.
channels = tf.unstack(image_norm, axis=-1)
image_norm = tf.stack(
[channels[2], channels[1], channels[0]], axis=-1)
boxes_class_gt, boxes_2d_gt, no_gt = tf.py_function(
self._read_labels, [sample_id], [
tf.float32, tf.float32, tf.bool])
# Create_sample_dict
sample_dict = dict()
sample_dict.update({constants.IMAGE_NORMALIZED_KEY: image_norm})
sample_dict.update(
{constants.ORIGINAL_IM_SIZE_KEY: tf.shape(image)})
# Create prior anchors and anchor targets
generator = FpnAnchorGenerator(self.anchor_gen_config)
boxes_2d_gt_vuhw = box_utils.vuvu_to_vuhw(boxes_2d_gt)
anchors_list = []
anchors_class_target_list = []
anchors_box_target_list = []
anchors_positive_mask_list = []
anchors_negative_mask_list = []
for layer_number in self.anchor_gen_config['layers']:
anchors = generator.generate_anchors(
tf.shape(image_norm), layer_number)
anchors_list.append(anchors)
if not self.is_testing:
anchor_corners = box_utils.vuhw_to_vuvu(anchors)
ious = box_utils.bbox_iou_vuvu(anchor_corners, boxes_2d_gt)
positive_anchor_mask, negative_anchor_mask, max_ious = generator.positive_negative_batching(
ious, self.anchor_gen_config['min_positive_iou'],
self.anchor_gen_config['max_negative_iou'])
anchors_positive_mask_list.append(positive_anchor_mask)
anchors_negative_mask_list.append(negative_anchor_mask)
anchor_box_targets, anchor_class_targets = generator.generate_anchor_targets(
anchors, boxes_2d_gt_vuhw, boxes_class_gt, max_ious,
positive_anchor_mask)
anchors_box_target_list.append(anchor_box_targets)
anchors_class_target_list.append(anchor_class_targets)
# Sample dict is stacked from p3 --> p7, this is essential to
# memorize for stacking the predictions later on
sample_dict.update(
{constants.ANCHORS_KEY: tf.concat(anchors_list, axis=0)})
if not self.is_testing:
sample_dict.update({constants.ANCHORS_BOX_TARGETS_KEY: tf.concat(
anchors_box_target_list, axis=0),
constants.ANCHORS_CLASS_TARGETS_KEY: tf.concat(
anchors_class_target_list, axis=0),
constants.POSITIVE_ANCHORS_MASK_KEY: tf.concat(
anchors_positive_mask_list, axis=0),
constants.NEGATIVE_ANCHOR_MASK_KEY: tf.concat(
anchors_negative_mask_list, axis=0)})
return sample_dict
def _read_labels(self, sample_id):
"""
Reads ground truth labels and parses them into one hot class representation and groundtruth 2D bounding box.
"""
sample_id = sample_id.numpy()
# Extract the list
no_gt = False
categories = self.training_data_config['categories']
boxes_class_gt = []
sample_id = sample_id.decode("utf-8")
frame_labels = [label for label in self.labels if
label['name'] == sample_id and label[
'category'] in categories]
boxes_2d_gt = np.array([[label['bbox'][1],
label['bbox'][0],
label['bbox'][3],
label['bbox'][2]] for label in frame_labels])
categories_gt = [label['category'] for label in frame_labels]
if boxes_2d_gt.size == 0:
cat_one_hot = [0 for e in range(len(categories) + 1)]
boxes_2d_gt = np.array([0.0, 0.0, 1.0, 1.0])
boxes_class_gt.append(cat_one_hot)
no_gt = True
else:
for elem in categories_gt:
cat_one_hot = [0 for e in range(len(categories) + 1)]
cat_idx = categories.index(elem.lower())
cat_one_hot[cat_idx] = 1
boxes_class_gt.append(cat_one_hot)
# one-hot representation dependent on config file
if len(boxes_2d_gt.shape) == 1:
boxes_2d_gt = np.expand_dims(boxes_2d_gt, axis=0)
return [np.array(boxes_class_gt).astype(np.float32),
np.array(boxes_2d_gt).astype(np.float32),
no_gt]
|
<?php
/**
* This file is part of Berlioz framework.
*
* @license https://opensource.org/licenses/MIT MIT License
* @copyright 2020 Ronan GIRON
* @author Ronan GIRON <https://github.com/ElGigi>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code, to the root.
*/
declare(strict_types=1);
namespace Berlioz\CliCore\Command\Berlioz;
use Berlioz\CliCore\Command\AbstractCommand;
use Berlioz\CliCore\Exception\CommandException;
use Berlioz\Core\Core;
use Berlioz\Core\CoreAwareInterface;
use Berlioz\Core\CoreAwareTrait;
use Berlioz\Core\Exception\BerliozException;
use GetOpt\GetOpt;
/**
* Class CacheClearCommand.
*
* @package Berlioz\CliCore\Command\Berlioz
*/
class CacheClearCommand extends AbstractCommand implements CoreAwareInterface
{
use CoreAwareTrait;
/**
* CacheClearCommand constructor.
*
* @param Core $core
*/
public function __construct(Core $core)
{
$this->setCore($core);
}
/**
* @inheritdoc
*/
public static function getShortDescription(): ?string
{
return 'Clear cache of Berlioz Framework';
}
/**
* @inheritdoc
* @throws BerliozException
* @throws CommandException
*/
public function run(GetOpt $getOpt): int
{
if (empty($cacheManager = $this->getCore()->getCacheManager())) {
throw new CommandException('Missing cache service');
}
print "Cache clear of Berlioz...";
$result = $cacheManager->clear();
print sprintf(' %s!', $result ? 'done' : 'failed') . PHP_EOL;
return (int)!$result;
}
}
|
##############################################################################################
# UpdateGlobalConfigurationFromXmlSecrets.ps1
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache License.
# Operations :
#
<#
.SYNOPSIS
Update GlobalConfigurations.xml
.PARAMETER
<Parameters>
.INPUTS
.NOTES
!!!Deprecate this file!!!
.EXAMPLE
#>
###############################################################################################
param(
[parameter(Mandatory=$true)]
[string]$XmlSecretsFilePath
)
$ErrorActionPreference = "Stop"
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$rootPath = Split-Path -Parent $scriptPath
Get-ChildItem (Join-Path $rootPath "Libraries") -Recurse | `
Where-Object { $_.FullName.EndsWith(".psm1") } | `
ForEach-Object { Import-Module $_.FullName -Force -Global -DisableNameChecking }
$XmlSecrets = [xml](Get-Content $XmlSecretsFilePath)
$GlobalConfigurationXMLFilePath = Resolve-Path ".\XML\GlobalConfigurations.xml"
$GlobalXML = [xml](Get-Content $GlobalConfigurationXMLFilePath )
$GlobalXML.Global.Azure.Subscription.SubscriptionID = $XmlSecrets.secrets.SubscriptionID
$GlobalXML.Global.Azure.TestCredentials.LinuxUsername = $XmlSecrets.secrets.linuxTestUsername
$GlobalXML.Global.Azure.TestCredentials.LinuxPassword = $XmlSecrets.secrets.linuxTestPassword
$GlobalXML.Global.Azure.TestCredentials.sshPrivateKey = $XmlSecrets.secrets.sshPrivateKey.InnerText
$GlobalXML.Global.Azure.ResultsDatabase.server = $XmlSecrets.secrets.DatabaseServer
$GlobalXML.Global.Azure.ResultsDatabase.user = $XmlSecrets.secrets.DatabaseUser
$GlobalXML.Global.Azure.ResultsDatabase.password = $XmlSecrets.secrets.DatabasePassword
$GlobalXML.Global.Azure.ResultsDatabase.dbname = $XmlSecrets.secrets.DatabaseName
$GlobalXML.Global.HyperV.TestCredentials.LinuxUsername = $XmlSecrets.secrets.linuxTestUsername
$GlobalXML.Global.HyperV.TestCredentials.LinuxPassword = $XmlSecrets.secrets.linuxTestPassword
$GlobalXML.Global.HyperV.ResultsDatabase.server = $XmlSecrets.secrets.DatabaseServer
$GlobalXML.Global.HyperV.ResultsDatabase.user = $XmlSecrets.secrets.DatabaseUser
$GlobalXML.Global.HyperV.ResultsDatabase.password = $XmlSecrets.secrets.DatabasePassword
$GlobalXML.Global.HyperV.ResultsDatabase.dbname = $XmlSecrets.secrets.DatabaseName
$GlobalXML.Save($GlobalConfigurationXMLFilePath )
Write-LogInfo "Updated GlobalConfigurations.xml"
|
# SoulmangaAdmin
Soul Manga Admin
# Docker
- ๆๅปบ้ๅ
```
docker build -t soulmangaadmin .
```
- ่ฟ่กๅฎนๅจ
```
# simply run the container instance & bind the port
docker run --name vapor-server -p 8080:8080 soulmangaadmin
# run the instance, bind the port, see logs remove after exit (CTRL+C)
docker run --rm -p 8080:8080 -it soulmangaadmin
# volumes
docker run --rm --name vapor-server \
--volume "$(pwd):/src" \
--workdir "/src" \
-p 8080:8080 \
soulmangaadmin
```
- ๆต่ฏๅฎนๅจ
```
docker run --rm --name vapor-server \
--volume "$(pwd):/src" \
--workdir "/src" \
-p 8080:8080 \
-it \
vapor/swift:5.2
```
|
import ViewerContext from 'common/components/ViewerContext';
import gql from 'graphql-tag';
import React, { useContext } from 'react';
import { Mutation } from 'react-apollo';
import { Logout as LogoutData } from './__generated__/Logout';
import LogoutLogic from './LogoutLogic';
const LOGOUT = gql`
mutation Logout {
logout
}
`;
const Logout: React.FunctionComponent = () => {
const { clearViewer } = useContext(ViewerContext);
return (
<Mutation<LogoutData> mutation={LOGOUT}>
{logout => <LogoutLogic logout={logout} clearViewer={clearViewer} />}
</Mutation>
);
};
export default Logout;
|
//
// Created by Andrey Tabakov on 08/10/2018.
//
#include "Stack.h"
Stack::~Stack() = default;
|
๏ปฟusing System;
namespace Akiba.Core.Exceptions
{
[Serializable]
class BootstrapException : Exception
{
private string BootstrapError;
public override string Message
{
get
{
return BootstrapError;
}
}
public BootstrapException(string message)
{
this.BootstrapError = message;
}
}
}
|
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
/**
*
*/
interface IAxesActorInitialValues {}
export interface vtkAxesActor extends vtkActor {
/**
*
*/
getConfig(): object;
/**
*
*/
getXAxisColor(): number[];
/**
*
*/
getXAxisColorByReference(): number[];
/**
*
*/
getYAxisColor(): number[];
/**
*
*/
getYAxisColorByReference(): number[];
/**
*
*/
getZAxisColor(): number[];
/**
*
*/
getZAxisColorByReference(): number[];
/**
*
* @param config
*/
setConfig(config: object): boolean;
/**
*
* @param r
* @param g
* @param b
*/
setXAxisColor(r: number, g: number, b: number): boolean;
/**
*
* @param XAxisColor
*/
setXAxisColorFrom(XAxisColor: number[]): boolean;
/**
*
* @param r
* @param g
* @param b
*/
setYAxisColor(r: number, g: number, b: number): boolean;
/**
*
* @param YAxisColor
*/
setYAxisColorFrom(YAxisColor: number[]): boolean;
/**
*
* @param r
* @param g
* @param b
*/
setZAxisColor(r: number, g: number, b: number): boolean;
/**
*
* @param ZAxisColor
*/
setZAxisColorFrom(ZAxisColor: number[]): boolean;
/**
*
*/
update(): void;
}
/**
* Method use to decorate a given object (publicAPI+model) with vtkAxesActor characteristics.
*
* @param publicAPI object on which methods will be bounds (public)
* @param model object on which data structure will be bounds (protected)
* @param initialValues (default: {})
*/
export function extend(publicAPI: object, model: object, initialValues?: IAxesActorInitialValues): void;
/**
* Method use to create a new instance of vtkAxesActor.
* @param initialValues for pre-setting some of its content
*/
export function newInstance(initialValues?: IAxesActorInitialValues): vtkAxesActor;
/**
* vtkAxesActor is a hybrid 2D/3D actor used to represent 3D axes in a scene.
* The user can define the geometry to use for the shaft or the tip,
* and the user can set the text for the three axes. The text will appear
* to follow the camera since it is implemented by means of vtkCaptionActor2D.
* All of the functionality of the underlying vtkCaptionActor2D objects are accessible so that,
* for instance, the font attributes of the axes text can be manipulated through vtkTextProperty.
* Since this class inherits from vtkProp3D, one can apply a user transform to the underlying
* geometry and the positioning of the labels. For example, a rotation transform could be used to
* generate a left-handed axes representation.
* @see vtkAnnotatedCubeActor
* @see vtkOrientationMarkerWidget
* @see vtkCaptionActor2D
* @see vtkTextProperty
*
*/
export declare const vtkAxesActor: {
newInstance: typeof newInstance,
extend: typeof extend,
};
export default vtkAxesActor;
|
////////////////////////////////////////////////////////////////////////////////////////////////////
// NoesisGUI - http://www.noesisengine.com
// Copyright (c) 2013 Noesis Technologies S.L. All Rights Reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef __GUI_TABITEM_H__
#define __GUI_TABITEM_H__
#include <NsCore/Noesis.h>
#include <NsGui/HeaderedContentControl.h>
#include <NsGui/Enums.h>
namespace Noesis
{
class TabControl;
////////////////////////////////////////////////////////////////////////////////////////////////////
/// Represents a selectable item inside a TabControl.
///
/// http://msdn.microsoft.com/en-us/library/system.windows.controls.tabitem.aspx
////////////////////////////////////////////////////////////////////////////////////////////////////
class NS_GUI_CORE_API TabItem: public HeaderedContentControl
{
public:
TabItem();
/// Gets or sets a value that indicates whether the TabItem is selected
//@{
bool GetIsSelected() const;
void SetIsSelected(bool isSelected);
//@}
/// Gets the tab strip placement
Dock GetTabStripPlacement() const;
// Used by TabControl to force focus on the Tab
// Returns true if focus was set in the tab or in the content of the tab
bool SetFocus();
public:
/// Dependency properties
//@{
static const DependencyProperty* IsSelectedProperty;
static const DependencyProperty* TabStripPlacementProperty;
//@}
protected:
/// Called to indicate that the IsSelected property has changed to true
virtual void OnSelected(const RoutedEventArgs& args);
/// Called to indicate that the IsSelected property has changed to false
virtual void OnUnselected(const RoutedEventArgs& args);
/// From DependencyObject
//@{
bool OnPropertyChanged(const DependencyPropertyChangedEventArgs& args) override;
//@}
/// From UIElement
//@{
void OnKeyDown(const KeyEventArgs& e) override;
void OnPreviewGotKeyboardFocus(const KeyboardFocusChangedEventArgs& e) override;
void OnMouseLeftButtonDown(const MouseButtonEventArgs& e) override;
//@}
/// From Control
//@{
void UpdateVisualStates() override;
//@}
private:
TabControl* GetParentTabControl() const;
NS_DECLARE_REFLECTION(TabItem, HeaderedContentControl)
};
}
#endif
|
"use strict";
const config = require('./config'),
CoinbaseClient = require('coinbase').Client,
Transaction = require('coinbase').Transaction
;
const client = new CoinbaseClient({'apiKey': config.api_key, 'apiSecret': config.api_secret});
// Helper function to display error message and then quit the program.
const processError = function(scope, err) {
if (err != null) {
console.log(scope + ': ' + err);
process.exit(1);
}
}
// Find if received a transaction in 24 hours.
// If yes, the amount * percentage should be sent to my friend.
const processTransactions = function(txnList) {
if (txnList.length != 0) {
if ( !(txnList instanceof Array) && !(txnList[0] instanceof Transaction) ) {
throw "An array of type 'Transaction' is expected.";
}
var applicableAmountList = [];
const currentDate = new Date();
txnList.forEach(function(txn, index) {
const updatedDate = new Date(txn.updated_at);
const diffHours = (currentDate - updatedDate) / (1000 * 60 * 60);
if (diffHours < 24 && txn.status === 'completed' && txn.type === 'send') {
applicableAmountList.push(txn.amount);
// console.log(txn);
}
});
if (applicableAmountList.length == 0) {
console.log('No applicable transactions in the wallet. Program exits...');
return -1;
} else {
var totalAmount = 0;
applicableAmountList.forEach(function(amountObj, index) {
totalAmount += parseFloat(amountObj.amount);
});
return totalAmount * percentage;
}
} else {
console.log('No transactions in the wallet. Program exits...');
return -1;
}
}
// Percentage designates how much should be sent to my friend on a regular basis.
var percentage;
try {
percentage = parseFloat(config.percentage);
} catch(e) {
processError('Parsing percentage value', e);
}
client.getCurrentUser(function(err, user) {
processError('Get Current User', err);
console.log('Logged in as ' + user.name);
console.log('================================================');
// Get all transactions under a specific address.
client.getAccount(config.account_id, function(err, account) {
processError('Get Account', err);
// Loop through all addresses returned by Coinbase API to find the address ID (UUID)
// which is used to look up transactions sent to that address.
account.getAddresses(null, function(err, addr) {
processError('Get All Addresses', err);
// console.log("All addresses for account " + account.name + ": " + addr);
var ethermine_addr_id = '';
addr.forEach(function(val, index) {
if (ethermine_addr_id == '' && val.address === config.ethermine_addr) {
ethermine_addr_id = val.id;
}
})
if (ethermine_addr_id == '') {
processError('The given ETH address is not found in Coinbase. ');
}
account.getAddress(ethermine_addr_id, function(err, addr) {
processError('Get Address', err);
addr.getTransactions(null, function(err, txnList) {
processError('Get Transactions', err);
var amount = processTransactions(txnList);
if (amount > 0) {
const opts = {
'to': config.to_address,
'amount': amount.toFixed(8), // Coinbase only accept 8 decimal places amount
'currency': 'ETH'
};
console.log('Sending to ' + opts.to + ' with ' + opts.currency + ' ' + opts.amount +
' (' + (percentage * 100).toFixed(1) + '%) ...');
account.sendMoney(opts, function(err, txn) {
processError('Create Send Money Transaction', err);
console.log('\n\nTransaction created: \n' + txn);
});
}
});
});
});
});
});
|
import os
import sys
import json
import subprocess
from collections import OrderedDict
import pytest
import hurry
@pytest.fixture()
def create_hurry_json(tmpdir):
path_to_file = tmpdir.join('hurry.json')
os.chdir(os.path.dirname(path_to_file))
def creator(dictionary):
with open(path_to_file, "w+") as hurry_json:
json.dump(dictionary, hurry_json)
return creator
def test_generate_exec_str():
conf = {
'one': 'one command',
'two words': 'two words command',
'start <name>': 'docker run <name>',
'end <arg1> <arg2>': 'arg1=<arg1> arg2=<arg2>',
}
sys.argv = ['hurry', 'one']
assert hurry.generate_exec_str(conf) == 'one command'
sys.argv = ['hurry', 'two', 'words']
assert hurry.generate_exec_str(conf) == 'two words command'
sys.argv = ['hurry', 'start', 'service']
assert hurry.generate_exec_str(conf) == 'docker run service'
sys.argv = ['hurry', 'end', 'test', 'prod']
assert hurry.generate_exec_str(conf) == 'arg1=test arg2=prod'
sys.argv = ['hurry', 'one', '--', 'dynamic', 'arg']
assert hurry.generate_exec_str(conf) == 'one command dynamic arg'
sys.argv = ['hurry', 'one', 'unknown']
assert hurry.generate_exec_str(conf) is None
def test_run_hurry_e2e(create_hurry_json, tmpdir):
create_hurry_json({
'write <file_path>': 'echo "this is e2e test" > <file_path>',
'read <file_path>': 'cat <file_path>',
})
test_file = tmpdir.join("test.txt")
stdout = execute('hurry write ' + str(test_file))
assert stdout.decode().strip() == 'Execute: echo "this is e2e test" > ' + str(test_file)
assert test_file.read().strip() == 'this is e2e test'
stdout = execute('hurry read some/path')
assert stdout.decode().strip() == 'Execute: cat some/path'
stdout = execute('hurry unknown')
help_msg = 'Usage:\n hurry write <file_path>\n hurry read <file_path>'
assert stdout.decode().strip() == help_msg
stdout = execute('hurry read file -- hello')
assert stdout.decode().strip() == 'Execute: cat file hello'
def execute(command):
src = os.path.abspath(os.path.dirname(__file__))
return subprocess.check_output("PYTHONPATH={src} python {src}/bin/{cmd}".format(src=src, cmd=command), shell=True)
def test_run_hurry_without_hurry_json(capsys, tmpdir):
os.chdir(tmpdir)
hurry.main()
stdout, _stderr = capsys.readouterr()
assert stdout.strip() == "Can't find hurry.json in the current folder"
@pytest.mark.parametrize("content", ("\"-p wow! first with dash!\"", "\"first without dash\""))
def test_run_hurry_with_many_args(create_hurry_json, tmpdir, content):
create_hurry_json({"write <file_path> <content>": "echo \"<content>\" > <file_path>"})
test_file = tmpdir.join("test.txt")
sys.argv[1:] = ["write", str(test_file), content]
hurry.main()
assert test_file.read().strip() == content.strip("\"")
|
CREATE OR REPLACE FUNCTION geocode_location(
parsed NORM_ADDY
) RETURNS REFCURSOR
AS $_$
DECLARE
result REFCURSOR;
tempString VARCHAR;
tempInt INTEGER;
BEGIN
-- Try to match the city/state to a zipcode first
SELECT INTO tempInt count(*)
FROM zip_lookup_base zip
JOIN state_lookup sl ON (zip.state = sl.name)
JOIN zt99_d00 zl ON (zip.zip = zl.zcta::integer)
WHERE soundex(zip.city) = soundex(parsed.location) and sl.abbrev = parsed.stateAbbrev;
-- If that worked, just use the zipcode lookup
IF tempInt > 0 THEN
OPEN result FOR
SELECT
NULL::varchar(2) as fedirp,
NULL::varchar(30) as fename,
NULL::varchar(4) as fetype,
NULL::varchar(2) as fedirs,
coalesce(zip.city) as place,
sl.abbrev as state,
parsed.zip as zip,
centroid(wkb_geometry) as address_geom,
100::integer + levenshtein_ignore_case(coalesce(zip.city), parsed.location) as rating
FROM
zip_lookup_base zip
JOIN state_lookup sl on (zip.state = sl.name)
JOIN zt99_d00 zl ON (zip.zip = zl.zcta::integer)
WHERE
soundex(zip.city) = soundex(parsed.location) and sl.abbrev = parsed.stateAbbrev;
RETURN result;
END IF;
-- Try to match the city/state to a place next
SELECT INTO tempInt count(*)
FROM pl99_d00 pl
JOIN state_lookup sl ON (pl.state::integer = sl.st_code)
WHERE soundex(pl.name) = soundex(parsed.location) and sl.abbrev = parsed.stateAbbrev;
-- If that worked then use it
IF tempInt > 0 THEN
OPEN result FOR
SELECT
NULL::varchar(2) as fedirp,
NULL::varchar(30) as fename,
NULL::varchar(4) as fetype,
NULL::varchar(2) as fedirs,
pl.name as place,
sl.abbrev as state,
NULL::integer as zip,
centroid(wkb_geometry) as address_geom,
100::integer + levenshtein_ignore_case(coalesce(zip.city), parsed.location) as rating
FROM pl99_d00 pl
JOIN state_lookup sl ON (pl.state::integer = sl.st_code)
WHERE soundex(pl.name) = soundex(parsed.location) and sl.abbrev = parsed.stateAbbrev;
RETURN result;
END IF;
RETURN result;
END;
$_$ LANGUAGE plpgsql;
|
package com.example.grpc_coffee
import io.grpc.*
import io.grpc.stub.ClientCalls
import io.grpc.stub.StreamObserver
import kotlinx.coroutines.Job
import kotlinx.coroutines.runBlocking
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit.SECONDS
private class CoffeeDrinker(private val channel: ManagedChannel) {
private val blockingStub = CoffeeMachineGrpc.newBlockingStub(channel)
private val nonBlockingStub = CoffeeMachineGrpc.newStub(channel)
fun ping() {
println("Pinging coffee machine nowโฆ")
val pingResponse = blockingStub.ping(PingRequest.getDefaultInstance())
println("Coffee machine is alive=${pingResponse.alive} and replied with: '${pingResponse.message}'")
}
fun giveMeMy(product: Product) {
println("Asking coffee machine to make me ${product.name.toLowerCase()}โฆ")
val request = ProduceProductRequest.newBuilder().setProduct(product).build()
val response = blockingStub.getProduct(request)
println("Coffee machine made me ${response.product.name.toLowerCase()} :-)")
}
fun printOnlyCappuccinosFromHistory() {
runBlocking {
println("Getting only cappuccinosโฆ")
val job = Job()
val start = Instant.now()
val responseObserver = object : StreamObserver<GetHistoryResponse> {
var cappuccinos = 0
override fun onNext(value: GetHistoryResponse) {
if (value.product == Product.CAPPUCCINO) {
cappuccinos++
println("Got $cappuccinos cappuccinos so far :-)")
}
}
override fun onError(throwable: Throwable) {
println("error $throwable")
job.cancel()
}
override fun onCompleted() {
val duration = ChronoUnit.SECONDS.between(start, Instant.now())
println("Getting history took $duration seconds")
job.cancel()
}
}
nonBlockingStub.getHistory(GetHistoryRequest.getDefaultInstance(), responseObserver)
job.join()
}
}
fun printStatusUpdates(name: String, numUpdates: Int = 5) {
runBlocking {
println("Getting some status updatesโฆ")
val job = Job()
val call = channel.newCall(CoffeeMachineGrpc.getGetStatusUpdatesMethod(), CallOptions.DEFAULT)
val responseObserver = object : StreamObserver<GetStatusUpdatesResponse> {
private var counter = 0
override fun onNext(value: GetStatusUpdatesResponse) {
println("Got status update: ${value.message}")
counter++
if (counter >= numUpdates) {
call.cancel("", null)
}
}
override fun onError(t: Throwable) {
println("onError $t")
job.cancel()
}
override fun onCompleted() {
println("onCompleted")
job.cancel()
}
}
val requestObserver = ClientCalls.asyncBidiStreamingCall(call, responseObserver)
requestObserver.onNext(GetStatusUpdatesRequest.newBuilder().setName(name).build())
requestObserver.onCompleted()
job.join()
}
}
fun printStatusUpdatesWithManualFlowControl(name: String, numUpdates: Int = 5) {
runBlocking {
println("Getting some status updatesโฆ")
val job = Job()
val call = channel.newCall(CoffeeMachineGrpc.getGetStatusUpdatesMethod(), CallOptions.DEFAULT)
val listener = object : ClientCall.Listener<GetStatusUpdatesResponse>() {
private var counter = 0
override fun onReady() {
println("onReady")
}
override fun onMessage(message: GetStatusUpdatesResponse) {
println("Got status update: ${message.message}")
counter++
if (counter >= numUpdates) {
closeEverything()
} else {
call.request(1)
}
}
override fun onHeaders(headers: Metadata) {
println("onReady")
}
override fun onClose(status: Status, trailers: Metadata) {
println("onClose, status = $status")
}
private fun closeEverything() {
call.cancel("", null)
job.cancel()
}
}
call.start(listener, Metadata())
call.sendMessage(GetStatusUpdatesRequest.newBuilder().setName(name).build())
call.halfClose()
call.request(1)
job.join()
}
}
}
fun main() {
val channelToCoffeeMachine = ManagedChannelBuilder.forAddress("localhost", 50051)
.usePlaintext()
.build()
val coffeeDrinker = CoffeeDrinker(channelToCoffeeMachine)
coffeeDrinker.ping()
println()
coffeeDrinker.giveMeMy(Product.CAPPUCCINO)
println()
coffeeDrinker.printOnlyCappuccinosFromHistory()
println()
coffeeDrinker.printStatusUpdates("Max Mustermann")
channelToCoffeeMachine.shutdown().awaitTermination(10, SECONDS)
}
|
package io.craigmiller160.stockmarket;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import io.craigmiller160.mvp.core.AbstractPropertyModel;
import io.craigmiller160.mvp.core.PropertyChangeView;
import io.craigmiller160.stockmarket.controller.StockMarketController;
/**
* Performs post-processing initialization actions on the controller
* for this program. Primarily focused on adding all views/models to
* the controller for it to manage at runtime.
* <p>
* <b>DEPRECATED</b>: As of Version 2.3, this class has been deprecated
* in favor of <tt>GuiPostProcessor</tt> and <tt>ModelPostProcessor</tt>.
*
* @author craig
* @version 2.1
*/
@Deprecated
public class InitPostProcessor implements BeanPostProcessor, ApplicationContextAware {
/**
* The <tt>ApplicationContext</tt> object, used to access the Spring container
* during post-processing.
*/
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//If bean is controller, add models and views to it.
if(bean instanceof StockMarketController){
StockMarketController controller = (StockMarketController) bean;
controller.addPropertyModel((AbstractPropertyModel) context.getBean("guiStateModel"));
controller.addPropertyModel((AbstractPropertyModel) context.getBean("stockDisplayModel"));
controller.addView((PropertyChangeView) context.getBean("frame"));
controller.addView((PropertyChangeView) context.getBean("menuBar"));
controller.addView((PropertyChangeView) context.getBean("toolBar"));
controller.addView((PropertyChangeView) context.getBean("portfolioPanel"));
controller.addView((PropertyChangeView) context.getBean("stockDisplayPanel"));
controller.addView((PropertyChangeView) context.getBean("searchPanel"));
controller.addView((PropertyChangeView) context.getBean("buySellPanel"));
controller.addView((PropertyChangeView) context.getBean("stockDetailsPanel"));
controller.addView((PropertyChangeView) context.getBean("stockHistoryPanel"));
}
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
|
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osg/Hint>
#include <osg/StateSet>
using namespace osg;
void Hint::apply(State& /*state*/) const
{
if (_target==GL_NONE || _mode==GL_NONE) return;
glHint(_target, _mode);
}
void Hint::setTarget(GLenum target)
{
if (_target==target) return;
if (_parents.empty())
{
_target = target;
return;
}
// take a reference to this clip plane to prevent it from going out of scope
// when we remove it temporarily from its parents.
osg::ref_ptr<Hint> hintRef = this;
// copy the parents as they _parents list will be changed by the subsequent removeAttributes.
ParentList parents = _parents;
// remove this attribute from its parents as its position is being changed
// and would no longer be valid.
ParentList::iterator itr;
for(itr = parents.begin();
itr != parents.end();
++itr)
{
osg::StateSet* stateset = *itr;
stateset->removeAttribute(this);
}
// assign the hint target
_target = target;
// add this attribute back into its original parents with its new position
for(itr = parents.begin();
itr != parents.end();
++itr)
{
osg::StateSet* stateset = *itr;
stateset->setAttribute(this);
}
}
|
๏ปฟusing UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class Carrier : MonoBehaviour
{
public CarriableObject Carrying;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (!Carrying)
Carrying = GetComponentInChildren<CarriableObject>();
if (Carrying && ! Carrying.Carrier)
{
var carryObj = Carrying;
Carrying = null;
carryObj.AttachTo(this);
}
}
void Attach()
{
}
public void Release()
{
if (Carrying)
Carrying.Detach();
}
}
|
#!/bin/bash
(
set -x
set -e
this_script="$(readlink -e "${BASH_SOURCE[0]}")"
this_script_dir="$(dirname "${this_script}")"
workspace_dir="${this_script_dir}/workspace"
# Setup the workspace/ directory
(cd "$workspace_dir"
rm -rf ./{*,.venv}
)
)
|
#include "MidiSessionALSA.hh"
#include "CliComm.hh"
#include "MidiOutDevice.hh"
#include "PlugException.hh"
#include "PluggingController.hh"
#include "serialize.hh"
#include <iostream>
#include <memory>
namespace openmsx {
// MidiOutALSA ==============================================================
class MidiOutALSA final : public MidiOutDevice {
public:
MidiOutALSA(
snd_seq_t& seq,
snd_seq_client_info_t& cinfo, snd_seq_port_info_t& pinfo);
~MidiOutALSA() override;
// Pluggable
void plugHelper(Connector& connector, EmuTime::param time) override;
void unplugHelper(EmuTime::param time) override;
const std::string& getName() const override;
std::string_view getDescription() const override;
// MidiOutDevice
void recvMessage(
const std::vector<uint8_t>& message, EmuTime::param time) override;
template<typename Archive>
void serialize(Archive& ar, unsigned version);
private:
void connect();
void disconnect();
snd_seq_t& seq;
snd_midi_event_t* event_parser;
int sourcePort;
int destClient;
int destPort;
std::string name;
std::string desc;
bool connected;
};
MidiOutALSA::MidiOutALSA(
snd_seq_t& seq_,
snd_seq_client_info_t& cinfo, snd_seq_port_info_t& pinfo)
: seq(seq_)
, sourcePort(-1)
, destClient(snd_seq_port_info_get_client(&pinfo))
, destPort(snd_seq_port_info_get_port(&pinfo))
, name(snd_seq_client_info_get_name(&cinfo))
, desc(snd_seq_port_info_get_name(&pinfo))
, connected(false)
{
}
MidiOutALSA::~MidiOutALSA() {
if (connected) {
disconnect();
}
}
void MidiOutALSA::plugHelper(Connector& /*connector_*/, EmuTime::param /*time*/)
{
connect();
}
void MidiOutALSA::unplugHelper(EmuTime::param /*time*/)
{
disconnect();
}
void MidiOutALSA::connect()
{
sourcePort = snd_seq_create_simple_port(
&seq, "MIDI out pluggable",
0, SND_SEQ_PORT_TYPE_MIDI_GENERIC);
if (sourcePort < 0) {
throw PlugException(
"Failed to create ALSA port: ", snd_strerror(sourcePort));
}
int err = snd_seq_connect_to(&seq, sourcePort, destClient, destPort);
if (err) {
snd_seq_delete_simple_port(&seq, sourcePort);
throw PlugException(
"Failed to connect to ALSA port "
"(", destClient, ':', destPort, ")"
": ", snd_strerror(err));
}
snd_midi_event_new(MAX_MESSAGE_SIZE, &event_parser);
connected = true;
}
void MidiOutALSA::disconnect()
{
snd_midi_event_free(event_parser);
snd_seq_disconnect_to(&seq, sourcePort, destClient, destPort);
snd_seq_delete_simple_port(&seq, sourcePort);
connected = false;
}
const std::string& MidiOutALSA::getName() const
{
return name;
}
std::string_view MidiOutALSA::getDescription() const
{
return desc;
}
void MidiOutALSA::recvMessage(
const std::vector<uint8_t>& message, EmuTime::param /*time*/)
{
snd_seq_event_t ev;
snd_seq_ev_clear(&ev);
// Set routing.
snd_seq_ev_set_source(&ev, sourcePort);
snd_seq_ev_set_subs(&ev);
// Set message.
long encodeLen = snd_midi_event_encode(
event_parser, message.data(), message.size(), &ev);
if (encodeLen < 0) {
std::cerr << "Error encoding MIDI message of type "
<< std::hex << int(message[0]) << std::dec
<< ": " << snd_strerror(encodeLen) << '\n';
return;
}
if (ev.type == SND_SEQ_EVENT_NONE) {
std::cerr << "Incomplete MIDI message of type "
<< std::hex << int(message[0]) << std::dec << '\n';
return;
}
// Send event.
snd_seq_ev_set_direct(&ev);
int err = snd_seq_event_output(&seq, &ev);
if (err < 0) {
std::cerr << "Error sending MIDI event: "
<< snd_strerror(err) << '\n';
}
snd_seq_drain_output(&seq);
}
template<typename Archive>
void MidiOutALSA::serialize(Archive& ar, unsigned /*version*/)
{
if (ar.isLoader()) {
connect();
}
}
INSTANTIATE_SERIALIZE_METHODS(MidiOutALSA);
REGISTER_POLYMORPHIC_INITIALIZER(Pluggable, MidiOutALSA, "MidiOutALSA");
// MidiSessionALSA ==========================================================
std::unique_ptr<MidiSessionALSA> MidiSessionALSA::instance;
void MidiSessionALSA::registerAll(
PluggingController& controller, CliComm& cliComm)
{
if (!instance) {
// Open the sequencer.
snd_seq_t* seq;
int err = snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0);
if (err < 0) {
cliComm.printError(
"Could not open sequencer: ", snd_strerror(err));
return;
}
snd_seq_set_client_name(seq, "openMSX");
instance.reset(new MidiSessionALSA(*seq));
}
instance->scanClients(controller);
}
MidiSessionALSA::MidiSessionALSA(snd_seq_t& seq_)
: seq(seq_)
{
}
MidiSessionALSA::~MidiSessionALSA()
{
// While the Pluggables still have a copy of this pointer, they won't
// be accessing it anymore when openMSX is exiting.
snd_seq_close(&seq);
}
void MidiSessionALSA::scanClients(PluggingController& controller)
{
// Iterate through all clients.
snd_seq_client_info_t* cinfo;
snd_seq_client_info_alloca(&cinfo);
snd_seq_client_info_set_client(cinfo, -1);
while (snd_seq_query_next_client(&seq, cinfo) >= 0) {
int client = snd_seq_client_info_get_client(cinfo);
if (client == SND_SEQ_CLIENT_SYSTEM) {
continue;
}
// TODO: When there is more than one usable port per client,
// register them as separate pluggables.
snd_seq_port_info_t* pinfo;
snd_seq_port_info_alloca(&pinfo);
snd_seq_port_info_set_client(pinfo, client);
snd_seq_port_info_set_port(pinfo, -1);
while (snd_seq_query_next_port(&seq, pinfo) >= 0) {
unsigned int type = snd_seq_port_info_get_type(pinfo);
if (!(type & SND_SEQ_PORT_TYPE_MIDI_GENERIC)) {
continue;
}
constexpr unsigned int wrcaps =
SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE;
if ((snd_seq_port_info_get_capability(pinfo) & wrcaps) == wrcaps) {
controller.registerPluggable(std::make_unique<MidiOutALSA>(
seq, *cinfo, *pinfo
));
}
}
}
}
} // namespace openmsx
|
/*
* Written and Developed by Inuwa Ibrahim - https://linktr.ee/Ibrajix
* All rights reserved
*/
package com.ibrajix.eplfootball.network
import javax.inject.Inject
class ApiDataSource @Inject constructor(private val apiService: ApiService) {
//get premier league teams
suspend fun getPremierLeagueTeams() = apiService.getPremierLeagueTeams()
//get premier league team players
suspend fun getPremierLeagueTeamPlayers(id: String) = apiService.getPremierLeagueTeamPlayers(id)
}
|
package com.github.njhu.njcloudreader.Bean
class Banner(val desc: String, val id:String, val imagePath: String,
val isVisible: String, val order:String, val title: String,
val type: String, val url:String
)
|
val maven_group: String by project
val mod_version: String by project
val archives_base_name: String by project
val minecraft_version: String by project
val yarn_mappings: String by project
val loader_version: String by project
val fabric_version: String by project
val common = project(":MCAPI-common")
plugins {
id("fabric-loom") version "0.2.6-SNAPSHOT"
`maven-publish`
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
base {
archivesBaseName = archives_base_name
}
group = maven_group
version = mod_version
repositories {
mavenLocal()
maven(url = "http://maven.fabricmc.net") {
name = "Fabric"
}
}
minecraft {
}
dependencies {
//to change the versions see the gradle.properties file
minecraft("com.mojang:minecraft:${minecraft_version}")
mappings("net.fabricmc:yarn:${yarn_mappings}:v2")
modCompile("net.fabricmc:fabric-loader:${loader_version}")
// Fabric API. This is technically optional, but you probably want it anyway.
modCompile("net.fabricmc.fabric-api:fabric-api:${fabric_version}")
compile(common)
// PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs.
// You may need to force-disable transitiveness on them.
testCompile("junit:junit:4.12")
}
tasks.getByName<ProcessResources>("processResources") {
filesMatching("fabric.mod.json") {
expand(
mutableMapOf("version" to version)
)
}
}
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this task, sources will not be generated.
val sourcesJar = tasks.create<Jar>("sourcesJar") {
archiveClassifier.set("sources")
from(sourceSets["main"].allSource)
}
val buildFinal = tasks.create<Zip>("buildFinal") {
from(zipTree((common.tasks.get("jar") as Jar).archiveFile))
from(zipTree((tasks.get("remapJar") as Zip).archiveFile))
archiveFileName.set("$archives_base_name-$mod_version.jar")
destinationDirectory.set(file("$buildDir/dist"))
}
buildFinal.dependsOn("remapJar")
tasks.get("build").dependsOn(buildFinal)
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The vector package implements an efficient container for managing
// linear arrays of elements. Unlike arrays, vectors can change size dynamically.
package vector
// Element is an empty-interface object representing the contents of
// a cell in the vector.
type Element interface{}
// Vector is the container itself.
// The zero value for Vector is an empty vector ready to use.
type Vector struct {
a []Element;
}
func copy(dst, src []Element) {
for i := 0; i < len(src); i++ {
dst[i] = src[i];
}
}
// Insert n elements at position i.
func expand(a []Element, i, n int) []Element {
// make sure we have enough space
len0 := len(a);
len1 := len0+n;
if len1 < cap(a) {
// enough space - just expand
a = a[0:len1];
} else {
// not enough space - double capacity
capb := cap(a)*2;
if capb < len1 {
// still not enough - use required length
capb = len1;
}
// capb >= len1
b := make([]Element, len1, capb);
copy(b, a);
a = b;
}
// make a hole
for j := len0-1; j >= i; j-- {
a[j+n] = a[j];
}
return a;
}
// Init initializes a new or resized vector. The initial_len may be <= 0 to
// request a default length. If initial_len is shorter than the current
// length of the Vector, trailing elements of the Vector will be cleared.
func (p *Vector) Init(initial_len int) *Vector {
a := p.a;
if cap(a) == 0 || cap(a) < initial_len {
n := 8; // initial capacity
if initial_len > n {
n = initial_len;
}
a = make([]Element, n);
} else {
// nil out entries
for j := len(a)-1; j >= 0; j-- {
a[j] = nil;
}
}
p.a = a[0 : initial_len];
return p;
}
// New returns an initialized new Vector with length at least len.
func New(len int) *Vector {
return new(Vector).Init(len);
}
// Len returns the number of elements in the vector.
// Len is 0 if p == nil.
func (p *Vector) Len() int {
if p == nil {
return 0;
}
return len(p.a);
}
// At returns the i'th element of the vector.
func (p *Vector) At(i int) Element {
return p.a[i];
}
// Set sets the i'th element of the vector to value x.
func (p *Vector) Set(i int, x Element) {
p.a[i] = x;
}
// Last returns the element in the vector of highest index.
func (p *Vector) Last() Element {
return p.a[len(p.a)-1];
}
// Data returns all the elements as a slice.
func (p *Vector) Data() []Element {
arr := make([]Element, p.Len());
for i, v := range p.a {
arr[i] = v;
}
return arr;
}
// Insert inserts into the vector an element of value x before
// the current element at index i.
func (p *Vector) Insert(i int, x Element) {
p.a = expand(p.a, i, 1);
p.a[i] = x;
}
// Delete deletes the i'th element of the vector. The gap is closed so the old
// element at index i+1 has index i afterwards.
func (p *Vector) Delete(i int) {
a := p.a;
n := len(a);
copy(a[i : n-1], a[i+1 : n]);
a[n-1] = nil; // support GC, nil out entry
p.a = a[0 : n-1];
}
// InsertVector inserts into the vector the contents of the Vector
// x such that the 0th element of x appears at index i after insertion.
func (p *Vector) InsertVector(i int, x *Vector) {
p.a = expand(p.a, i, len(x.a));
copy(p.a[i : i+len(x.a)], x.a);
}
// Cut deletes elements i through j-1, inclusive.
func (p *Vector) Cut(i, j int) {
a := p.a;
n := len(a);
m := n-(j-i);
copy(a[i:m], a[j:n]);
for k := m; k < n; k++ {
a[k] = nil; // support GC, nil out entries
}
p.a = a[0:m];
}
// Slice returns a new Vector by slicing the old one to extract slice [i:j].
// The elements are copied. The original vector is unchanged.
func (p *Vector) Slice(i, j int) *Vector {
s := New(j-i); // will fail in Init() if j < j
copy(s.a, p.a[i:j]);
return s;
}
// Do calls function f for each element of the vector, in order.
// The function should not change the indexing of the vector underfoot.
func (p *Vector) Do(f func(elem Element)) {
for i := 0; i < len(p.a); i++ {
f(p.a[i]); // not too safe if f changes the Vector
}
}
// Convenience wrappers
// Push appends x to the end of the vector.
func (p *Vector) Push(x Element) {
p.Insert(len(p.a), x);
}
// Pop deletes the last element of the vector.
func (p *Vector) Pop() Element {
i := len(p.a)-1;
x := p.a[i];
p.a[i] = nil; // support GC, nil out entry
p.a = p.a[0:i];
return x;
}
// AppendVector appends the entire Vector x to the end of this vector.
func (p *Vector) AppendVector(x *Vector) {
p.InsertVector(len(p.a), x);
}
// Partial sort.Interface support
// LessInterface provides partial support of the sort.Interface.
type LessInterface interface {
Less(y Element) bool;
}
// Less returns a boolean denoting whether the i'th element is less than the j'th element.
func (p *Vector) Less(i, j int) bool {
return p.a[i].(LessInterface).Less(p.a[j]);
}
// Swap exchanges the elements at indexes i and j.
func (p *Vector) Swap(i, j int) {
a := p.a;
a[i], a[j] = a[j], a[i];
}
// Iterate over all elements; driver for range
func (p *Vector) iterate(c chan<- Element) {
for _, v := range p.a {
c <- v;
}
close(c);
}
// Channel iterator for range.
func (p *Vector) Iter() <-chan Element {
c := make(chan Element);
go p.iterate(c);
return c;
}
|
pub mod error;
pub mod arg;
pub mod buffer;
pub mod tube;
pub mod process;
pub mod remote;
|
<?php
namespace app\modules\v1\controllers;
use tests\RedirectTest;
use yii\rest\Controller;
use yii\base\Event;
use app\models\TournamentToUser;
use app\models\Tournament;
use app\models\Fight;
use app\models\Score;
use app\models\User;
use app\models\IntermediateScore;
use app\modules\v1\helpers\TournamentHelper;
use app\helpers\TournamentStatusHelper;
use yii\web\NotFoundHttpException;
use yii\web\NotAcceptableHttpException;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;
use Yii;
class TournamentController extends Controller
{
private $tournametModel;
private $scoreModel;
private $fightModel;
private $userModel;
private $intermediateScoreModel;
private $tournamentHelper;
public $active = false;
public function init()
{
$this->tournamentHelper = new TournamentHelper();
$this->scoreModel = new Score();
$this->tournametModel = new Tournament();
$this->fightModel = new Fight();
$this->userModel = new User();
$this->intermediateScoreModel = new IntermediateScore();
}
public function actionTournaments()
{
$tournaments = $this->tournametModel->getTournaments();
return [
'tournaments' => $tournaments
];
}
public function actionTournament($tournamentId)
{
$tournament = $this->tournametModel->getTournament($tournamentId);
if (!$tournament) {
throw new NotFoundHttpException('Tournament not found');
}
return [
'tournament' => $tournament
];
}
public function actionStart($tournamentId)
{
$request = Yii::$app->request;
$type = $request->getBodyParam('type');
$type = isset($type) ? $type : 'bo1';
if (!$this->tournamentHelper->validateFightType($type)) {
throw new NotAcceptableHttpException('Type should be bo1, bo3, bo5 or bo7');
}
$tournament = $this->tournametModel->getTournament($tournamentId);
$userList = TournamentToUser::getUserList($tournamentId);
if (!$tournament) {
throw new NotFoundHttpException('Tournament not found');
}
if ($tournament->status !== TournamentStatusHelper::$waiting) {
throw new NotAcceptableHttpException('Tournament already started');
}
if ($tournament->players_count !== count($userList)) {
throw new NotAcceptableHttpException('Wrong players number');
}
if ($tournament->start()) {
$pairs = $this->tournamentHelper->getPairs($userList);
foreach ($pairs as $key => $pair) {
$score = new Score();
$fight = new Fight();
$scoreId = $score->create();
$isFightSaved = $fight->createFight($pair[0], $pair[1], $tournamentId, $key + 1, $scoreId, $type);
if (!$isFightSaved) {
$tournament->allow();
$score->delete();
return ['errors' => $fight->errors];
}
}
return ['pairs' => $pairs];
} else {
return ['errors' => $tournament->errors];
}
}
public function actionBrackets($tournamentId)
{
$tournament = $this->tournametModel->getTournament($tournamentId);
if (!$tournament) {
throw new NotFoundHttpException('Tournament not found');
}
$size = $tournament->players_count;
$fights = $this->fightModel->getTournamentFights($tournamentId);
$teams = [];
$scores = [];
for ($i = 0; $i < $size / 2; $i++) {
$fight = $fights[$i];
$teams[] = $this->userModel->getUsername($fight->first_user_id);
$teams[] = $this->userModel->getUsername($fight->second_user_id);
}
foreach ($fights as $fight) {
$scores[] = $this->scoreModel->getScore($fight->score_id);
}
return $this->tournamentHelper->buildBracket($teams, $scores);
}
public function actionUpdateFightStatus($tournamentId, $fightId)
{
$request = Yii::$app->request;
$fight = $this->fightModel->getFightById($fightId);
if ($fight->status == Fight::$status['finished']) {
throw new NotAcceptableHttpException('Fight already finished');
}
$firstStatus = $request->getBodyParam('firstStatus');
if (!$firstStatus) $firstStatus = IntermediateScore::$status['unset'];
$secondStatus = $request->getBodyParam('secondStatus');
if (!$secondStatus) $secondStatus = IntermediateScore::$status['unset'];
$updateStatus = $this->intermediateScoreModel->updateStatuses($fightId, $firstStatus, $secondStatus);
if (!$updateStatus) {
throw new BadRequestHttpException('Bad request');
}
$status = $this->intermediateScoreModel->getByFight($fightId);
$score = $this->scoreModel->getScore($fight->score_id);
$result = $this->tournamentHelper->getUpdatedResult($score, $status);
$scoreStatus = true;
if (!$status->active) {
$scoreStatus = $this->scoreModel->updateScore($fight->score_id, $result[0], $result[1]);
}
$this->fightModel->updateFightStatus($fight->id);
$firstUserScore = $fight->score->first_user_score;
$secondUserScore = $fight->score->second_user_score;
$type = $fight->type;
if ($firstUserScore != Fight::maxGamesByBO($type) && $secondUserScore != Fight::maxGamesByBO($type)) {
$updateActive = $this->intermediateScoreModel->updateActive($fightId);
if (!$updateActive) {
throw new BadRequestHttpException('Bad request(bo)');
}
}
return [
'status' => $status,
'result' => $result,
'scoreStatus' => $scoreStatus
];
}
public function actionUpdateScore($tournamentId, $fightId)
{
$request = Yii::$app->request;
$fight = $this->fightModel->getFightById($fightId);
if ($fight->status == Fight::$status['finished']) {
throw new NotAcceptableHttpException('Fight already finished');
}
$first = $request->getBodyParam('first');
$second = $request->getBodyParam('second');
$this->scoreModel->updateScore($fight->score_id, $first, $second);
$score = $this->scoreModel->getScore($fight->score_id);
return [
'score' => $score
];
}
}
|
{-# LANGUAGE OverloadedStrings #-}
module Poker.History.Base where
import Control.Monad.Identity
import Data.Text (Text)
import qualified Data.Text as T
import Data.Void
import Poker
import Poker.History.Types
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
import Text.Printf (printf)
type Parser a = ParsecT Void Text Identity a
-- | default space consumer
sc :: MonadParsec Void Text m => m ()
sc = L.space space1 empty empty
-- | default space consuming lexeme
lexeme :: MonadParsec Void Text m => m a -> m a
lexeme = L.lexeme sc
lexeme_ :: MonadParsec Void Text m => m a -> m ()
lexeme_ = void . lexeme
string_ :: MonadParsec Void Text m => Text -> m ()
string_ = void . string
integer :: MonadParsec Void Text m => m Int
integer = L.decimal <?> "integer"
rational :: MonadParsec Void Text m => m Rational
rational = toRational <$> L.scientific <?> "rational"
try_ :: MonadParsec Void Text m => m a -> m ()
try_ = void . try
optional_ :: MonadParsec Void Text m => m a -> m ()
optional_ = void . optional
symbol :: MonadParsec Void Text m => Text -> m Text
symbol = L.symbol sc
symbol_ :: MonadParsec Void Text m => Text -> m ()
symbol_ = void . symbol
parens,
braces,
angles,
brackets,
singleQuotes ::
MonadParsec Void Text m => m a -> m a
parens = between (symbol "(") (symbol ")")
braces = between (symbol "{") (symbol "}")
angles = between (symbol "<") (symbol ">")
brackets = between (symbol "[") (symbol "]")
singleQuotes = between (symbol "'") (symbol "'")
semicolon, comma, colon, dot, fwdSlash, dash :: MonadParsec Void Text m => m Text
semicolon = symbol ";"
comma = symbol ","
colon = symbol ":"
dot = symbol "."
fwdSlash = symbol "/"
dash = string "-"
pCurrency :: MonadParsec Void Text m => m SomeCurr
pCurrency =
anySingle >>= \case
'$' -> pure $ SomeCurr USD
'โฌ' -> pure $ SomeCurr EUR
'ยฃ' -> pure $ SomeCurr GBP
_ -> empty <?> "currency"
pCard :: MonadParsec Void Text m => m Card
pCard = maybe empty pure . cardFromShortTxt =<< takeP (Just "Card Token") 2
eol_ :: MonadParsec e Text m => m ()
eol_ = void eol
line_ :: MonadParsec Void Text m => m a -> m ()
line_ = (>> eol_)
line :: MonadParsec Void Text m => m a -> m a
line = (<* eol_)
-- | Match a specified number of cards. If the number of cards found is not equal
-- to the given number expected, this 'Parser' fails.
--
-- Note that this 'Parser' is greedy - it will match as many 'Card's as it can,
-- not up until the number specified.
countCard :: MonadParsec Void Text m => Int -> m () -> m [Card]
countCard num pBetween = do
cards <- try pCard `sepEndBy` pBetween <?> "Multiple Cards"
if length cards /= num
then empty <?> printf "Expected %d cards, but found %d" num (length cards)
else pure cards
pAmount :: MonadParsec Void Text m => m SomeBetSize
pAmount =
lexeme
( pCurrency >>= \case
SomeCurr curr -> SomeBetSize curr <$> rational
)
lineEndedBy :: (MonadParsec e Text m) => Text -> m Text
lineEndedBy suffix = do
(T.pack -> lineTxt) <- many (notFollowedBy eol *> anySingle)
guard $ suffix `T.isSuffixOf` lineTxt
eol_
pure lineTxt
|
# TODO This file is going away, but we need it temporarily for compatibility with the integration scaffolder.
# ๐
super scaffolding will insert new oauth providers above this line.
def any_oauth_enabled?
[
stripe_enabled?,
# ๐
super scaffolding will insert new oauth provider checks above this line.
].select(&:present?).any?
end
|
๏ปฟnamespace Disqord
{
public static class LocalNestedComponentExtensions
{
public static TComponent WithIsDisabled<TComponent>(this TComponent component, bool isDisabled = true)
where TComponent : LocalNestedComponent
{
component.IsDisabled = isDisabled;
return component;
}
}
}
|
@using StartupCreativeAgency.Web.RazorPages.Areas.Admin
@using StartupCreativeAgency.Web.RazorPages.Infrastructure
@using StartupCreativeAgency.Web.RazorPages.Areas.Admin.ViewModels
@using StartupCreativeAgency.Domain.Entities
@namespace StartupCreativeAgency.Web.RazorPages.Areas.Admin.Pages
@addTagHelper StartupCreativeAgency.Web.RazorPages.Infrastructure.*, Web.RazorPages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
---
title: KataLientesS
affiliatelink: "https://www.katalientess.com"
imageName: seoKatalientess
credits: Biggest React Project
---
The largest React project I have created on my own.
|
# How-detect-robots-and-spiders-with-PHP
How-detect-robots-and-spiders-with-PHP
Here is the simple function for detecting spiders and robots. It will return true or false.
<pre>
function is_bot(){
$bots = array(
'Googlebot',
'Baiduspider',
'ia_archiver',
'R6_FeedFetcher',
'NetcraftSurveyAgent',
'Sogou web spider',
'bingbot',
'Yahoo! Slurp',
'facebookexternalhit',
'PrintfulBot',
'msnbot',
'Twitterbot',
'UnwindFetchor',
'urlresolver',
'Butterfly',
'TweetmemeBot');
foreach($bots as $b){
if( stripos( $_SERVER['HTTP_USER_AGENT'], $b ) !== false ) return true;
}
return false;
}
<pre>
|
package fi.riista.common.network
import fi.riista.common.RiistaSdkConfiguration
import io.ktor.client.*
import io.ktor.client.features.cookies.*
import io.ktor.client.request.*
internal expect class HttpClientProvider() {
fun getConfiguredHttpClient(sdkConfiguration: RiistaSdkConfiguration,
cookiesStorage: CookiesStorage): HttpClient
}
@Suppress("unused") // having HttpClientProvider as receiver provides better scoping
internal fun HttpClientProvider.configureDefaultRequest(
requestBuilder: HttpRequestBuilder,
sdkConfiguration: RiistaSdkConfiguration
) {
requestBuilder.header("mobileClientVersion", sdkConfiguration.versionInfo.appVersion)
requestBuilder.header("platform", sdkConfiguration.platform.name.platformNameString)
requestBuilder.header("device", sdkConfiguration.device.name)
requestBuilder.header("osVersion", sdkConfiguration.device.osVersion)
}
|
# frozen_string_literal: true
module UsersHelper
def full_name(user)
[user.first_name, user.last_name].reject { |n| n.nil? or n.blank? }.join(' ')
end
def sortable_full_name(user)
[user.last_name, user.first_name].reject { |n| n.nil? or n.blank? }.join(', ')
end
end
|
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:square_connect/square_connect.dart';
part 'catalog_object.g.dart';
@JsonSerializable()
class CatalogObject extends Equatable {
const CatalogObject({
required this.type,
required this.id,
required this.updatedAt,
required this.version,
required this.isDeleted,
required this.presentAtAllLocations,
this.presentAtLocationIds,
this.absentAtLocationIds,
this.imageId,
this.itemData,
this.itemVariationData,
this.categoryData,
this.taxData,
this.discountData,
this.modifierListData,
this.modifierData,
this.imageData,
this.measurementUnitData,
// this.customAttributeDefinitionData,
// this.customAttributeValues,
// this.itemOptionData,
// this.itemOptionValueData,
// this.pricingRuleData,
// this.productSetData,
// this.quickAmountsSettingsData,
// this.subscriptionPlanData,
// this.timePeriodData,
});
/// Converts a [Map] to an [CatalogObject]
factory CatalogObject.fromJson(Map<String, dynamic> json) =>
_$CatalogObjectFromJson(json);
/// Converts a [CatalogObject] to a [Map]
Map<String, dynamic> toJson() => _$CatalogObjectToJson(this);
final String id;
final CatalogObjectType type;
final DateTime updatedAt;
final int version;
final bool isDeleted;
final bool presentAtAllLocations;
final List<String>? presentAtLocationIds;
final List<String>? absentAtLocationIds;
final String? imageId;
final CatalogItem? itemData;
final CatalogItemVariation? itemVariationData;
final CatalogCategory? categoryData;
final CatalogTax? taxData;
final CatalogDiscount? discountData;
final CatalogModifierList? modifierListData;
final CatalogModifier? modifierData;
final CatalogImage? imageData;
final CatalogMeasurementUnit? measurementUnitData;
// final CatalogCustomAttributeDefinition? customAttributeDefinitionData;
// final Map<String, CatalogCustomAttributeValue>? customAttributeValues;
// final CatalogItemOption? itemOptionData;
// final CatalogItemOptionValue? itemOptionValueData;
// final CatalogPricingRule? pricingRuleData;
// final CatalogProductSet? productSetData;
// final CatalogQuickAmountsSettings? quickAmountsSettingsData;
// final CatalogSubscriptionPlan? subscriptionPlanData;
// final CatalogTimePeriod? timePeriodData;
@override
List<Object?> get props {
return [
type,
id,
updatedAt,
version,
isDeleted,
presentAtAllLocations,
presentAtLocationIds,
absentAtLocationIds,
imageId,
itemData,
itemVariationData,
categoryData,
taxData,
discountData,
modifierListData,
modifierData,
imageData,
measurementUnitData,
// customAttributeDefinitionData,
// customAttributeValues,
// itemOptionData,
// itemOptionValueData,
// pricingRuleData,
// productSetData,
// quickAmountsSettingsData,
// subscriptionPlanData,
// timePeriodData,
];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.